MyBatis 注解的使用

作者: 右耳菌 | 来源:发表于2022-04-29 00:49 被阅读0次
    数据库表准备

    两张测试用表,用以测试使用

    • users 表
    CREATE TABLE users (
      id int(11) NOT NULL AUTO_INCREMENT,
      name varchar(255)  DEFAULT NULL,
      username varchar(255) NOT NULL,
      password varchar(255) NOT NULL,
      PRIMARY KEY (id),
      UNIQUE KEY UK_username (username)
    ) ENGINE=InnoDB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8
    
    • product 表
    CREATE TABLE product (
        id int(11) NOT NULL AUTO_INCREMENT,
        name char(20) NOT NULL DEFAULT '',
        description char(100) DEFAULT NULL,
        price int(7) NOT NULL,
        pic char(20) DEFAULT NULL,
        uid int(11) NOT NULL DEFAULT 0,
        PRIMARY KEY (id)
    ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET = utf8
    

    例子
    1. 创建SpringBoot项目
    2. pom.xml引入以下依赖
       <dependencies>
            <!-- MyBatis -->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.2.2</version>
            </dependency>
            <!-- MySQL驱动 -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>
            <!-- 引入Lombok, 如何启用请查看 https://www.jianshu.com/p/9109d2d0b432  -->
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <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>
                    <configuration>
                        <excludes>
                            <exclude>
                                <groupId>org.projectlombok</groupId>
                                <artifactId>lombok</artifactId>
                            </exclude>
                        </excludes>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    
    3. 修改application.properties
    #mysql的配置信息
    spring.datasource.url=jdbc:mysql://localhost:3306/cloud_study?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
    spring.datasource.username=####(账号)
    spring.datasource.password=####(密码)
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    
    #展示sql语句
    logging.level.cn.lazyfennec.springboot.repository=debug
    
    #MyBatis的配置, 本项目使用注解版,故不需要以下配置
    #设置mybatis的配置文件路径,默认是在resources的目录
    #mybatis.config-location=classpath:mybatis/mybatis-config.xml
    #设置mybatis下面的mapper映射文件路径,默认是在resources的目录
    #mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
    #设置项目中实体类包路径;
    #mybatis.type-aliases-package=cn.lazyfennec.springboot.entity
    
    4. 创建实体类
    • Users
    package cn.lazyfennec.springboot.entity;
    
    import lombok.Data;
    
    import java.util.List;
    
    /**
     * @Author: Neco
     * @Description:
     * @Date: create in 2022/4/29 0:20
     */
    @Data
    public class Users {
        private Integer id;
        private String name;
        private String username;
        private String password;
        private List<Product> products;
    }
    
    • Product
    package cn.lazyfennec.springboot.entity;
    
    import lombok.Data;
    
    /**
     * @Author: Neco
     * @Description:
     * @Date: create in 2022/4/29 0:21
     */
    @Data
    public class Product {
        private Integer id;
        private String name;
        private String description;
        private Double price;
        private String pic;
        private Integer uid; // users 的 id
    }
    
    5. 常用注解
    • @Select
        @Select("select id, name, username, password from users")
        public List<Users> findAll();
    
        @Select("select id, name, username, password from users where id=#{id}")
        public Users findById(@Param("id") String id);
    
    • @Update
        @Update("update set name=#{users.name}, password=#{users.password} where id = #{users.id}")
        public void updateUsers(@Param("users") Users users);
    
    • @Insert
        @Insert("insert into users (name, username, password) values(#{users.name}, #{users.username}, #{users.password})")
        public void insertUser(@Param("users") Users users);
    
    • @Delete
        @Delete("delete from users where id=#{id}")
        public void deleteUserById(Integer id);
    
    6. 更复杂的注解用法
    • @Results 类比 <resultMap>
    • @Result 类比 <result> 和 <id>
    • @Many 类比 <collection>
    • @One 类比 <association>

    使用例子如下

    • UsersRepository
    package cn.lazyfennec.springboot.repository;
    
    import cn.lazyfennec.springboot.entity.Users;
    import org.apache.ibatis.annotations.*;
    
    import java.util.List;
    
    public interface UsersRepository {
        @Select("select id, name, username, password from users")
        public List<Users> findAll();
    
        @Select("select id, name, username, password from users where id=#{id}")
        public Users findById(@Param("id") String id);
    
        @Update("update set name=#{users.name}, password=#{users.password} where id = #{users.id}")
        public void updateUsers(@Param("users") Users users);
    
        @Insert("insert into users (name, username, password) values(#{users.name}, #{users.username}, #{users.password})")
        public void insertUser(@Param("users") Users users);
    
        @Delete("delete from users where id=#{id}")
        public void deleteUserById(Integer id);
    
    
        @Select("select * from Users where id=#{id}")
        @Results({
                @Result(
                        property = "products", column = "id", many = @Many(select = "com.study.mybatis.repository.ProductRepository.findByUid")
                )
        })
        Users findUsersById(int id);
    }
    
    • ProductRepository
    package cn.lazyfennec.springboot.repository;
    
    import cn.lazyfennec.springboot.entity.Product;
    import org.apache.ibatis.annotations.Select;
    
    public interface ProductRepository {
        @Select("select * from Product where uid=#{uid}")
        Product findByUid(int uid);
    }
    

    7. 更多注解相关内容,请查看 官网 https://mybatis.org/mybatis-3/zh/java-api.html

    更多知识,请点击关注查看我的主页信息哦~

    相关文章

      网友评论

        本文标题:MyBatis 注解的使用

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