前面我们已经学习mybatis相关知识,领略了mybatis的强大。但是有没有发现mybatis的一些缺陷。在myabtis眼里无论是单表还是多表都要自己写sql语句(即使使用注解的方式),那么有没有一种方式针对单表我们可以不写sql语句呢,毕竟在项目开发中绝大多数是单表,尤其是互联网项目。
开源的力量是无穷的,针对mybatis的上述缺陷,国产大神团队开发了牛逼的Mybatis-plus,与mybatis无缝衔接,不降低mybatis的性能,而大大的增加了开发效率。
一、创建maven项目并导入相应的开发包
<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.qiu</groupId>
<artifactId>mybatis-plus</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- mybatis-plus2.3.1版本,最新版本写demo时候失败,所以选这个版本-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>2.3.1</version>
</dependency>
<!-- druid数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<!-- velocity模板,用于代码生成器使用 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- spring事务相关 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
<!-- 日志-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<!-- freemarker模板,代码生成器相关 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
<!-- mybatis-plus代码生成器 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.36</version>
</dependency>
<!-- springaop -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
<!-- springweb -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
<!-- spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
<!-- spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
</dependencies>
</project>
二、使用mybatis-plus代码生成器生成相应的代码
package generator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
public class MybatisPlusGenerator {
public static void main(String[] args) {
String packageName = "com.qiu";
// user -> UserService, 为true: user -> IUserService
boolean serviceNameStartWithI = false;
generateByTables(serviceNameStartWithI, packageName, "user", "role");
}
private static void generateByTables(boolean serviceNameStartWithI, String packageName, String... tableNames) {
GlobalConfig config = new GlobalConfig();
String dbUrl = "jdbc:mysql://localhost:3306/mybatis";
DataSourceConfig dataSourceConfig = new DataSourceConfig();
dataSourceConfig.setDbType(DbType.MYSQL);
dataSourceConfig.setTypeConvert(new MySqlTypeConvert() {
// 自定义数据库表字段类型转换【可选】
@Override
public DbColumnType processTypeConvert(String fieldType) {
System.out.println("转换类型:" + fieldType);
return super.processTypeConvert(fieldType);
}
});
dataSourceConfig.setDbType(DbType.MYSQL).setUrl(dbUrl).setUsername("root").setPassword("123456")
.setDriverName("com.mysql.jdbc.Driver");
StrategyConfig strategyConfig = new StrategyConfig();
strategyConfig.setCapitalMode(true).setEntityLombokModel(false)
// .setDbColumnUnderline(true)
// 采用驼峰策略
.setNaming(NamingStrategy.underline_to_camel).setInclude(tableNames);
config.setActiveRecord(false).setAuthor("qiuzhangwei")
// 输出位置
.setOutputDir("d:\\").setFileOverride(true);
if (!serviceNameStartWithI) {
config.setServiceName("%sService");
}
new AutoGenerator().setGlobalConfig(config).setDataSource(dataSourceConfig).setStrategy(strategyConfig)
.setPackageInfo(
new PackageConfig().setParent(packageName).setController("controller").setEntity("entity"))
.execute();
}
}
三、代码生成器生成的代码
- entity
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String userName;
private String userPassword;
private String userEmail;
private String userInfo;
private String headImg;
private Date createTime;
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 getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public String getUserInfo() {
return userInfo;
}
public void setUserInfo(String userInfo) {
this.userInfo = userInfo;
}
public String getHeadImg() {
return headImg;
}
public void setHeadImg(String headImg) {
this.headImg = headImg;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName=" + userName +
", userPassword=" + userPassword +
", userEmail=" + userEmail +
", userInfo=" + userInfo +
", headImg=" + headImg +
", createTime=" + createTime +
"}";
}
}
- mapper
//这里继承BaseMapper,实现单表无sql语句
public interface UserMapper extends BaseMapper<User> {
}
- UserMapper.xml
<?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.qiu.mapper.UserMapper">
</mapper>
四、mybatis和spring相关配置
- applicationContext.xml
<?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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
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-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- 数据源 -->
<context:property-placeholder
location="classpath:db.properties" />
<bean id="dataSource"
class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 事务管理器 -->
<bean id="dataSourceTransactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 基于注解的事务管理 -->
<tx:annotation-driven
transaction-manager="dataSourceTransactionManager" />
<!-- Spring整合Mybatis,更多查看文档:http://mp.baomidou.com -->
<bean id="sqlSessionFactory"
class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描Mapping.xml文件 -->
<property name="mapperLocations"
value="classpath:mapper/*.xml" />
<property name="configLocation"
value="classpath:mybatis-config.xml" />
<!-- <property name="typeEnumsPackage" value="com.baomidou.springmvc.model.enums"/> -->
<property name="plugins">
<array>
<!-- 分页插件配置 -->
<bean id="paginationInterceptor"
class="com.baomidou.mybatisplus.plugins.PaginationInterceptor">
</bean>
</array>
</property>
<!-- 全局配置注入 -->
</bean>
<!-- MyBatis 动态扫描 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.qiu.mapper" />
</bean>
</beans>
- mybatis-config.xml
<?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>
<!-- 全局配置 -->
<settings>
<!--是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN 到经典Java 属性名 aColumn 的类似映射。 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<typeAliases>
<package name="com.qiu.entity.*"/>
</typeAliases>
</configuration>
- ab.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=123456
- log4j.properties(打印出相应的sql语句用于调试)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration
xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT"
class="org.apache.log4j.ConsoleAppender">
<param name="Encoding" value="UTF-8" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
</layout>
</appender>
<logger name="java.sql">
<level value="debug" />
</logger>
<logger name="org.apache.ibatis">
<level value="info" />
</logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>
五、测试
- spring资源初始化
private ApplicationContext ioc=null;
private UserMapper userMapper=null;
@Before
public void init() {
ioc=new ClassPathXmlApplicationContext("applicationContext.xml");
userMapper=ioc.getBean(UserMapper.class);
}
- 1.插入
@Test
public void insertUser() {
User user=new User();
user.setUserName("qiu1");
user.setUserPassword("111");
user.setCreateTime(new Date());
user.setUserInfo("demo1");
// insert插入数据
int insert = userMapper.insert(user);
//打印
System.out.println(user.getId());
}
- 2.修改
@Test
public void update() {
User user = new User();
user.setUserName("qiu1");
user.setUserPassword("111111111111");
user.setCreateTime(new Date());
user.setUserInfo("demo1");
user.setId(5);
int updateById = userMapper.updateById(user);
System.out.println(user.getUserPassword());
}
- 3.删除(按id删除和批量删除)
@Test
public void delete() {
//按id删除
int deleteById = userMapper.deleteById(1);
System.out.println(deleteById);
//批量删除
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(5);
userMapper.deleteBatchIds(list);
}
- 4.查询
@Test
public void select() {
//1.按id查询
User user = userMapper.selectById(1);
System.out.println(user);
//2.批量查询
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(5);
List<User> selectBatchIds = userMapper.selectBatchIds(list);
selectBatchIds.forEach(System.out::println);
//3.使用JavaBean封装按条件查询
User queryUser = new User();
queryUser.setUserName("qiu1");
queryUser.setUserPassword("1111111111");
User selectOne = userMapper.selectOne(queryUser);
System.out.println(selectOne);
//4.使用map封装按条件查询
Map<String, Object> map = new HashMap<>();
map.put("user_name", "qiu1");
List<User> selectByMap = userMapper.selectByMap(map);
selectByMap.forEach(System.out::println);
//5.分页查询
int current = 1;
int size = 5;
Page<User> page = new Page<>(current, size);
List<User> selectPage = userMapper.selectPage(page, null);
System.out.println(selectPage.size());
}
- 5.功能强大的EntityWrapper(实现灵活的动态拼接)
@Test
public void enrityWrappertets() {
EntityWrapper<User> entityWrapper = new EntityWrapper<>();
//条件查询user_name=‘qiu1’
entityWrapper.eq("user_name", "qiu1");
//分页查询
List<User> selectPage = userMapper.selectPage(new
Page<User>(1, 5), entityWrapper);
selectPage.forEach(System.out::println);
}