mybatis 和 mybatis-plus
mybatis
配置
1.新建MAVEN项目
2.配置mybatis依赖
<?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>org.example</groupId>
<artifactId>DemoMybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- 连接数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<!-- mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.12</version>
</dependency>
</dependencies>
<build>
<!-- 配置idea扫描xml或者properties文件 -->
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
</project>
3.创建表
REATE TABLE IF NOT EXISTS users \
id INT AUTO_INCREMENT PRIMARY KEY, \
name VARCHAR(100), \
email VARCHAR(150));
4.创建数据源database.properties文件
resources 目录下 创建 database.properties
文件:用于mybatis配置文件读取数据库信息
driver=com.mysql.cj.jdbc.Driver
url= jdbc:mysql://127.0.0.1:3306/mydatabase?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
username=root
password=123456
5.编写mybatis-config.xml配置文件
resources 目录下 创建 mybatis-config.xml
配置文件: 用于配置数据库连接和 MyBatis 运行时所需的各种特性,包含了设置和影响 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">
<!-- mybatis的主配置文件 -->
<configuration>
<!-- 引入外部资源: database.properties 配置文件-->
<properties resource="database.properties"/>
<!-- 配置环境:有助于将 SQL 映射应用于多种数据库之中 -->
<environments default="mysql">
<!-- 配置环境id:mysql-->
<environment id="mysql">
<!-- 配置事务的类型:使用JDBC的事务-->
<transactionManager type="JDBC"/>
<!-- 配置数据源(连接池)type="POOLED说明是使用连接池方式,节省资源 -->
<dataSource type="POOLED">
<!-- 配置连接数据库的4个基本信息 -->
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
</configuration>
6.连接测试
package org.example;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.Reader;
public class Main {
public static void main(String[] args) {
// mybatis-config.xml 路径
String mybatisConfig = "mybatis-config.xml";
try {
// 加载配置文件
Reader config = Resources.getResourceAsReader(mybatisConfig);
// 构建会话
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(config);
SqlSession sqlSession = sqlSessionFactory.openSession();
System.out.println(sqlSession.getConfiguration());
sqlSession.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
使用
1.映射类
创建entity/User
类:用于跟数据库字段做映射。
注意:与数据库中字段名、类型一致
package org.example.user;
import lombok.Data;
@Data
public class UserEntity {
private int id;
private String name;
private String email;
}
2.Mapper接口
创建mapper/IUserMapper接口: 用于操作数据库CURD的方法
package org.example.mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.example.entity.User;
import java.util.List;
import java.util.Map;
public interface IUserMapper {
List<User> queryUser();
// @Select("SELECT * FROM users")
// List<User> queryUser();
String getNameById(@Param("id") Long id);
List<User> queryUserByMap(Map<String, Object> param);
List<User> queryUserEntity(User user);
int insertUser(@Param("user") User user);
int updateUser(@Param("user") User user);
int deleteUser(@Param("id") Long id);
}
3.mapper.xml文件
resources 目录下 org/example/mapper创建IUserMapper.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">
<!--namespace=绑定一个对应的Mapper接口-->
<mapper namespace="org.example.mapper.IUserMapper">
<!--查询所有用户-->
<!--<select> 标签表明这是一条查询语句,属性id用来标识这条SQL;resultType表示返回的是一个userEntity类型的值。 -->
<select id="queryUser" resultType="org.example.entity.User">
select * from users;
</select>
<select id="getNameById" resultType="string">
select name from users where id = #{id};
</select>
<select id="queryUserByMap" parameterType="map" resultType="org.example.entity.User">
select * from users where id = #{id};
</select>
<select id="queryUserEntity" parameterMap="org.example.entity.User" resultType="org.example.entity.User">
select * from users where id = #{id};
</select>
<insert id="insertUser" keyProperty="id" useGeneratedKeys="true">
insert into users (name, email)
values (#{user.name}, #{user.email})
</insert>
<update id="updateUser">
update users set email=#{user.email} where id = #{user.id}
</update>
<delete id="deleteUser">
delete from users where id = #{id}
</delete>
</mapper>
注意:
mapper接口和mapper.xml之间需要遵循一定规则,才能成功的让mybatis将mapper接口和mapper.xml绑定起来
- mapper接口和mapper.xml的命名要一样;
- mapper接口的全限定名,要和mapper.xml的namespace属性一致;
- mapper接口中的方法名,要和mapper.xml中的SQL标签的id一致;
- mapper接口中的方法入参类型,要和mapper.xml中SQL语句的入参类型一致;
- mapper接口中的方法出参类型,要和mapper.xml中SQL语句的返回值类型一致。
Java框架:Mybatis【详细】_java mybatis-CSDN博客
mybatis-plus
MyBatis Plus 和 MyBatis 的区别
MyBatis Plus 与原始的 MyBatis 框架有以下主要区别:
功能增强:MyBatis Plus 在 MyBatis 的基础上提供了更多的功能,如通用的 CRUD 操作、分页查询、条件构造器等。这些功能减少了开发人员的工作量,提高了开发效率。
注解支持:MyBatis Plus 引入了一系列注解,如@TableName、@TableId、@TableField等,使得实体类的映射更加灵活和方便,不再需要 XML 映射文件。
更强大的条件构造器:MyBatis Plus 的条件构造器允许我们以更加直观和链式的方式构建 SQL 查询条件,而不必担心拼接 SQL 字符串。
自动代码生成:MyBatis Plus 提供了代码生成器,可以根据数据库表结构自动生成实体类和 Mapper 接口,极大地简化了开发过程。
总的来说,MyBatis Plus 是 MyBatis 的增强版,旨在提供更多便捷的特性,减少开发工作,同时保留了 MyBatis 的灵活性和强大性能。
1. 实体类注解
@TableName:用于指定数据库表的名称。
@TableId:用于指定主键字段。
@TableField:用于指定非主键字段的属性配置。
2. 逻辑删除注解
@TableLogic:用于实现逻辑删除。
3. 字段填充注解
@TableField:其中的 fill 属性可以用于指定字段的自动填充策略,如插入和更新时自动填充时间戳等。
SpringBoot中使用mybatis-plus
1.新建SpringBoot项目
2.配置mybatis-plus依赖
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.example</groupId>
<artifactId>MySpringBoot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>MySpringBoot</name>
<description>MySpringBoot</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.34</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3.创建表
CREATE TABLE `users` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`email` varchar(150) DEFAULT NULL,
`status` int(10) DEFAULT '1',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
4.配置数据库
application.properties文件中配置数据库连接信息:
spring.application.name=MySpringBoot
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mydatabase?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
#debug=true
5.配置 MapperScan 注解
MySpringBootApplication.java
package org.example.myspringboot;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("org.example.myspringboot.**.mapper") // 配置 MapperScan 注解
public class MySpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(MySpringBootApplication.class, args);
}
}
6.映射类
Users.java
package org.example.myspringboot.accounts.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("users")
public class Users {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("name")
private String name;
@TableField("email")
private String email;
@TableField("status")
private Long status;
@TableField("create_time")
private LocalDateTime create_time;
@TableField("update_time")
private LocalDateTime update_time;
// @TableField("isMarried")
// private Boolean isMarried;
}
7.Mapper映射
UsersMapper.java
package org.example.myspringboot.accounts.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.example.myspringboot.accounts.domain.Users;
@Mapper
public interface UsersMapper extends BaseMapper<Users> {
}
8.CURD
UserContorller.java
package org.example.myspringboot.accounts.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.myspringboot.accounts.domain.Users;
import org.example.myspringboot.accounts.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
@RequestMapping("/users")
@RestController
public class UserContorller {
@Autowired
private UsersMapper usersMapper;
@RequestMapping
public ResponseEntity<List<Users>> list(){
// 查询所有
// List<Users> usersList = usersMapper.selectList(null);
// 分页查询
Page<Users> page = new Page<>(1, 10);
IPage<Users> usersPage = usersMapper.selectPage(page, null);
List<Users> usersList = usersPage.getRecords();
return ResponseEntity.ok()
.body(usersList);
}
@RequestMapping("/add")
public ResponseEntity<Users> add(){
Users users = new Users();
users.setName("admin");
users.setEmail("admin@example.com");
users.setStatus(1L);
int row = usersMapper.insert(users);
System.out.println(row);
return ResponseEntity.ok()
.body(users);
}
@RequestMapping("/get")
public ResponseEntity<List<Users>> getUser(){
//Users users = usersMapper.selectById(1L);
HashMap<String, Object> map = new HashMap<>();
// 查找 name=admin and status=0
map.put("name", "admin"); // 查找name=admin
map.put("status", "0"); // 查找status=0
List<Users> userList = usersMapper.selectByMap(map);
return ResponseEntity.ok()
.body(userList);
}
@RequestMapping("/update")
public ResponseEntity<String> update(){
Users users = new Users();
users.setId(1L);
// 修改用户邮箱和status
users.setEmail("admin@xxxxx.com"); // 修改id=1的用户邮箱
users.setStatus(0L); // 修改id=1的 status
int row = usersMapper.updateById(users);
System.out.println(row);
return ResponseEntity.ok("OK");
}
public ResponseEntity<String> delete(){
int row = usersMapper.deleteById(1L);
return ResponseEntity.ok("OK");
}
}
【MyBatis Plus】初识 MyBatis Plus,在 Spring Boot 项目中集成 MyBatis Plus,理解常用注解以及常见配置_mybatisplus-CSDN博客