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
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql-connector.version}</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis-spring-boot.version}</version> </dependencyapplication.properties
mybatis.mapper-locations=classpath:mapper/*.xml该配置指明mybatis的xml映射文件位置。
@Mapper
@Mapper public interface CityBeanMapper { long countByExample(CityBeanExample example); int deleteByExample(CityBeanExample example); int deleteByPrimaryKey(Short cityId); int insert(CityBean record); int insertSelective(CityBean record); List<CityBean> selectByExample(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上下文管理器中,以后使用的时候便可自动注入到需要的类中。
使用mybatis的时候很多时候都是通过mybatis-generator自动生成mapper.xml、接口、model。示例工程中已经加入了相关的配置,可参考。
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <properties resource="application.properties"/> <classPathEntry location="D:\\Java\\maven\\repository\\mysql\\mysql-connector-java\\5.1.39\\mysql-connector-java-5.1.39.jar" /> <context id="Mysql" targetRuntime="MyBatis3" defaultModelType="flat"> <commentGenerator> <!-- 关闭自动生成的注释 --> <property name="suppressAllComments" value="true" /> </commentGenerator> <jdbcConnection driverClass="${spring.datasource.driverClassName}" connectionURL="${spring.datasource.url}" userId="${spring.datasource.username}" password="${spring.datasource.password}"> </jdbcConnection> <javaModelGenerator targetPackage="com.itclj.model" targetProject="src/main/java"/> <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/> <javaClientGenerator targetPackage="com.itclj.dao" targetProject="src/main/java" type="XMLMAPPER"/> <table schema="sakila" tableName="city" domainObjectName="CityBean"></table> </context> </generatorConfiguration>工程地址:https://github.com/clj198606061111/spring-boot-mybatis-demo 原文地址:http://www.itclj.com/blog/58c62d9f47508f786718d4f5