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

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, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]');

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("[email protected]");
        user.setName("scj");
        userMapper.addUser(user);
    }

    @Test
    public void testUpdateUser(){
    
    
        User user = new User();
        user.setId(6L);
        user.setAge(18);
        user.setEmail("[email protected]");
        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("[email protected]");
        user.setUsername("scj");
        userDAOMapper.insert(user);
    }

    @Test
    public void testUpdateUser(){
    
    
        UserDAO user = new UserDAO();
        user.setId(1L);
        user.setAge(18);
        user.setEmail("[email protected]");
        user.setUsername("熊二");
        userDAOMapper.updateById(user);
    }

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

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

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

猜你喜欢

转载自blog.csdn.net/scj0725/article/details/131275803