MyBatis(二)MyBatis入門程式(MyBatis demo)

z1340954953發表於2018-07-03

建立工程

工程原始碼下載


mybatis-config.xml

需要注意的是,定義元素的順序按照下面的順序定義


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 定義別名 -->
  <typeAliases>
  	<typeAlias alias="student" type="cn.bing.pojo.Student"/>
  </typeAliases>
  <environments default="development">
    <environment id="development">
      <!-- 採用JDBC的事務管理方式 -->
      <transactionManager type="JDBC">
      	<property name="autoCommit" value="false"/>
      </transactionManager>
      <!-- 配置資料庫的連結資訊 -->
      <dataSource type="POOLED">
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/test"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
      </dataSource>
    </environment>
  </environments>
  <!-- 定義對映器,引入的xml檔案的作用是,提供了SQL和SQL對POJO的對映規則定義,
       它包含了對映器裡面的資訊,Mybatis將會為我們解析這個xml生成對映器
   -->
  <mappers>
  	<mapper resource="cn\bing\mapper\StudentMapper.xml"/>
  </mappers>
</configuration>

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);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.bing.mapper.StudentMapper">
  <select id="queryStudentInfo" resultType="student">
    select stu_id as stuId,stu_age as stuAge,stu_sex as stuSex,stu_name as stuName 
    from student_info where stu_id = #{id}
  </select>
</mapper>

定義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();
	}
}







相關文章