SpringBoot系列四:整合持久層技術


整合MyBatis

在SpringBoot中,MyBatis官方提供了一套自動化方案,可以做到MyBatis開箱即用。

創建工程,添加依賴

<!-- 添加mybatis依賴 -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>
<!-- 添加數據依賴 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<!-- 添加數據連接池依賴 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.9</version>
</dependency>

創建數據庫、表、實體類等

配置數據庫、表、實體類

配置DemoApplication和properties

在DemoApplication.java中添加@MapperScan註解
在這裏插入圖片描述
在properties中配置數據庫
在這裏插入圖片描述

創建數據訪問層

Mapper.java

/**
 * (Student)表數據庫訪問層
 *
 * @author Lw中
 * @since 2020-06-10 08:36:07
 *
 * @Mapper:表明該接口是一個MyBatis中的Mapper
 * @Component:爲了防止在Service中注入Mapper出現報錯(雖然不影響運行)而添加
 */
@Mapper
@Component
public interface StudentMapper {
    /**
     * 通過ID查詢單條數據
     *
     * @param id 主鍵
     * @return 實例對象
     */
    Student queryById(Integer id);
    /**
     * 查詢指定行數據
     *
     * @param offset 查詢起始位置
     * @param limit 查詢條數
     * @return 對象列表
     */
    List<Student> queryAllByLimit(@Param("offset") int offset, @Param("limit") int limit);
    /**
     * 通過實體作爲篩選條件查詢
     *
     * @param student 實例對象
     * @return 對象列表
     */
    List<Student> queryAll(Student student);
}

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.lwz.demo.mapper.StudentMapper">
    <resultMap type="com.lwz.demo.entity.Student" id="StudentMap">
        <result property="id" column="id" jdbcType="INTEGER"/>
        <result property="studentId" column="student_id" jdbcType="INTEGER"/>
        <result property="studentName" column="student_name" jdbcType="VARCHAR"/>
        <result property="age" column="age" jdbcType="INTEGER"/>
        <result property="gender" column="gender" jdbcType="VARCHAR"/>
        <result property="className" column="class_name" jdbcType="VARCHAR"/>
    </resultMap>
    <!--查詢單個-->
    <select id="queryById" resultMap="StudentMap">
        select
          id, student_id, student_name, age, gender, class_name
        from mybatis.t_student
        where id = #{id}
    </select>
    <!--查詢指定行數據-->
    <select id="queryAllByLimit" resultMap="StudentMap">
        select
          id, student_id, student_name, age, gender, class_name
        from mybatis.t_student
        limit #{offset}, #{limit}
    </select>
    <!--通過實體作爲篩選條件查詢-->
    <select id="queryAll" resultMap="StudentMap">
        select
          id, student_id, student_name, age, gender, class_name
        from mybatis.t_student
        <where>
            <if test="id != null">
                and id = #{id}
            </if>
            <if test="studentId != null">
                and student_id = #{studentId}
            </if>
            <if test="studentName != null and studentName != ''">
                and student_name = #{studentName}
            </if>
            <if test="age != null">
                and age = #{age}
            </if>
            <if test="gender != null and gender != ''">
                and gender = #{gender}
            </if>
            <if test="className != null and className != ''">
                and class_name = #{className}
            </if>
        </where>
    </select>

創建Controller類

此處省略Service類的編寫

@RestController
public class StudentController {
    @Autowired
    StudentService studentService;
    @GetMapping("/studentOps")
    public void studentOps() {
        Student student = new Student();
        student.setStudentId(2018123444);
        student.setStudentName("Lw中");
        student.setAge(19);
        student.setGender("男");
        student.setClassName("18軟件技術777");
        Student insert = studentService.insert(student);
        System.out.println(insert.getStudentName());
        Student student1 = new Student();
        student1.setId(9);
        student1.setStudentId(2018123444);
        student1.setStudentName("Lw中update");
        student1.setAge(19);
        student1.setGender("男");
        student1.setClassName("18軟件技術777");
        Student update = studentService.update(student1);
        System.out.println(update.getStudentName());
        boolean b = studentService.deleteById(3);
        if (b) {
            System.out.println("刪除成功");
        }
    }
}

整合MyBatis-Plus

創建工程,添加依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.3.2</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 添加數據連接池依賴 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.9</version>
</dependency>

創建MyBatis-plus配置類

@Configuration
@MapperScan("com.lwz.demo.mapper")
@ConditionalOnClass(value = {PaginationInterceptor.class})
public class MybatisPlusConfig {
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        return paginationInterceptor;
    }
}

創建實體類

@Data
public class Acount {

    private int id;
    private String userName;
    private double balance;
}

創建mapper文件

mapper類要繼承BaseMapper<Acount>

public interface AcountMapper extends BaseMapper<Acount> {

}

編寫測試類,測試結果

@RunWith(SpringRunner.class)
@SpringBootTest
class DemoApplicationTests {
    @Resource
    private AcountMapper acountMapper;
    @Test
    void contextLoads() {
        Acount acount = acountMapper.selectById(1);
        System.out.println(acount.getUserName());
    }
}

結果如下圖所示:
在這裏插入圖片描述

在Mybatis-plus中編寫原生sql的兩種方法

第一:在pom.xml文件中添加

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
        </resource>
    </resources>
</build>  

第二:把xml文件放到resources裏面的mapper文件中

在這裏插入圖片描述

使用MyBatis-plus進行分頁查詢

創建工程,添加依賴

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.3.2</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 添加數據連接池依賴 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.9</version>
</dependency>

創建Controller類

中間的步驟省略,直接到Controller類中編寫接口進行測試

@RestController
public class queryList {
    @Resource
    UserMapper userMapper;
    @GetMapping("queryUser")
    public UserVo queryList(Integer current, Integer size) {
        UserVo userVo = new UserVo();
        IPage<User> page = new Page<>(current, size);
        userMapper.selectPage(page, null);
        userVo.setCurrent(current);
        userVo.setSize(size);
        userVo.setTotal(page.getTotal());
        userVo.setUserList(page.getRecords());
        return userVo;
    }
}

在瀏覽器中輸入http://localhost:8080/queryUser?current=1&size=2,查看測試結果
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章