myBatis系列之二:以接口方式交互数据

myBatis系列之一:搭建开发环境是采用SqlSession的通用方法并强制转换的方式,存在着转换安全的问题: 

Mybatis技术学习,更多知识请访问https://www.itkc8.com

Java代码  收藏代码

  1. User user = (User)session.selectOne("com.john.hbatis.model.UserMapper.getUserById"1);  



可以采用接口加sql语句的方式来解决,sql语句理解为是接口的实现: 

1. 新建接口类:

 

Java代码  收藏代码

  1. package com.john.hbatis.mapper;  
  2.   
  3. import com.john.hbatis.model.User;  
  4.   
  5. public interface IUserMapper {  
  6.     User getUserById(int id);  
  7. }  



2. 修改User.xml文件,确保namespace属性值和接口的全限定名相同,且id属性值和接口方法名相同:

 

Xml代码  收藏代码

  1. <mapper namespace="com.john.hbatis.mapper.IUserMapper">  
  2.     <select id="getUserById"  



3. 在MyBatisBasicTest类中添加测试方法:

 

Java代码  收藏代码

  1. @Test  
  2. public void queryInInterfaceWayTest() {  
  3.     SqlSession session = sqlSessionFactory.openSession();  
  4.     IUserMapper mapper = session.getMapper(IUserMapper.class); // 如果namespace和接口全限定名不一致,报org.apache.ibatis.binding.BindingException: Type interface com..IUserMapper is not known to the MapperRegistry异常。  
  5.     User user = mapper.getUserById(1);  
  6.     log.info("{}: {}", user.getName(), user.getAddress());  
  7. }  




附: 
上面的实现是把sql语句放在XML文件中,并通过一定的约束来保证接口能够在XML中找到对应的SQL语句; 
还有一种方式是通过接口+注解SQL方式来交互数据: 

①. 新建接口类:

 

Java代码  收藏代码

  1. package com.john.hbatis.mapper;  
  2.   
  3. import org.apache.ibatis.annotations.Select;  
  4.   
  5. import com.john.hbatis.model.User;  
  6.   
  7. public interface IUserMapper2 {  
  8.     @Select({ "select * from `user` where id = #{id}" })  
  9.     User getUserById(int id);  
  10. }  



②. 在Configuration.xml文件中加入:

 

Xml代码  收藏代码

  1. <mappers>  
  2.     <mapper class="com.john.hbatis.mapper.IUserMapper2" />  
  3. </mappers>  



或在初始化语句中加入: 

 

Java代码  收藏代码

  1. sqlSessionFactory.getConfiguration().addMapper(IUserMapper2.class);  



③. 相应修改上面的测试方法:

 

Java代码  收藏代码

  1. IUserMapper2 mapper = session.getMapper(IUserMapper2.class);  


Mybatis技术学习,更多知识请访问https://www.itkc8.com
参考: 
http://www.yihaomen.com/article/java/304.htm

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值