非spring项目使用mybatis-plus
阅读数:82 评论数:0
跳转到新版页面分类
python/Java
正文
一、初始化项目
1、pom.xml
<?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.lhstack.mybatis</groupId>
<artifactId>mybatis-plus-test</artifactId>
<version>0.0.1</version>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<mybatis-plus.version>3.4.3</mybatis-plus.version>
<hikaricp.version>4.0.3</hikaricp.version>
<mysql.version>8.0.23</mysql.version>
<junit.version>4.13</junit.version>
<slf4j.version>1.7.31</slf4j.version>
<logback.version>1.2.3</logback.version>
</properties>
<dependencies>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-extension -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.zaxxer/HikariCP -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>${hikaricp.version}</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**</include>
</includes>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/main/resources</directory>
<includes>
<include>**</include>
</includes>
</testResource>
</testResources>
</build>
</project>
2、项目结构
二、化码
1、创建entity
package com.lhstack.mybatis.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.util.Date;
@TableName(value = "t_user")
public class User {
@TableId(type = IdType.AUTO)
private Integer id;
private Date createTime;
private String description;
private String email;
private Boolean enable;
private String name;
private String password;
private String pic;
private String salt;
private Date updateTime;
private String username;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Boolean getEnable() {
return enable;
}
public void setEnable(Boolean enable) {
this.enable = enable;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", createTime=" + createTime +
", description='" + description + '\'' +
", email='" + email + '\'' +
", enable=" + enable +
", name='" + name + '\'' +
", password='" + password + '\'' +
", pic='" + pic + '\'' +
", salt='" + salt + '\'' +
", updateTime=" + updateTime +
", username='" + username + '\'' +
'}';
}
}
2、创建mapper接口
package com.lhstack.mybatis.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lhstack.mybatis.entity.User;
import java.util.List;
public interface UserMapper extends BaseMapper<User> {
List<User> findAll();
}
3、创建mapper.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.lhstack.mybatis.mapper.UserMapper">
<select id="findAll" resultType="com.lhstack.mybatis.entity.User">
SELECT * FROM t_user
</select>
</mapper>
4、测试方法
package com.lhstack.mybatis;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lhstack.mybatis.entity.User;
import com.lhstack.mybatis.mapper.UserMapper;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.logging.slf4j.Slf4jImpl;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import javax.sql.DataSource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.JarURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
@RunWith(JUnit4.class)
public class MybatisPlusApplicationTests {
private SqlSession session;
@Before
public void before() throws IOException {
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
MybatisConfiguration configuration = new MybatisConfiguration();
initConfiguration(configuration);
configuration.addInterceptor(initInterceptor());
//扫描mapper接口所在包
configuration.addMappers("com.lhstack.mybatis.mapper");
//配置日志实现
configuration.setLogImpl(Slf4jImpl.class);
//构建mybatis-plus需要的globalconfig
GlobalConfig globalConfig = new GlobalConfig();
//此参数会自动生成实现baseMapper的基础方法映射
globalConfig.setSqlInjector(new DefaultSqlInjector());
//设置id生成器
globalConfig.setIdentifierGenerator(new DefaultIdentifierGenerator());
//设置超类mapper
globalConfig.setSuperMapperClass(BaseMapper.class);
//给configuration注入GlobalConfig里面的配置
GlobalConfigUtils.setGlobalConfig(configuration, globalConfig);
//设置数据源
Environment environment = new Environment("1", new JdbcTransactionFactory(), initDataSource());
configuration.setEnvironment(environment);
this.registryMapperXml(configuration, "mapper");
//构建sqlSessionFactory
SqlSessionFactory sqlSessionFactory = builder.build(configuration);
this.session = sqlSessionFactory.openSession();
}
@After
public void after() {
this.session.commit();
this.session.close();
}
/**
* 初始化配置
*
* @param configuration
*/
private void initConfiguration(MybatisConfiguration configuration) {
configuration.setMapUnderscoreToCamelCase(true);
configuration.setUseGeneratedKeys(true);
}
/**
* 初始化数据源
*
* @return
*/
private DataSource initDataSource() {
HikariDataSource dataSource = new HikariDataSource();
dataSource.setJdbcUrl("jdbc:mysql://192.168.101.150:3306/cms?allowPublicKeyRetrieval=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8&useUnicode=true");
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUsername("root");
dataSource.setPassword("123456");
dataSource.setIdleTimeout(60000);
dataSource.setAutoCommit(true);
dataSource.setMaximumPoolSize(5);
dataSource.setMinimumIdle(1);
dataSource.setMaxLifetime(60000 * 10);
dataSource.setConnectionTestQuery("SELECT 1");
return dataSource;
}
/**
* 初始化拦截器
*
* @return
*/
private Interceptor initInterceptor() {
//创建mybatis-plus插件对象
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//构建分页插件
PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
paginationInnerInterceptor.setDbType(DbType.MYSQL);
paginationInnerInterceptor.setOverflow(true);
paginationInnerInterceptor.setMaxLimit(500L);
interceptor.addInnerInterceptor(paginationInnerInterceptor);
return interceptor;
}
/**
* 解析mapper.xml文件
*
* @param configuration
* @param classPath
* @throws IOException
*/
private void registryMapperXml(MybatisConfiguration configuration, String classPath) throws IOException {
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
Enumeration<URL> mapper = contextClassLoader.getResources(classPath);
while (mapper.hasMoreElements()) {
URL url = mapper.nextElement();
if (url.getProtocol().equals("file")) {
String path = url.getPath();
File file = new File(path);
File[] files = file.listFiles();
for (File f : files) {
FileInputStream in = new FileInputStream(f);
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(in, configuration, f.getPath(), configuration.getSqlFragments());
xmlMapperBuilder.parse();
in.close();
}
} else {
JarURLConnection urlConnection = (JarURLConnection) url.openConnection();
JarFile jarFile = urlConnection.getJarFile();
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry jarEntry = entries.nextElement();
if (jarEntry.getName().endsWith(".xml")) {
InputStream in = jarFile.getInputStream(jarEntry);
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(in, configuration, jarEntry.getName(), configuration.getSqlFragments());
xmlMapperBuilder.parse();
in.close();
}
}
}
}
}
@Test
public void testInsert() {
User user = new User();
user.setCreateTime(new Date());
user.setDescription(UUID.randomUUID() + "test");
user.setPassword(UUID.randomUUID() + "123456");
user.setUsername(UUID.randomUUID().toString());
user.setEnable(true);
user.setEmail(UUID.randomUUID() + "xxx@qq.com");
user.setUpdateTime(new Date());
UserMapper mapper = session.getMapper(UserMapper.class);
mapper.insert(user);
System.out.println(user);
}
@Test
public void testSelectPage() {
UserMapper mapper = session.getMapper(UserMapper.class);
Page<User> pageResult = mapper.selectPage(new Page<>(2, 1), new QueryWrapper<>());
System.out.println(pageResult.getTotal());
System.out.println(pageResult.getPages());
System.out.println(pageResult.getRecords());
}
@Test
public void testDelete() {
UserMapper mapper = session.getMapper(UserMapper.class);
int result = mapper.deleteById(5);
System.out.println(result);
this.testSelectList();
}
@Test
public void testUpdate() {
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.selectById(5);
user.setName("test");
user.setUpdateTime(new Date());
user.setPassword("654321");
user.setDescription("update");
mapper.updateById(user);
System.out.println(user);
}
@Test
public void testSelectList() {
UserMapper mapper = session.getMapper(UserMapper.class);
List<User> users = mapper.selectList(new QueryWrapper<>());
System.out.println(users);
}
@Test
public void testFindAll() {
UserMapper mapper = session.getMapper(UserMapper.class);
List<User> list = mapper.findAll();
System.out.println(list);
}
@Test
public void testFindAllPage() {
UserMapper mapper = session.getMapper(UserMapper.class);
this.testInsert();
Page<User> pageResult = mapper.findAllPage(new Page<>(1, 1));
System.out.println(pageResult.getTotal());
System.out.println(pageResult.getPages());
System.out.println(pageResult.getRecords());
}
@Test
public void testDataSource() throws Exception {
HikariDataSource dataSource = new HikariDataSource();
dataSource.setJdbcUrl("jdbc:mysql://192.168.101.150:3306/cms?allowPublicKeyRetrieval=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8&useUnicode=true");
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUsername("root");
dataSource.setPassword("123456");
dataSource.setIdleTimeout(60000);
dataSource.setAutoCommit(true);
dataSource.setMaximumPoolSize(5);
dataSource.setMinimumIdle(1);
dataSource.setMaxLifetime(60000 * 10);
dataSource.setConnectionTestQuery("SELECT 1");
Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("show table status");
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
String name = metaData.getColumnLabel(i);
String field = resultSet.getString(i);
System.out.printf("%s:%s\t", name, field);
}
System.out.println();
}
}
}
相关推荐
mybatis-plus是一个mybatis增强版工具,为了简化开发和提高效率。
可以在idea安装一个mybatisx插件,此插件可以通过mapper中的方法定位到xml中。</
一、AbstractWrapper
用于生成sql的where条件,当第一个入参数为boolean condition时,表示该条件是否加入最后成的sql中。
1、allEq
allEq(Map<R,
mybatis-plus的分页查询,高版本与低版本有所不同,同事由原来的3.1改成了3.4.2,但配置项并没有随之修改,导致查询成功但无法分页,page和total都为0。
之前的配置项是这样配置的:
一、@SqlParser
如果在程序中,有部分SQL不需要加上租户ID的表示,需要过滤特定的sql,可以通过@SqlParser(filter = true)的形式,只能作用于
方法一
给XXMapper.java加上Mapper注解,如:
import org.apache.i
一、使用mybatis-plus实现物理删除
1、根据id删除
// 1.根据id删除
@Test
public void testDeleteById(){