SpringBoot学习10:springboot整合mybatis
Posted 天涯浪子心
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot学习10:springboot整合mybatis相关的知识,希望对你有一定的参考价值。
需求:通过使用 SpringBoot+SpringMVC+MyBatis 整合实现一个对数据库中的 t_user 表的 CRUD 的操作
1、创建maven项目,添加项目所需依赖
<!--springboot项目依赖的父项目--> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.RELEASE</version> </parent> <dependencies> <!--注入springboot启动器--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--注入springboot对thymeleaf视图技术的支持--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!--mybaits启动器,注入springboot对mybatis的支持--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <!-- mysql 数据库驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- 阿里巴巴druid数据库连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.9</version> </dependency> <!-- jpa实体类规范 --> <dependency> <groupId>javax.persistence</groupId> <artifactId>persistence-api</artifactId> <version>1.0</version> </dependency> </dependencies>
2、在resource文件夹下添加application.properties全局配置文件
#数据库连接信息 spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springboot spring.datasource.username=root spring.datasource.password=duan #数据库连接池 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource #配置mybatis中实体类xml配置文件中实体类所在文件夹,如果配置了,在xml配置文件中参数、返回值实体类可以不写包名 mybatis.type-aliases-package=com.bjsxt.pojo #mapper接口xml文件所在位置 mybatis.mapper-locations=classpath:mapping/*.xml
3、数据库设计
创建数据库
DROP TABLE IF EXISTS `t_user`; CREATE TABLE `t_user` ( `id` bigint(10) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, `age` smallint(3) DEFAULT NULL, `hobby` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
添加数据
INSERT INTO `t_user` VALUES (\'1\', \'张三\', \'22\', \'羽毛球\'); INSERT INTO `t_user` VALUES (\'2\', \'李四\', \'20\', \'篮球\'); INSERT INTO `t_user` VALUES (\'3\', \'王五\', \'24\', \'排球\');
4、创建实体类User
package com.bjsxt.pojo; import javax.persistence.*; /** * Created by Administrator on 2019/2/10. */ @Entity @Table(name = "t_user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Long id; @Column(name = "name") private String name; @Column(name = "age") private int age; @Column(name = "hobby") private String hobby; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getHobby() { return hobby; } public void setHobby(String hobby) { this.hobby = hobby; } }
5、创建mapper接口以及接口映射的配置文件
package com.bjsxt.mapper; import com.bjsxt.pojo.User; import org.apache.ibatis.annotations.Mapper; import java.util.List; /** * Created by Administrator on 2019/2/10. */ public interface UserMapper { /** * 查询所有的用户 * @return */ List<User> selectAllUser(); /** * 查询单个用户 */ User selectUserById(Integer id); /** * 添加用户 */ void addUser(User user); /** * 修改用户 */ void updateUser(User user); /** * 删除用户 */ void deleteUser(Integer id); }
<?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.bjsxt.mapper.UserMapper"> <select id="selectAllUser" resultType="User"> select * from t_user; </select> <select id="selectUserById" parameterType="java.lang.Integer" resultType="User"> select * from t_user where id=#{id}; </select> <insert id="addUser" parameterType="User"> insert into t_user(name,age,hobby) values(#{name},#{age},#{hobby}); </insert> <update id="updateUser" parameterType="User"> update t_user set name=#{name},age=#{age},hobby=#{hobby} where id=#{id}; </update> <delete id="deleteUser" parameterType="java.lang.Integer"> delete from t_user where id=#{id}; </delete> </mapper>
6、创建业务层
接口:
package com.bjsxt.service; import com.bjsxt.pojo.User; import java.util.List; /** * Created by Administrator on 2019/2/10. */ public interface UserService { /** * 查询所有的用户 * @return */ List<User> selectAllUser(); /** * 查询单个用户 */ User selectUserById(Integer id); /** * 添加用户 */ void addUser(User user); /** * 修改用户 */ void updateUser(User user); /** * 删除用户 */ void deleteUser(Integer id); }
实现类
package com.bjsxt.service.impl; import com.bjsxt.mapper.UserMapper; import com.bjsxt.pojo.User; import com.bjsxt.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * Created by Administrator on 2019/2/10. */ @Service @Transactional //service层打开事务 public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public List<User> selectAllUser() { return userMapper.selectAllUser(); } @Override public User selectUserById(Integer id) { return userMapper.selectUserById(id); } @Override public void addUser(User user) { userMapper.addUser(user); } @Override public void updateUser(User user) { userMapper.updateUser(user); } @Override public void deleteUser(Integer id) { userMapper.deleteUser(id); } }
7、创建controller
package com.bjsxt.controller; import com.bjsxt.pojo.User; import com.bjsxt.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpServletRequest; /** * Created by Administrator on 2019/2/10. */ @Controller @RequestMapping("user") public class UserController { @Autowired private UserService userService; /** * 去用户列表页面 * @param model * @return */ @RequestMapping("toUserList") public String toUserList(Model model){ model.addAttribute("userList",userService.selectAllUser()); return "user_list"; } /** * 去用户编辑添加页面 */ @RequestMapping("toUserEdit") public String toUserEdit(HttpServletRequest request,Model model){ String id=request.getParameter("id"); if(null!=id&&!"".equals(id)){ //编辑 User user=userService.selectUserById(Integer.parseInt(id)); model.addAttribute("user",user); } return "user_edit"; } /** * 用户添加或编辑 */ @RequestMapping(value = "userEdit",method = RequestMethod.POST) public String userEdit(HttpServletRequest request,User user){ if(null!=user.getId()&&!"".equals(user.getId())){ //编辑 userService.updateUser(user); }else{ //添加 userService.addUser(user); } return "redirect:/user/toUserList"; } /** * 用户删除 */ @RequestMapping("deleteUser") public String deleteUser(Integer id){ userService.deleteUser(id); return "redirect:/user/toUserList"; } }
8、编写页面,视图层采用thymeleaf技术
用户列表页面user_list.html
<!DOCTYPE html > <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>用户列表</title> </head> <body> <div> <div><a href="toUserEdit">添加</a></div> <table> <tr> <th>用户id</th> <th>用户姓名</th> <th>用户年龄</th> <th>用户爱好</th> <th>操作</th> </tr> <tr th:each="user:${userList}"> <td th:text="${user.id}"></td> <td th:text="${user.name}"></td> <td th:text="${user.age}"></td> <td th:text="${user.hobby}"></td> <td> <a th:href="@{/user/toUserEdit(id=${user.id})}">编辑</a> <a th:href="@{/user/deleteUser(id=${user.id})}">删除</a> </td> </tr> </table> </div> </body> </html>
用户添加编辑页面user_edit.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>用户编辑添加</title> </head> <body> <form action="/user/userEdit" method="post"> <input type="hidden" name="id" th:field="${user.id}"> 用户姓名:<input type="text" name="name" th:field="${user.name}"><br /> 用户年龄:<input type="text" name="age" th:field="${user.age}"><br /> 用户爱好:<input type="text" name="hobby" th:field="${user.hobby}"><br /> <input type="submit" value="提交"> </form> </body> </html>
9、编写启动类
package com.bjsxt; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Created by Administrator on 2019/2/10. */ @SpringBootApplication @MapperScan("com.bjsxt.mapper") //指定mapper接口所在的位置 public class App { public static void main(String[] args){ SpringApplication.run(App.class,args); } }
在浏览器中访问即可http://localhost:8080/user/toUserList
10、最后目录结构
以上是关于SpringBoot学习10:springboot整合mybatis的主要内容,如果未能解决你的问题,请参考以下文章
学习笔记从零开始的SpringBoot新手教程(WIN10+JDK9+STS4)
springboot学习笔记10:DubboZookeeper