一.mybatis給sqlSession指定sql方式:
mybatis里頭給sqlSession指定執行哪條sql的時候,有兩種方式,一種是寫mapper的xml的namespace+statementId,如下:
public Student findStudentById(Integer studId) { logger.debug("Select Student By ID :{}", studId); SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSession(); try { return sqlSession.selectOne("com.mybatis3.StudentMapper.findStudentById", studId); } finally { sqlSession.close(); } }
另外一種方法是指定mapper的接口:
public Student findStudentById(Integer studId) { logger.debug("Select Student By ID :{}", studId); SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSession(); try { StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); return studentMapper.findStudentById(studId); } finally { sqlSession.close(); } }
一般的話,比較推薦第二種方法,因為手工寫namespace和statementId極大增加了犯錯誤的概率,而且也降低了開發的效率。
二.mapper的實現類如何生成
如果使用mapper接口的方式,問題來了,這個是個接口,通過sqlSession對象get出來的一定是個實現類,問題是,我們並沒有手工去寫 實現類,那么誰去干了這件事情呢?答案是mybatis通過JDK的動態代理方式,在啟動加載配置文件時,根據配置mapper的xml去生成。
啟動時加載解析mapper的xml
如果不是集成spring的,會去讀取<mappers>節點,去加載mapper的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> <settings> <setting name="cacheEnabled" value="true"/> <setting name="lazyLoadingEnabled" value="true"/> <setting name="multipleResultSetsEnabled" value="true"/> <setting name="useColumnLabel" value="true"/> <setting name="useGeneratedKeys" value="false"/> <setting name="defaultExecutorType" value="SIMPLE"/> <setting name="defaultStatementTimeout" value="2"/> </settings> <typeAliases> <typeAlias alias="CommentInfo" type="com.xixicat.domain.CommentInfo"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/demo"/>