mybatis学习

入门案例:
在IDEA中新建了一个普通的java项目,加入jar包,工程结构如图。

mybatis学习_第1张图片
图片.png

log4j.properties(在控制台打印日志,方便查看)

# Global logging configuration

log4j.rootLogger=DEBUG, stdout

# Console output...

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

SqlMapConfig.xml(mybatis全局配置文件)




   
        
            
            
            
            
                
                
                
                
            
        
    

ItemsMapper.xml(映射文件,sql语句)






    
    

在sqlMapConfig.xml中加载User.xml

 
        
 

程序代码

Items.java

package po;

/**
 * Created by admin on 2017/7/1.
 */
public class Items {
    private int id;
    private String name;
    private double price;
    private String detail;

    @Override
    public String toString() {
        return "Items{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                ", detail='" + detail + '\'' +
                '}';
    }
//get/set方法省略
}

测试类Test.jav

package test;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import po.Items;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by admin on 2017/7/1.
 */
public class Test {


    @org.junit.Test
    public void test01() throws IOException {

        String path = "SqlMapConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(path);
        //创建会话工厂,传入mybatis配置文件的信息
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        // 通过工厂得到SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        Items list = sqlSession.selectOne("mapper.ItemsMapper.queryItemsById",1);
        System.out.println(list);
        sqlSession.close();

    }
}

查询结果

mybatis学习_第2张图片
图片.png

你可能感兴趣的:(mybatis学习)