Springboot系列記錄(七)——Springboot整合Mybatis

上一篇已經記錄了Springboot整合Thymeleaf 

一、準備工作

首先準備好表和數據

 pom依賴:

     <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
 <!-- mybatis-spring-boot-starter -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>
        <!-- mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

application.properties

spring.datasource.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/數據庫名?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC
spring.datasource.username = root
spring.datasource.password = 密碼

新建Student類

public class Student {

    private Integer id;

    private String sname;

    getter setter...
}

二、註解方式

新建mapper接口: StudentMapper  加上註解@Mapper

@Mapper
public interface StudentMapper {

    @Select("select * from student")
    List<Student> findAll();
}

對應的註解有:@Insert、@Delete、@Update

這裏省略service層,直接創建Controller

@Controller
@RequestMapping("/studentManage")
public class StudentController {

    @Autowired
    StudentMapper studentMapper;

    @RequestMapping("/listStudent")
    public String toStudentView(Model model){
        List<Student> students = studentMapper.findAll();
        model.addAttribute("students",students);
        return "views/listStudent";
    }
}

 html:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>學生</title>
</head>
<body>
<table>
    <thead>
    <tr>
        <th>id</th>
        <th>學生姓名</th>
    </tr>
    </thead>
    <tbody>
    <tr th:each="s: ${students}">
        <td th:text="${s.id}"></td>
        <td th:text="${s.sname}"></td>
    </tr>
    </tbody>
</table>
</body>
</html>

 運行項目:訪問http://localhost:8080/studentManage/listStudent

 註解方式對一些簡單的SQL來說還是很方便的,但是實際項目中肯定會有複雜SQL,而複雜的SQL放註解上簡直慘不忍睹,所以下面來說一下XML的方式。

三、XML方式

首先把mapper接口的@Select註解去掉

在StudentMapper同文件夾下新建StudentMapper.xml文件  這裏要注意namespace  學到這裏應該對MyBatis沒有疑惑了

<?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.test.demo.mapper.StudentMapper">
    <select id="findAll" resultType="com.test.demo.domain.Student">
        select * from student
    </select>
</mapper>

注意:在properties文件中指明從哪裏去找xml配置文件

mybatis.mapper-locations=classpath:com/test/demo/mapper/*.xml

好了其他不用動,運行項目開始訪問:  一樣的效果

 

四、擴展

上文中提到要在mapper接口上添加註解@Mapper   實際項目中mapper接口肯定很多,我們可以在主程序上加上

@MapperScan("com.test.demo.mapper")

也可以指定多個包

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