MyBatis(二)MyBatis入门程序(MyBatis demo)

建立工程

工程源码下载

MyBatis(二)MyBatis入门程序(MyBatis demo)_第1张图片

mybatis-config.xml

需要注意的是,定义元素的顺序按照下面的顺序定义






  
  	
  
  
    
      
      
      	
      
      
      
        
        
        
        
      
    
  
  
  
  	
  

StudentMapper.xml的路径是\分隔

获取SqlSessionFactory

因为只是用来获取sqlSession,需要多次调用,定义为单例的,节省对象的创建资源。

public class SqlFactoryUtil {
	private SqlFactoryUtil(){}
	private static final Class CLASS_LOCK = SqlFactoryUtil.class;
	private static SqlSessionFactory factory = null;
	public static SqlSessionFactory getSqlSessionFactory(){
		InputStream input = null;
		try {
			input = Resources.getResourceAsStream("mybatis-config.xml");
			synchronized (CLASS_LOCK) {
				if(factory==null){
					factory = new SqlSessionFactoryBuilder().build(input);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return factory;
	}
}

映射的pojo对象

定义为javaBean风格

public class Student {
	private Integer stuId;
	private Integer stuAge;
	private Integer stuSex;
	private String stuName;
	public Integer getStuId() {
		return stuId;
	}
	public void setStuId(Integer stuId) {
		this.stuId = stuId;
	}
	public Integer getStuAge() {
		return stuAge;
	}
	public void setStuAge(Integer stuAge) {
		this.stuAge = stuAge;
	}
	public Integer getStuSex() {
		return stuSex;
	}
	public void setStuSex(Integer stuSex) {
		this.stuSex = stuSex;
	}
	public String getStuName() {
		return stuName;
	}
	public void setStuName(String stuName) {
		this.stuName = stuName;
	}
}

定义StudentMapper.java 和StudentMapper.xml 

* 格式上要求文件同名,放在一个包下面

* SQL语句的查询字段的名称,必须和POJO的字段名一致,才能映射到对象上

* namespace的值是接口的全路径名

package cn.bing.mapper;

import cn.bing.pojo.Student;

public interface StudentMapper {
	public Student queryStudentInfo(int id);
}



  

定义log4j.properties,输出日志信息

log4j.rootLogger = DEBUG,stdout
log4j.logger.org.mybatis = DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p %d %C:%m%n

测试类,调用查询方法

SqlSessionFactory factory = SqlFactoryUtil.getSqlSessionFactory();
SqlSession session = null;
try{
	session = factory.openSession();
	StudentMapper mapper = (StudentMapper) session.getMapper(StudentMapper.class);
	Student st = mapper.queryStudentInfo(1);
	System.out.println(st.getStuName());
	session.commit();
}catch(Exception e){
	e.printStackTrace();
	session.rollback();
}finally{
	//确保资源被关闭
	if(session!=null){
		session.close();
	}
}







你可能感兴趣的:(MyBatis)