美文网首页springboot
SpringBoot 整合MyBatis

SpringBoot 整合MyBatis

作者: 月弦 | 来源:发表于2019-08-23 16:17 被阅读0次

    前言

    MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的XML或注解来配置和映射原生类型、接口和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

    一、建库建表

    • 建库
    CREATE DATABASE test;
    
    • 建表
    CREATE TABLE `users` (
      `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键id',
      `userName` varchar(32) DEFAULT NULL COMMENT '用户名',
      `passWord` varchar(32) DEFAULT NULL COMMENT '密码',
      `user_sex` varchar(32) DEFAULT NULL,
      `nick_name` varchar(32) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8;
    

    二、pom.xml文件

    添加MyBatis依赖和MySQL依赖.

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.7.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
    
        <groupId>com.huzh</groupId>
        <artifactId>springboot-mybatis</artifactId>
        <version>1.0-SNAPSHOT</version>
        <name>springboot-mybatis</name>
        <description>springboot-mybatis</description>
    
        <properties>
            <java.version>1.8</java.version>
            <mybatis.version>2.1.0</mybatis.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-jdbc</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <!--mybatis-->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>${mybatis.version}</version>
            </dependency>
            <!--mysql-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <scope>runtime</scope>
                <optional>true</optional>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    </project>
    

    三、实体类

    • 实体类
    public class User implements Serializable {
        private static final long serialVersionUID = 1L;
        private Long id;
        private String userName;
        private String passWord;
        private UserSexEnum userSex;
        private String nickName;
    
        public User() {
            super();
        }
    
        public User(String userName, String passWord, UserSexEnum userSex) {
            super();
            this.passWord = passWord;
            this.userName = userName;
            this.userSex = userSex;
        }
    
        public Long getId() {
            return id;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    
        public String getUserName() {
            return userName;
        }
    
        public void setUserName(String userName) {
            this.userName = userName;
        }
    
        public String getPassWord() {
            return passWord;
        }
    
        public void setPassWord(String passWord) {
            this.passWord = passWord;
        }
    
        public UserSexEnum getUserSex() {
            return userSex;
        }
    
        public void setUserSex(UserSexEnum userSex) {
            this.userSex = userSex;
        }
    
        public String getNickName() {
            return nickName;
        }
    
        public void setNickName(String nickName) {
            this.nickName = nickName;
        }
    
        @Override
        public String toString() {
            // TODO Auto-generated method stub
            return "userName " + this.userName + ", pasword " + this.passWord + "sex " + userSex.name();
        }
    }
    
    • 枚举类
    public enum UserSexEnum {
        MAN, WOMAN
    }
    

    四、两种整合模式

    - 注解模式

    1、配置mybatis和数据库

    spring:
      datasource:
        driver-class-name: com.mysql.jdbc.Driver
        username: root
        password: 123456
        url: jdbc:mysql://localhost:3306/test?serverTimezone=GMT
    mybatis:
      #这个配置用来指定bean在哪个包里,避免存在同名class时找不到bean
      type-aliases-package: com.huzh.springbootmybatisannotation.model
    

    2、编写 Mapper 层

    public interface UserMapper {
    
        @Select("SELECT * FROM users")
        @Results({
                @Result(property = "userSex", column = "user_sex", javaType = UserSexEnum.class),
                @Result(property = "nickName", column = "nick_name")
        })
        List<User> getAll();
    
        @Select("SELECT * FROM users WHERE id = #{id}")
        @Results({
                @Result(property = "userSex", column = "user_sex", javaType = UserSexEnum.class),
                @Result(property = "nickName", column = "nick_name")
        })
        User getOne(Long id);
    
        @Insert("INSERT INTO users(userName,passWord,user_sex) VALUES(#{userName}, #{passWord}, #{userSex})")
        void insert(User user);
    
        @Update("UPDATE users SET userName=#{userName},nick_name=#{nickName} WHERE id =#{id}")
        void update(User user);
    
        @Delete("DELETE FROM users WHERE id =#{id}")
        void delete(Long id);
    }
    

    3、创建controller

    @RestController
    public class UserController {
    
        @Autowired
        private UserMapper userMapper;
    
        @RequestMapping("/getUsers")
        public List<User> getUsers() {
            List<User> users=userMapper.getAll();
            return users;
        }
    
        @RequestMapping("/getUser")
        public User getUser(Long id) {
            User user=userMapper.getOne(id);
            return user;
        }
    
        @RequestMapping("/add")
        public void save(User user) {
            userMapper.insert(user);
        }
    
        @RequestMapping(value="update")
        public void update(User user) {
            userMapper.update(user);
        }
    
        @RequestMapping(value="/delete/{id}")
        public void delete(@PathVariable("id") Long id) {
            userMapper.delete(id);
        }
    }
    

    - xml模式

    1、配置mybatis和数据库

    • 指定了 Mybatis 基础配置文件和实体类映射文件的地址。
    spring:
      datasource:
        driver-class-name: com.mysql.jdbc.Driver
        username: root
        password: 123456
        url: jdbc:mysql://localhost:3306/test?serverTimezone=GMT
    mybatis:
      #这个配置用来指定bean在哪个包里,避免存在同名class时找不到bean
      type-aliases-package: com.huzh.springbootmybatisxml.model
      ##检查 mybatis 配置是否存在,一般命名为 mybatis-config.xml
      check-config-location: true
      ##配置文件位置
      config-location: classpath:mybatis/mybatis-config.xml
      ## dao xml 文件地址
      mapper-locations: classpath:mapper/*Mapper.xml
    
    • mybatis-config.xml 配置
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <typeAliases>
            <typeAlias alias="Integer" type="java.lang.Integer" />
            <typeAlias alias="Long" type="java.lang.Long" />
            <typeAlias alias="HashMap" type="java.util.HashMap" />
            <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
            <typeAlias alias="ArrayList" type="java.util.ArrayList" />
            <typeAlias alias="LinkedList" type="java.util.LinkedList" />
        </typeAliases>
    </configuration>
    
    • 添加 User 的映射文件
    <?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.huzh.springbootmybatisxml.mapper.UserMapper">
        <resultMap id="BaseResultMap" type="com.huzh.springbootmybatisxml.model.User">
            <id column="id" property="id" jdbcType="BIGINT"/>
            <result column="userName" property="userName" jdbcType="VARCHAR"/>
            <result column="passWord" property="passWord" jdbcType="VARCHAR"/>
            <result column="user_sex" property="userSex" javaType="com.huzh.springbootmybatisxml.enums.UserSexEnum"/>
            <result column="nick_name" property="nickName" jdbcType="VARCHAR"/>
        </resultMap>
        <parameterMap id="user" type="com.huzh.springbootmybatisxml.model.User"/>
    
        <sql id="Base_Column_List" >
            id, userName, passWord, user_sex, nick_name
        </sql>
    
        <select id="getAll" resultMap="BaseResultMap"  >
            SELECT
            <include refid="Base_Column_List" />
            FROM users
        </select>
    
        <select id="getOne" parameterType="java.lang.Long" resultMap="BaseResultMap" >
            SELECT
            <include refid="Base_Column_List" />
            FROM users
            WHERE id = #{id}
        </select>
    
        <insert id="insert" parameterMap="user" >
           INSERT INTO
                users
                (userName,passWord,user_sex)
            VALUES
                (#{userName}, #{passWord}, #{userSex})
        </insert>
    
        <update id="update" parameterMap="user" >
            UPDATE
            users
            SET
            <if test="userName != null">userName = #{userName},</if>
            <if test="passWord != null">passWord = #{passWord},</if>
            nick_name = #{nickName}
            WHERE
            id = #{id}
        </update>
    
        <delete id="delete" parameterType="java.lang.Long" >
           DELETE FROM
                 users
           WHERE
                 id =#{id}
        </delete>
    </mapper>
    

    2、编写 Mapper 层

    public interface UserMapper {
    
        List<User> getAll();
    
        User getOne(Long id);
    
        void insert(User user);
    
        void update(User user);
    
        void delete(Long id);
    }
    

    3、创建controller

    @RestController
    public class UserController {
    
        @Autowired
        private UserMapper userMapper;
    
        @RequestMapping("/getUsers")
        public List<User> getUsers() {
            List<User> users = userMapper.getAll();
            return users;
        }
    
        @RequestMapping("/getUser")
        public User getUser(Long id) {
            User user = userMapper.getOne(id);
            return user;
        }
    
        @RequestMapping("/add")
        public void save(User user) {
            userMapper.insert(user);
        }
    
        @RequestMapping(value = "update")
        public void update(User user) {
            userMapper.update(user);
        }
    
        @RequestMapping(value = "/delete/{id}")
        public void delete(@PathVariable("id") Long id) {
            userMapper.delete(id);
        }
    }
    

    5、启动类

    添加对 mapper 包扫描@MapperScan,可以直接在 Mapper 类上面添加注解@Mapper,建议使用下面那种,不然每个 mapper 要加个注解。

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

    相关文章

      网友评论

        本文标题:SpringBoot 整合MyBatis

        本文链接:https://www.haomeiwen.com/subject/iujzsctx.html