mybatis既有jdbc的灵活,有具有orm工具的方便,是一套很好用的工具,这儿就使用mybatis来作为数据访问工具,具体添加过程如下:
1. 添加mybatis依赖,并更新项目
1 <dependency> 2 <groupId>mysql</groupId> 3 <artifactId>mysql-connector-java</artifactId> 4 <scope>runtime</scope> 5 </dependency> 6 <dependency> 7 <groupId>org.mybatis.spring.boot</groupId> 8 <artifactId>mybatis-spring-boot-starter</artifactId> 9 <version>1.3.1</version> 10 </dependency>
2. 在application.properties中添加datasource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/blog?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
3. 添加实体类
1 package com.lvniao.blog.model; 2 3 public class User { 4 5 private Long id; 6 7 private String name; 8 9 private String password; 10 11 public Long getId() { 12 return id; 13 } 14 15 public void setId(Long id) { 16 this.id = id; 17 } 18 19 public String getName() { 20 return name; 21 } 22 23 public void setName(String name) { 24 this.name = name; 25 } 26 27 public String getPassword() { 28 return password; 29 } 30 31 public void setPassword(String password) { 32 this.password = password; 33 } 34 }
4. 添加Mapper类
package com.lvniao.blog.mapper; import java.util.List; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import com.lvniao.blog.model.User; @Mapper public interface UserMapper { @Select("select id, name, password from users") public List<User> getUsers(); }
5. 在控制器中添加Mapper变量
1 package com.lvniao.blog.admin.controller; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.stereotype.Controller; 5 import org.springframework.ui.Model; 6 import org.springframework.web.bind.annotation.RequestMapping; 7 8 import com.lvniao.blog.mapper.UserMapper; 9 10 @Controller 11 @RequestMapping("/admin") 12 public class AdminController { 13 14 @Autowired 15 private UserMapper userMapper; 16 17 @RequestMapping("/") 18 public String index(Model model) { 19 model.addAttribute("users", userMapper.getUsers()); 20 return "admin/index"; 21 } 22 }
6. 在视图中添加对应的处理
1 <!DOCTYPE HTML> 2 <html> 3 <head> 4 <title>lvniao</title> 5 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 6 </head> 7 <body> 8 <table border="1"> 9 <tr><th>id</th><th>name</th><th>password</th></tr> 10 <tr th:each="user:${users}"> 11 <td th:text="${user.id}"></td> 12 <td th:text="${user.name}"></td> 13 <td th:text="${user.password}"></td> 14 </tr> 15 </table> 16 </body> 17 </html>
如上就完成了spring和mybatis的整合,其中配置SqlSessionFactory的工作都是由mybatis提供了MybatisAutoConfiguration类完成的,而使用时只需在Mapper接口中添加对应的sql即可,极大地提高了开发速度。