• springboot整合Mybatis(无xml)


     1、pom文件 依赖引入

    <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.8.RELEASE</version>
            <relativePath />
        </parent>
    
        <dependencies>
            <!-- SpringBoot 测试 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
    
            <!-- mybatis 支持 SpringBoot -->
            <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>
                <version>5.1.38</version>
            </dependency>
    
            <!-- SpringBoot web组件 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
        </dependencies>

    2、 application.yml 新增配置

    spring:
      datasource:
        url: jdbc:mysql://localhost:3306/yys_springboot_mybatis?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
        username: root
        password: 123456
        driver-class-name: com.mysql.cj.jdbc.Driver

    3、UserEntity.java

    /**
     * 用户管理
     *      Entity
     * @author yys
     */
    
    import com.fasterxml.jackson.annotation.JsonFormat;
    
    import java.io.Serializable;
    import java.sql.Date;
    
    public class UserEntity implements Serializable {
    
        private Long id;
    
        private String name;
    
        private Integer age;
    
        private Byte status;
    
        @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="GMT+8")
        private Date createTime;
    
        @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="GMT+8")
        private Date updateTime;
    
        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 Integer getAge() {
            return age;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
    
        public Byte getStatus() {
            return status;
        }
    
        public void setStatus(Byte status) {
            this.status = status;
        }
    
        public Date getCreateTime() {
            return createTime;
        }
    
        public void setCreateTime(Date createTime) {
            this.createTime = createTime;
        }
    
        public Date getUpdateTime() {
            return updateTime;
        }
    
        public void setUpdateTime(Date updateTime) {
            this.updateTime = updateTime;
        }
    
    }

    4、UserController.java

    /**
     * 用户管理
     *      Controller
     * @author yys
     */
    @RestController
    @RequestMapping("/user")
    public class UserController {
    
        @Autowired
        private UserService userService;
    
        @RequestMapping("/add")
        public String addUser(String userName, Integer age) {
            return userService.addUser(userName, age) ? "success" : "fail";
        }
    
        @RequestMapping("/get")
        public UserEntity getUserByName(String userName) {
            return userService.getUserByName(userName);
        }
    
    }

    5、UserService.java

    /**
     * 用户管理
     *      Service
     * @author yys
     */
    @Service
    public class UserService {
    
        @Autowired
        private UserMapper userMapper;
    
        public boolean addUser(String userName, Integer age) {
            return userMapper.insert(userName, age) > 0 ? true : false;
        }
    
        public UserEntity getUserByName(String userName) {
            return userMapper.findByName(userName);
        }
    
    }

    6、UserMapper.java

    /**
     * 用户管理
     *      Mapper
     * @author yys
     */
    public interface UserMapper {
    
        @Select("SELECT id, user_name AS name, age, status, create_time AS createTime, update_time AS updateTime FROM yys_user WHERE user_name = #{name}")
        UserEntity findByName(@Param("name") String name);
    
        @Insert("INSERT INTO yys_user VALUES (NULL, #{name}, #{age}, 1, NOW(), NOW())")
        int insert(@Param("name") String name, @Param("age") Integer age);
    
    }

    7、启动类

    @SpringBootApplication
    @MapperScan("com.yys.mapper")
    public class YysApp {
    
        public static void main(String[] args) {
            SpringApplication.run(YysApp.class, args);
        }
    
    }

    8、初始化sql文件

    CREATE TABLE `yys_user` (
      `id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT 'ID,自增列',
      `user_name` varchar(32) NOT NULL COMMENT '用户名',
      `age` int(11) NOT NULL COMMENT '用户年龄',
      `status` tinyint(2) NOT NULL DEFAULT '1' COMMENT '状态:-1-删除;1-正常;',
      `create_time` datetime NOT NULL COMMENT '创建时间',
      `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

    9、测试

    http://localhost:8080/user/add?userName=yys&age=18

      a、页面结果 - 如下图所示 :

    _b、数据库结果 - 如下图所示 :_ 

    http://localhost:8080/user/get?userName=yys

      a、页面结果 - 如下图所示 :

  • 相关阅读:
    MPlayer源代码分析
    洛谷 P1025 数的划分
    洛谷 P1209 [USACO1.3]修理牛棚 Barn Repair
    洛谷 P1744 采购特价商品
    洛谷 P1443 马的遍历
    洛谷 P1294 高手去散步
    洛谷 P2104 二进制
    洛谷 P1088 火星人
    洛谷 P1062 数列
    洛谷 P2005 A/B Problem II
  • 原文地址:https://www.cnblogs.com/lvchengda/p/12619459.html
Copyright © 2020-2023  润新知