本文共 2138 字,大约阅读时间需要 7 分钟。
spring-boot建议orm采用JPA,因为jpa符合spring-boot简化配置理念。但是最近在使用jpa的过程中各种不爽,特别是多表联合查询的时候,也可能是我对jpa还没深入。由于个人经历,mybatis使用较多,现整合spring-boot和mybatis。
按照约定,其实spring-boot整合mybatis非常简单,只需要加一个mybatis.mapper-locations
配置项标明mybatis的xml映射文件在哪,mybatis接口加上@Mapper
注解告诉spring的bean工厂,这是mybatis的mapper接口即可。 pom.xml
mysql mysql-connector-java ${mysql-connector.version} org.mybatis.spring.boot mybatis-spring-boot-starter ${mybatis-spring-boot.version}
application.properties
mybatis.mapper-locations=classpath:mapper/*.xml
该配置指明mybatis的xml映射文件位置。
@Mapper
@Mapperpublic interface CityBeanMapper { long countByExample(CityBeanExample example); int deleteByExample(CityBeanExample example); int deleteByPrimaryKey(Short cityId); int insert(CityBean record); int insertSelective(CityBean record); ListselectByExample(CityBeanExample example); CityBean selectByPrimaryKey(Short cityId); int updateByExampleSelective(@Param("record") CityBean record, @Param("example") CityBeanExample example); int updateByExample(@Param("record") CityBean record, @Param("example") CityBeanExample example); int updateByPrimaryKeySelective(CityBean record); int updateByPrimaryKey(CityBean record);}
mybatis接口层添加@Mapper注解,告诉spring的上下文管理器,自动把该接口实例化,并纳入spring上下文管理器中,以后使用的时候便可自动注入到需要的类中。
@Service(value = "cityService")public class CityServiceImpl implements CityService { @Autowired private CityBeanMapper cityBeanMapper; @Transactional public Boolean save(CityBean cityBean) { if (null == cityBean.getCityId()) { return cityBeanMapper.insert(cityBean)>0?true:false; }else{ return cityBeanMapper.updateByPrimaryKey(cityBean)>0?true:false; } } public CityBean findById(Short id) { return cityBeanMapper.selectByPrimaryKey(i); }}
使用mybatis的时候很多时候都是通过mybatis-generator自动生成mapper.xml、接口、model。示例工程中已经加入了相关的配置,可参考。
工程地址:
原文地址:转载地址:http://puvmb.baihongyu.com/