springboot整合mybatis

x33g5p2x  于11个月前 转载在 Spring  
字(8.2k)|赞(0)|评价(0)|浏览(146)

springboot整合mybatis

1.准备工作

1.创建用户信息表(tb_user)

-- 判断数据表是否存在,存在则删除
DROP TABLE IF EXISTS tb_user;
 
-- 创建“用户信息”数据表
CREATE TABLE IF NOT EXISTS tb_user
( 
	user_id INT AUTO_INCREMENT PRIMARY KEY COMMENT '用户编号',
	user_account VARCHAR(50) NOT NULL COMMENT '用户账号',
	user_password VARCHAR(50) NOT NULL COMMENT '用户密码',
	blog_url VARCHAR(50) NOT NULL COMMENT '博客地址',
	remark VARCHAR(50) COMMENT '备注'
) COMMENT = '用户信息表';
 
-- 添加数据
INSERT INTO tb_user(user_account,user_password,blog_url,remark) VALUES('拒绝熬夜啊的博客','123456','https://blog.csdn.net/weixin_43296313/','您好,欢迎访问拒绝熬夜啊的博客');

2、创建项目

项目结构如下

添加pom.xml配置信息
<!-- MyBatis与SpringBoot整合依赖 -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
</dependency>
 
<!-- MySQL的JDBC数据库驱动 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.20</version>
</dependency>
 
<!-- 引入Thymeleaf模板引擎 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
配置相关信息
spring:
  #DataSource数据源
  datasource:
    url: jdbc:mysql://localhost:3306/mybatis_test?useSSL=false&amp
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver
  #使用Thymeleaf模板引擎
  thymeleaf:
    mode: HTML5
    encoding: UTF-8
    cache: false  #使用Thymeleaf模板引擎,关闭缓存
    servlet:
      content-type: text/html

#MyBatis配置
mybatis:
  type-aliases-package: com.mye.hl08springbootmybatis.api.pojo #别名定义
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #指定 MyBatis 所用日志的具体实现,未指定时将自动查找
    map-underscore-to-camel-case: true #开启自动驼峰命名规则(camel case)映射
    lazy-loading-enabled: true #开启延时加载开关
    aggressive-lazy-loading: false #将积极加载改为消极加载(即按需加载),默认值就是false
    lazy-load-trigger-methods: "" #阻挡不相干的操作触发,实现懒加载
    cache-enabled: true #打开全局缓存开关(二级环境),默认值就是true
实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserInfo {
    private int userId; //用户编号
    private String userAccount; //用户账号
    private String userPassword; //用户密码
    private String blogUrl; //博客地址
    private String remark; //博客备注

}
mapper层
@Repository
//实现实体和数据表的映射关系可以在Mapper类上添加@Mapper注解
//但是建议以后直接在SpringBoot启动类中加 @MapperScan("com.mye.hl08springbootmybatis.api.mapper")注解,这样会比较方便,不需要对每个Mapper都添加@Mapper注解。
@Mapper
public interface UserMapper {
    /** * 新增用户,并获取自增主键 */
    @Insert("INSERT INTO tb_user(user_account,user_password,blog_url,remark) VALUES(#{userAccount},#{userPassword},#{blogUrl},#{remark})")
    @Options(useGeneratedKeys = true, keyColumn = "user_id", keyProperty = "userId")
    //或者:@SelectKey(statement = "SELECT LAST_INSERT_ID()", keyColumn = "user_id", keyProperty = "userId",before = false, resultType = Integer.class)
    int insertUser(UserInfo userInfo);
 
    /** * 修改用户 */
    @Update("UPDATE tb_user SET user_account = #{userAccount} ,user_password = #{userPassword} ,blog_url=#{blogUrl} ,remark=#{remark} WHERE user_id = #{userId}")
    int updateUser(UserInfo userInfo);
 
    /** * 删除用户 */
    @Delete("DELETE FROM tb_user WHERE user_id = #{userId}")
    int deleteUser(int userId);
 
    /** * 根据用户ID,获取用户信息 */
    @Select("SELECT * FROM tb_user WHERE user_id = #{userId}")
    UserInfo getUserById(int userId);
}
userService接口
public interface UserService {
    /** * 新增用户,并获取自增主键 */
    int insertUser(UserInfo userInfo);
 
    /** * 修改用户 */
    int updateUser(UserInfo userInfo);
 
    /** * 删除用户 */
    int deleteUser(int userId);
 
    /** * 根据用户ID,获取用户信息 */
    UserInfo getUserById(int userId);
}
userServiceImpl实现类
@Service
public class UserServiceImpl implements UserService {
 
    @Autowired
    private UserMapper userMapper;
 
    /** * 新增用户,并获取自增主键 */
    @Override
    public int insertUser(UserInfo userInfo)
    {
        return userMapper.insertUser(userInfo);
    }
 
    /** * 修改用户 */
    @Override
    public int updateUser(UserInfo userInfo)
    {
        return userMapper.updateUser(userInfo);
    }
 
    /** * 删除用户 */
    @Override
    public int deleteUser(int userId)
    {
        return userMapper.deleteUser(userId);
    }
 
    /** * 根据用户ID,获取用户信息 */
    @Override
    public UserInfo getUserById(int userId)
    {
        return userMapper.getUserById(userId);
    }
}
controller层
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
 
    /** * 新增用户 */
    @RequestMapping("/insertUser")
    @ResponseBody
    public boolean insertUser() {
        boolean result = false;
 
        //创建新用户
        UserInfo userInfo = new UserInfo();
        userInfo.setUserAccount("拒绝熬夜啊的博客");
        userInfo.setUserPassword("123456");
        userInfo.setBlogUrl("https://blog.csdn.net/weixin_43296313/");
        userInfo.setRemark("您好,欢迎访问 拒绝熬夜啊的博客");
        int count = userService.insertUser(userInfo);
 
        //返回结果
        result = count > 0;
        return result;
    }
 
    /** * 修改用户 */
    @RequestMapping("/updateUser")
    @ResponseBody
    public boolean updateUser(int userId) {
        //创建修改用户
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(userId);
        userInfo.setUserAccount("pan_junbiao的博客_02");
        userInfo.setUserPassword("123456");
        userInfo.setBlogUrl("https://blog.csdn.net/pan_junbiao");
        userInfo.setRemark("您好,欢迎访问 pan_junbiao的博客");
        int count = userService.updateUser(userInfo);

        return count > 0;
    }
 
    /** * 删除用户 */
    @RequestMapping("/deleteUser")
    @ResponseBody
    public boolean deleteUser(int userId) {
        //执行删除用户
        int count = userService.deleteUser(userId);
        //返回结果
        return count > 0;
    }
 
 
    /** * 根据用户ID,获取用户信息 */
    @RequestMapping("/getUserById")
    public ModelAndView getUserById(int userId) {
        UserInfo userInfo = userService.getUserById(userId);
 
        //返回结果
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("userInfo", userInfo);
        modelAndView.setViewName("userInfo.html");
        return modelAndView;
    }
}
启动类
@SpringBootApplication
@MapperScan(basePackages = "com.mye.hl08springbootmybatis.api.mapper")
public class Hl08SpringbootMybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(Hl08SpringbootMybatisApplication.class, args);
    }

}

2.综合实例

2.1查询用户

http://127.0.0.1:8080/user/getUserById?userId=1

在resources/templates目录下,创建 userInfo.html 用户信息显示页面。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户信息</title>
    <meta name="author" content="pan_junbiao的博客">
    <style> table { border-collapse: collapse; margin-bottom: 10px} table,table tr th, table tr td { border:1px solid #000000; padding: 5px 10px;} </style>
</head>
<body>
<div align="center">
    <table>
        <caption>用户信息</caption>
        <tr>
            <th>用户ID:</th>
            <td th:text="${userInfo.userId}"></td>
        </tr>
        <tr>
            <th>用户姓名:</th>
            <td th:text="${userInfo.userAccount}"></td>
        </tr>
        <tr>
            <th>博客地址:</th>
            <td th:text="${userInfo.blogUrl}"></td>
        </tr>
        <tr>
            <th>博客信息:</th>
            <td th:text="${userInfo.remark}"></td>
        </tr>
    </table>
</div>
</body>
</html>

controller

/** * 根据用户ID,获取用户信息 */
    @RequestMapping("/getUserById")
    public ModelAndView getUserById(int userId) {
        UserInfo userInfo = userService.getUserById(userId);
 
        //返回结果
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("userInfo", userInfo);
        modelAndView.setViewName("userInfo.html");
        return modelAndView;

执行结果

2.2新增用户

http://127.0.0.1:8080/user/insertUser

controller

/** * 新增用户 */
    @RequestMapping("/insertUser")
    @ResponseBody
    public boolean insertUser() {
        boolean result = false;
 
        //创建新用户
        UserInfo userInfo = new UserInfo();
        userInfo.setUserAccount("拒绝熬夜啊的博客");
        userInfo.setUserPassword("123456");
        userInfo.setBlogUrl("https://blog.csdn.net/weixin_43296313/");
        userInfo.setRemark("您好,欢迎访问 拒绝熬夜啊的博客");
        int count = userService.insertUser(userInfo);
 
        //返回结果
        result = count > 0;
        return result;
    }

执行结果

2.2修改用户

http://127.0.0.1:8080/user/updateUser?userId=1

controller

/** * 修改用户 */
    @RequestMapping("/updateUser")
    @ResponseBody
    public boolean updateUser(int userId) {
        //创建修改用户
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(userId);
        userInfo.setUserAccount("pan_junbiao的博客_02");
        userInfo.setUserPassword("123456");
        userInfo.setBlogUrl("https://blog.csdn.net/pan_junbiao");
        userInfo.setRemark("您好,欢迎访问 pan_junbiao的博客");
        int count = userService.updateUser(userInfo);

        return count > 0;
    }

执行结果

2.4删除用户
http://127.0.0.1:8080/user/deleteUser?userId=1

controller

/** * 删除用户 */
    @RequestMapping("/deleteUser")
    @ResponseBody
    public boolean deleteUser(int userId) {
        //执行删除用户
        int count = userService.deleteUser(userId);
        //返回结果
        return count > 0;
    }

执行结果

相关文章