在idea里面创建springboot项目整合mybatis、mybatisplus

本文详细介绍了如何配置SpringBoot项目,调整POM文件以适应JDK8,配置数据库连接,创建实体类,编写Mapper接口和XML文件,以及进行数据库的增删改查操作。同时展示了如何利用MybatisPlus的特性简化开发,包括使用Lombok注解减少样板代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、首先创建如图所示:
springboot配置
2、创建完之后修改一下pom文件里的spring-boot-starter-parent版本,因为我电脑上jdk版本是8新建的是3.0版本以上的,所以要修改一下:版本修改
整个pom文件如下:

<?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>2.7.7</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.scj</groupId>
    <artifactId>springboot02</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot02</name>
    <description>springboot02</description>

    <properties>
        <java.version>8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

3、填写配置:

spring.datasource.url=jdbc:mysql://localhost:3306/sqglxt?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

mybatis.mapperLocations=classpath:mapper/*.xml
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

4、创建数据库和表:

-- 创建数据库
CREATE DATABASE `mybatis_plus` /*!40100 DEFAULT CHARACTER SET utf8mb4 */;
use `mybatis_plus`;
CREATE TABLE `user` (
`id` bigint(20) NOT NULL COMMENT '主键ID',
`name` varchar(30) DEFAULT NULL COMMENT '姓名',
`age` int(11) DEFAULT NULL COMMENT '年龄',
`email` varchar(50) DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- 添加数据
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');

5、添加实体

@Data //lombok注解
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}

6、添加mapper,写一个增删改查的接口。

public interface UserMapper {

    int addUser(User user);

    int updateUser(User user);

    int deleteUser(Long id);

    User findUserById(Long id);
    
    List<User> findAllUser(User user);
}

7、添加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.scj.springboot02.mapper.UserMapper">

    <resultMap type="com.scj.springboot02.entity.User" id="UserMap">
        <result property="id" column="id" jdbcType="INTEGER"/>
        <result property="name" column="name" jdbcType="VARCHAR"/>
        <result property="age" column="age" jdbcType="INTEGER"/>
        <result property="email" column="email" jdbcType="VARCHAR"/>
    </resultMap>

    <!--查询数据-->
    <select id="findAllUser" resultMap="UserMap">
        select
        id, name, age, email
        from user
        <where>
            <if test="id != null">
                and id = #{id}
            </if>
            <if test="name != null and name != ''">
                and name = #{name}
            </if>
            <if test="age != null">
                and age = #{age}
            </if>
            <if test="email != null and email != ''">
                and email = #{email}
            </if>
        </where>
    </select>

    <!--根据id查询-->
    <select id="getUserById" resultMap="UserMap">
        select
        id, name, age, email
        from user
        where id = #{id}
    </select>

    <!--新增所有列-->
    <insert id="addUser" keyProperty="id" useGeneratedKeys="true">
        insert into user
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != 0">
                id,
            </if>
            <if test="name != null and name != ''">
                name,
            </if>
            <if test="age != null">
                age,
            </if>
            <if test="email != null and email != ''">
                email,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="id != 0">
                #{id,jdbcType=INTEGER},
            </if>
            <if test="name != null and name != ''">
                #{name},
            </if>
            <if test="age != null">
                #{age},
            </if>
            <if test="email != null and email != ''">
                #{email},
            </if>
        </trim>
    </insert>

    <!--通过主键修改数据-->
    <update id="updateUser">
        update user
        <set>
            <if test="name != null and name != ''">
                name = #{name},
            </if>
            <if test="age != null">
                age = #{age},
            </if>
            <if test="email != null and email != ''">
                email = #{email},
            </if>
        </set>
        where id = #{id}
    </update>

    <!--通过主键删除-->
    <delete id="deleteUser">
        delete
        from user
        where id = #{id}
    </delete>

</mapper>

8、测试

@SpringBootTest
class Springboot02ApplicationTests {

    @Autowired
    private UserMapper userMapper;

    @Test
    void contextLoads() {
    }

    @Test
    public void testFindAllUser(){
        userMapper.findAllUser(null).forEach(System.out::println);
    }

    @Test
    public void testAddUser(){
        User user = new User();
        user.setId(6L);
        user.setAge(18);
        user.setEmail("1586156397@qq.com");
        user.setName("scj");
        userMapper.addUser(user);
    }

    @Test
    public void testUpdateUser(){
        User user = new User();
        user.setId(6L);
        user.setAge(18);
        user.setEmail("1586156397@qq.com");
        user.setName("光头强");
        userMapper.updateUser(user);
    }

    @Test
    public void testGetUserById(){
        System.err.println(userMapper.getUserById(6l));
    }

    @Test
    public void testDeleteUser(){
        userMapper.deleteUser(6l);
    }


}

9、测试结果查询:
测试结果图
10、利用mybatisplus实现增删改查,添加一个实体,如下图所示:

@Data
@TableName("user")
public class UserDAO {

    /**
     * IdType.ASSIGN_ID:雪花算法 基于雪花算法的策略生成数据id,与数据库id是否设置自增无关
     * IdType.AUTO:数据库自增 与数据库id是否设置自增有关
     * IdType.INPUT:用户输入id 与数据库id是否设置自增无关
     * IdType.NONE:无状态 与数据库id是否设置自增有关
     * IdType.ID_WORKER:数据库自增 与数据库id是否设置自增有关
     * IdType.ID_WORKER_STR:数据库自增 与数据库id是否设置自增有关
     * IdType.UUID:随机UUID 与数据库id是否设置自增无关
     */
    @TableId(type = IdType.ASSIGN_ID)
    private Long id;
    @TableField("name")
    private String username;
    private Integer age;
    private String email;

}

11、添加mapper,继承mybatisplus的特性,如下图所示:

public interface UserDAOMapper extends BaseMapper<UserDAO> {
}

UserDAOMapper
11、这样就可以测试增删改查了,代码如下:

 @Test
    public void testSelectList(){
        userDAOMapper.selectList(null).forEach(System.out::println);
    }

    @Test
    public void testAddUser(){
        UserDAO user = new UserDAO();
        user.setAge(18);
        user.setEmail("1586156397@qq.com");
        user.setUsername("scj");
        userDAOMapper.insert(user);
    }

    @Test
    public void testUpdateUser(){
        UserDAO user = new UserDAO();
        user.setId(1L);
        user.setAge(18);
        user.setEmail("1586156397@qq.com");
        user.setUsername("熊二");
        userDAOMapper.updateById(user);
    }

    @Test
    public void testGetUserById(){
        System.err.println(userDAOMapper.selectById(1l));
    }

    @Test
    public void testDeleteUser(){
        userDAOMapper.deleteById(1l);
    }

12、测试结果同上,如图所示:结果图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FirstTalent

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值