上一篇介绍了 集成数据库连接池与使用JPA 增删改查操作数据库,本篇将介绍 mybatis 的集成,内容多篇幅较长,耐心看完会有收获
1.什么是 MyBatis ?
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
2.SpringBoot整合mybatis有两种模式,分别是“全注解版” 和 “xml版”,下面截图说明注解版
- 全注解版 :在方法上加注解,在注解中写sql,下面的截图是注解模式的运用,小项目比较方便
- xml版:和以前一样,sql写在xml文件中,本文将整合此模式
图片中有使用 @Select( sql ) 注解的方式,@Results是返回结果集,如果实体类与字段一致则不需要手动对应,这是注解版,Sql写在java类的注解中,我感觉xml版的好用点
3.开始整合mybatis,先说整合流程,1.添加mybatis与generator的maven依赖,2.使用generator代码生成器生成实体类与mapper.xml文件,以简化重复工作
(1)添加mybatis依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!-- mybatis generator 自动生成代码插件 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.6</version>
<configuration>
<configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
</plugin>
(2)在项目中,把主体结构添加好,添加:dao、mapper架包,generator、entity资源目录,添加之后和下面类似
(3)在generator下创建generatorConfig.xml,用来生成 entity、dao接口、mapper.xml,可减少人工手动创建工作,生成器需要mysql-connector-java-5.1.25-bin.jar,下载资源,下面是generatorConfig.xml的代码,关键是要使用mysql-connector-java-5.1.25-bin.jar驱动包,设置好文件生成的位置,需要生成那些数据库表
<?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>
<!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
<classPathEntry location="D:\software\database\mybatis-generator-core-1.3.2\lib\mysql-connector-java-5.1.25-bin.jar"/>
<context id="DB2Tables" targetRuntime="MyBatis3" defaultModelType="flat">
<commentGenerator>
<property name="suppressDate" value="true"/>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据库链接URL,用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" userId="root" password="root" connectionURL="jdbc:mysql://localhost:3306/bigdata?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&maxReconnects=15000&allowMultiQueries=true">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成模型的包名和位置-->
<javaModelGenerator targetPackage="com.zypcy.expend.entity" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成映射文件的包名和位置-->
<sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成DAO的包名和位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.zypcy.expend.dao" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
<!-- 注意:已生成的不要再生成,不然会覆盖已生成的文件 -->
<!-- -->
<table tableName="customers" domainObjectName="Customer" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
要配置IDEA ,来运行 generatorConfig.xml,点击Run—-Edit Configurations
添加Maven配置,输入Name与Command line: mybatis-generator:generate -e
这样就可以通过 generatorConfig.xml 生成你需要的实体类、dao接口、 mybatis.xml文件
选中 generator ,点击右边的箭头,开始生成
我创建了一个customers表,generatorConfig.xml中配置了这个表,所以只生成了3个文件,分别在dao、entity、mapping下生成了文件
在启动类上添加 @MapperScan(“com.zypcy.expend.dao”) 扫描dao下的数据接口类
再创建服务接口与实现类,在服务实现类中调用dao接口,mybatis框架会自动映射到 mapping/customer.xml 中的sql
为什么能自动映射,因为 application.properties 配置了xml的地址与实体,而xml中的namespace与dao接口关联
# application.properties mybatis 配置
mybatis.mapper-locations=classpath:mapping/*.xml
mybatis.type-aliases-package=com.zypcy.expend.entity
(4)创建ICustomerService、CustomerServiceImpl
public interface ICustomerService {
void add(Customer customer);
void edit(Customer customer);
void delete(int id);
Customer getById(int id);
}
@Service
public class CustomerServiceImpl implements ICustomerService {
@Autowired private CustomerMapper customerMapper;
@Override
public void add(Customer customer) {
customerMapper.insert(customer);
}
@Override
public void edit(Customer customer) {
customerMapper.updateByPrimaryKey(customer);
}
@Override
public void delete(int id) {
customerMapper.deleteByPrimaryKey(id);
}
@Override
public Customer getById(int id) {
return customerMapper.selectByPrimaryKey(id);
}
}
编写一个测试类,调用上面的方法:
@RunWith(SpringRunner.class)
@SpringBootTest
public class CustomerTest {
@Autowired private ICustomerService customerService;
@Test
public void add(){
Customer customer = new Customer();
customer.setAge(26);
customer.setIsUse(true);
customer.setName("zy");
customerService.add(customer);
}
@Test
public void edit(){
Customer customer = new Customer();
customer.setId(13);
customer.setAge(27);
customer.setIsUse(false);
customer.setName("zy1");
customerService.edit(customer);
}
@Test
public void getById(){
Customer customer = customerService.getById(13);
System.out.println("customer:"+ JSON.toJSONString(customer));
}
}
测试结果如下:
一次执行多条sql,mysql驱动开启批量执行sql的开关。allowMultiQueries参数,设置为true
spring.datasource.url=jdbc:mysql://localhost:3306/bigdata?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&maxReconnects=15000&allowMultiQueries=true&useSSL=false
到此,mybatis的集成就完成了,感谢观看。
更多mybatis使用介绍,请参考:https://www.cnblogs.com/kenhome/p/7764398.html
下一篇:项目热部署