MyBatis接口式編程
一、原始方法:
1.編寫sql映射文件
<!-- sql映射文件 -->
<mapper namespace="org.test.example.ProductMapper">
<select id="selectProduct" resultType="mytest.dao.Product">
SELECT * FROM product p WHERE p.id = #{id};
</select>
</mapper>
2.通過sql映射文件中namespace和id屬性來定位Sql的位置炉旷,使用SqlSession對(duì)象的selectOne方法傳遞需要的參數(shù)arg并執(zhí)行指定位置的Sql語句。
public class MyBatisTest{
public void MyTest(){
String resource = "mybatis-config.xml";
IntputStream intputStream = Resources.getResourceAsStream();
SqlSessionFactory factory = newSqlSessionFactoryBuilder().bulid(intputStream);
SqlSession sqlSession = factory.openSession();
/** selectOne(String statement, Object parameter):
* statement :即sql映射文件中的namespace和id構(gòu)成:namespace.id
* parameter :傳遞給sql映射文件的值
*/
Product p = sqlSession.selectOne("org.test.example.ProductMapper.selectProduct", 1L);
}
}
該方法直接通過sql映射文件中namespace和id屬性來定位Sql的位置叉讥,要使用不同的方法砾跃,要改變id的值,看起來很不簡(jiǎn)潔节吮,不夠面向?qū)ο蟆?/p>
二、接口式編程
1.創(chuàng)建Mapper接口判耕,并定義一個(gè)getProductById方法透绩,用來通過id獲取product對(duì)象。
public interface ProductMapper {
Product getProductById(Long id);
}
2.sql映射文件中的namespace屬性為Mapper接口的全限定名,id為Mapper接口中對(duì)應(yīng)的方法
<!-- sql映射文件 -->
<mapper namespace="mytest.dao.ProductMapper">
<select id="getProductById" resultType="mytest.dao.Product">
SELECT * FROM product p WHERE p.id = #{id};
</select>
</mapper>
3.調(diào)用sqlSession對(duì)象中的getMapper(Class<T> type)方法來綁定Mapper接口,并獲取Mapper對(duì)象。Mapper對(duì)象擁有接口中的方法帚豪,可直接使用碳竟,例如:使用getProductById方法從數(shù)據(jù)庫中獲取 id= 1 的Product對(duì)象。
public class MyBatisTest{
public void MyTest(){
String resource = "mybatis-config.xml";
IntputStream intputStream = Resources.getResourceAsStream();
SqlSessionFactory factory = newSqlSessionFactoryBuilder().bulid(intputStream);
SqlSession sqlSession = factory.openSession();
/** getMapper(Class<T> type)
type: Mapper interface class.傳入Mapper接口class綁定接口
*/
ProductMapper mapper = sqlSession.getMapper(ProductMapper.class);
Product p = mapper.getProductById(1L);
}
}
總結(jié):比起原始方式狸臣,接口式編程的方法調(diào)用更加直觀莹桅,更加面向?qū)ο螅岣吡丝勺x性和可操作性烛亦。