》 實現思路:編寫Dao接口和實現類,在Dao接口中注入單例的SqlSessionFactory,經過SqlSessionFactory獲取SqlSession來獲取數據庫操做對象。》java
package com.ts.dao; import com.ts.domain.Users; public interface UsersDao { //根據ID查詢用戶信息 Users findUserById(int id) throws Exception; }
package com.ts.dao.impl; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import com.ts.dao.UsersDao; import com.ts.domain.Users; public class UsersDaoImpl implements UsersDao { private SqlSessionFactory sqlSessionFactory; //構造函數注入SqlSessionFactory public UsersDaoImpl(SqlSessionFactory sqlSessionFactory) { this.sqlSessionFactory =sqlSessionFactory; } /** * 1和3是模板代碼 * 1.SqlSession sqlSession = getSqlSession(); * 2.業務邏輯 * 3.sqlSession.close(); */ @Override public Users findUserById(int id) throws Exception { SqlSession sqlSession = sqlSessionFactory.openSession(); Users user = sqlSession.selectOne("Users.findUserById", id); sqlSession.close(); return user; }
缺點: 1.代碼冗餘,重複代碼不少。sql
2.根據Users.xmlMapper映射文件的id獲取SQL語句(Users.findUserById),硬編碼在Java代碼裏了。數據庫
3.調用SqlSession方法時,傳入的參數編譯期間不報錯,不能及時發現錯誤。(如:sqlSession.selectOne("Users.findUserById","123");apache
根據接口編寫規範:Mybatis能夠自動生成Mapper接口實現類的代理對象session
1.編寫UserMapper.java接口和UserMapper.xml的SQL映射文件app
package com.ts.dao; public interface UserMapper { public Users findUserById(int id) throws Exception; }
<mapper namespace="com.ts.dao.UserMapper"> <select id="findUserById" parameterType="int" resultType="com.ts.domain.Users"> select * from Users where id = #{id} </select> </mapper>
2.Mybatis自動生成代理實現類須要遵循的規範
dom
->Mapper.xml的namespace 和 mapper.xml接口全限定名一致( 觀察上面代碼 )ide
->Mapper.java接口中的方法名和mapper.xml中每一個SQL的ID一致函數
->Mapper.java接口中的輸入參數類型和mapper.xml中每一個SQL的輸入參數指定的類型一致測試
->Mapper.java接口中的返回值參數類型和mapper.xml中每一個SQL的返回值指定的類型一致
3.測試( 不要忘記把mapper.xml添加到SqlMapConfig.xml中)
package com.ts.dao.test; import java.io.IOException; import java.io.InputStream; 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 org.junit.Before; import org.junit.Test; import com.ts.dao.UserMapper; import com.ts.domain.Users; public class UserMapperTest { private static SqlSessionFactory sqlSessionFactory; @Before public void before() throws IOException{ //經過輸入流讀取全局配置信息建立工廠 String resource = "SqlMapConfig.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } @Test public void test() throws Exception { SqlSession sqlSession = sqlSessionFactory.openSession(); //生成代理實現類 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); Users user = userMapper.findUserById(1); //==>Users [id=1, name=田碩, sex=男, birth=Sat Apr 02 00:00:00 CST 2016, address=河南商丘] System.out.println(user); } }