11. MyBatis的实际应用
大约 5 分钟
MyBatis的实际应用
1.MyBatis和Spring的整合操作
创建一个普通的Maven项目即可
1.1 添加相关的依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.bobo</groupId>
<artifactId>MyBatisDemo11Spring</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- Spring核心依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<!--
MyBatis 相关依赖
MyBatis 自身依赖
MySQL驱动
日志
-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
<!-- Spring整合MyBatis的插件依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.4</version>
</dependency>
<!-- 单元测试的依赖 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>*.xml</include>
<include>*.properties</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
1.2 创建相关的配置文件
MyBatis的全局配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
</configuration>
Spring的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置扫描 -->
<context:component-scan base-package="com.bobo.service.*" />
<!-- 关联数据库属性文件 -->
<context:property-placeholder location="db.properties" />
<!-- 配置数据源 数据库连接池 -->
<bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource">
<property name="driverClass" value="${driver}" />
<property name="jdbcUrl" value="${url}"/>
<property name="user" value="${username}"/>
<property name="password" value="${password}"/>
</bean>
<!-- 整合MyBatis -->
<bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sessionFactoryBean">
<!-- 关联数据源 -->
<property name="dataSource" ref="dataSource" />
<!-- 关联配置文件 -->
<property name="configLocation" value="mybatis-cfg.xml" />
<!-- 添加别名 -->
<property name="typeAliasesPackage" value="com.bobo.pojo" />
</bean>
<!-- 配置接口的扫描路径 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" >
<property name="basePackage" value="com.bobo.mapper" />
</bean>
</beans>
db.properties文件
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/shop?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8
username=root
password=123456
#driver=com.mysql.cj.jdbc.Driver
#url=jdbc:mysql://192.168.100.122:3306/shop?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8
#username=root
#password=123456
log4j.properties文件
log4j.rootCategory=All, stdout , R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[QC] %p [%t] %C.%M(%L) | %m%n
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File=D:\\logs\\qc.log
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d-[TS] %p %t %c - %m%n
1.3 业务测试
JavaBean对象
package com.bobo.pojo;
public class User {
private Integer id;
private String username;
private String address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", address='" + address + '\'' +
'}';
}
}
Mapper接口和映射文件
package com.bobo.mapper;
import com.bobo.pojo.User;
import java.util.List;
public interface UserMapper {
List<User> query();
}
<?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="com.bobo.mapper.UserMapper">
<select id="query" resultType="user">
select * from t_user
</select>
</mapper>
service
package com.bobo.service;
import com.bobo.pojo.User;
import java.util.List;
public interface IUserService {
List<User> query();
}
package com.bobo.service.impl;
import com.bobo.mapper.UserMapper;
import com.bobo.pojo.User;
import com.bobo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements IUserService {
@Autowired
private UserMapper mapper;
@Override
public List<User> query() {
return mapper.query();
}
}
测试
@Test
public void test(){
ApplicationContext ac =
new ClassPathXmlApplicationContext("applicationContext.xml");
IUserService bean = ac.getBean(IUserService.class);
List<User> list = bean.query();
for (User user : list) {
System.out.println(user);
}
}
整体的项目结构
课后的作业:实现SpringMVC+Spring+MyBatis的整合。
2.逆向工程
2.1 什么是逆向工程
简单点说,就是通过数据库中的单表,自动生成Java代码。Mybatis官方提供了逆向工程,可以针对单表自动生成Mybatis代码(mapper.java\mapper.xml\po类)企业中,逆向工程是个很常用的工具,比我们手动创建映射文件的配置信息方便很多.
官网 http://www.mybatis.org/generator
2.2 逆向工程实现
添加mybatis-generator-maven-plugin插件
<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>
添加自动生成的配置文件
注意配置文件的名称必须是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>
<!-- 数据库的驱动包路径 -->
<classPathEntry location="C:\Users\dpb\.m2\repository\mysql\mysql-connector-java\8.0.11\mysql-connector-java-8.0.11.jar" />
<context id="DB2Tables" targetRuntime="MyBatis3">
<!-- 去掉生成文件中的注释 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!-- 数据库链接URL、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/shop?serverTimezone=GMT%2B8"
userId="root"
password="123456">
</jdbcConnection>
<!-- <jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver"
connectionURL="jdbc:oracle:thin:@localhost:1521:XE"
userId="car"
password="car">
</jdbcConnection> -->
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 生成模型的包名和位置 -->
<javaModelGenerator targetPackage="com.bobo.pojo" targetProject="./src/main/java">
<!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
<property name="enableSubPackages" value="false" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- 生成的映射文件包名和位置 -->
<sqlMapGenerator targetPackage="com.bobo.mapper" targetProject="./src/main/java">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- 生成DAO的包名和位置 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.bobo.mapper" targetProject="./src/main/java">
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<table tableName="t_user" domainObjectName="User" />
<table tableName="t_emp" domainObjectName="Emp" />
</context>
</generatorConfiguration>
自动生成代码
2.3 接口方法说明
UserBeanMapper接口中的方法说明
方法 | 功能说明 |
---|---|
int countByExample(UserExample example) | 按条件计数 |
int deleteByPrimaryKey(Integer id) | 按主键删除 |
int deleteByExample(UserExample example) | 按条件查询 |
Integer insert(User record) | 插入数据(返回值为ID) |
User selectByPrimaryKey(Integer id) | 按主键查询 |
List selectByExample(UserExample example) | 按条件查询 |
List selectByExampleWithBLOGs(UserExample example) | 按条件查询(包括BLOB字段)。只有当数据表中的字段类型有为二进制的才会产生。 |
int updateByPrimaryKey(User record) | 按主键更新 |
int updateByPrimaryKeySelective(User record) | 按主键更新值不为null的字段 |
int updateByExample(User record, UserExample example) | 按条件更新 |
int updateByExampleSelective(User record, UserExample example) | 按条件更新值不为null的字段 |
关键代码
package com.bobo.service.impl;
import com.bobo.mapper.EmpMapper;
import com.bobo.pojo.Emp;
import com.bobo.pojo.EmpExample;
import com.bobo.service.IEmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class EmpServiceImpl implements IEmpService {
@Autowired
private EmpMapper mapper;
@Override
public Emp queryEmpById(int id) {
return mapper.selectByPrimaryKey(id);
}
@Override
public List<Emp> query(Emp emp) {
EmpExample empExample = new EmpExample();
// 绑定查询的条件
EmpExample.Criteria criteria = empExample.createCriteria();
if(!"".equals(emp.getName()) && emp.getName() != null){
criteria.andNameLike("%"+emp.getName() +"%");
}
if(emp.getId() != null && emp.getId() > 0){
criteria.andIdEqualTo(emp.getId());
}
if(emp.getAge()!= null &&emp.getAge() > 0){
criteria.andAgeEqualTo(emp.getAge());
}
return mapper.selectByExample(empExample);
}
@Override
public Integer insert(Emp emp) {
return mapper.insertSelective(emp);
}
@Override
public Integer updateById(Emp emp) {
return mapper.updateByPrimaryKeySelective(emp);
}
@Override
public Integer deleteById(Emp emp) {
return mapper.deleteByPrimaryKey(emp.getId());
}
}