經過一個小例子來實現Spring Boot 與MyBatis的整合。html
<!-- mybatis整合spring boot的starter --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
Spring Boot官方提供的starter是這樣的:spring-boot-starter-* 而其餘第三方提供的starter是這樣的:*-spring-boot-starterjava
public class Emp { private Long id; private String name; private Date birthday; private Double salary; public Emp() { } public Emp(String name, Date birthday, Double salary) { this.name = name; this.birthday = birthday; this.salary = salary; } //getter and setter }
public interface EmpMapper { List<Emp> findAll(); Emp findById(Long id); void save(Emp emp); void update(Emp emp); void delete(Long id); }
@MapperScan("org.yun.mapper") //這裏指定要掃描的mapper包 @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
@MapperScan指定要掃描的mapper包mysql
在src/main/resources/下建立包 org.yun.mapper(與EmpMapper.java的包同名)。而後,創建EmpMapper.xml文件git
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="org.yun.mapper.EmpMapper"> <sql id="baseSql"> id,name,birthday,salary </sql> <select id="findAll" resultType="org.yun.domain.Emp"> select <include refid="baseSql"/> from emp </select> <select id="findById" parameterType="long" resultType="org.yun.domain.Emp"> select <include refid="baseSql"/> from emp where id = #{id} </select> <insert id="save" parameterType="org.yun.domain.Emp" keyProperty="id" useGeneratedKeys="true"> insert into emp(name,birthday,salary)values(#{name},#{birthday},#{salary}) </insert> <update id="update" parameterType="org.yun.domain.Emp"> update emp set name = #{name},birthday = #{birthday},salary = #{salary} where id = #{id} </update> <delete id="delete" parameterType="long"> delete from emp where id = #{id} </delete> </mapper>
關於 MyBatis 這部分,使用 MBG 或 MyBatis Plus會更方便。github
application.properties
#指定實體類的名別包 mybatis.type-aliases-package=org.yun.domain #指定XxxMapper.xml的位置 #mybatis.mapper-locations=classpath:org/yun/mapper/*Mapper.xml
CREATE TABLE emp ( id BIGINT AUTO_INCREMENT, name VARCHAR(30), birthday DATE, salary DOUBLE, PRIMARY KEY(id) );
insert into emp(name,birthday,salary)values('admin','1999-09-09',9000);
將schema.sql、data.sql(名字固定)文件放置在src/main/resources下目錄,Spring Boot啓動的時候會自動執行。spring
@RunWith(SpringRunner.class) @SpringBootTest public class ApplicationTests { @Autowired private EmpMapper empMapper; @Test public void contextLoads() { assertNotNull(empMapper); Emp emp1 = new Emp("tom", new Date(), 5000D); Emp emp2 = new Emp("bill", new Date(), 6000D); empMapper.save(emp1); empMapper.save(emp2); assertTrue(empMapper.findAll().size() == 3); Emp emp = empMapper.findById(2L); emp.setSalary(8000D); empMapper.update(emp); assertTrue(emp.getSalary() == 8000D); empMapper.delete(2L); assertTrue(empMapper.findAll().size() == 2); } }
參考資料:sql
https://github.com/mybatis/spring-boot-starter/wiki/Quick-Start數據庫
http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/index.html緩存
補充:mybatis
在實際項目中通常都會使用Mybatis Generator來實現實體類、映射文件的生成。
那具體怎麼操做呢?以MySQL數據庫爲例。
<!-- <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.41</version> <scope>runtime</scope> </dependency>
取消h2內存數據庫驅動的依賴,加入MySQL數據庫驅動的依賴。
同時添加以一個Mybatis Generator插件
<plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.41</version> </dependency> </dependencies> </plugin>
編寫mybatis的文件生成配置文件:generatorConfig.xml
<?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> <!--加載jdbc屬性文件--> <properties resource="application.properties"/> <context id="DB2Tables" targetRuntime="MyBatis3" defaultModelType="flat"> <!--緩存 暫時不加--> <!--<plugin type="org.mybatis.generator.plugins.CachePlugin"/>--> <!--重寫equals()和hashCode()--> <plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/> <!-- 分頁 --> <plugin type="org.mybatis.generator.plugins.RowBoundsPlugin"/> <!--序列化--> <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/> <!--重寫toString()--> <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/> <!-- 註釋 --> <commentGenerator> <!-- 是否取消註釋 --> <property name="suppressAllComments" value="true"/> <!-- 是否生成註釋代時間戳--> <property name="suppressDate" value="true"/> </commentGenerator> <!--數據庫連接URL,用戶名、密碼 --> <jdbcConnection driverClass="${spring.datasource.driver-class-name}" connectionURL="${spring.datasource.url}" userId="${spring.datasource.username}" password="${spring.datasource.password}"/> <!-- 類型解析器 --> <!-- 默認false:把JDBC DECIMAL 和 NUMERIC 類型解析爲java.lang.Integer true:把JDBC DECIMAL 和 NUMERIC 類型解析爲java.math.BigDecimal --> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- 生成model的包名和位置 --> <javaModelGenerator targetPackage="org.yun.domain" targetProject="src\main\java"> <!-- 是否讓schema做爲包的後綴 --> <property name="enableSubPackages" value="true"/> <!-- 從數據庫返回的值被清理先後的空格 --> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- 生成 xxxMapper.xml文件的包名和位置 --> <sqlMapGenerator targetPackage="org.yun.mapper" targetProject="src\main\resources"> <!-- 這裏必定是src/main/resources目錄 --> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <!-- 生成xxxMapper的包名和位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="org.yun.mapper" targetProject="src\main\java"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <!-- 要生成哪些表 --> <table tableName="emp" domainObjectName="Emp"/> </context> </generatorConfiguration>
使用IDA右鍵執行,便可實現代碼生成。
會生成以下代碼