美文网首页SpringBoot
SpringBoot(五) mybatis

SpringBoot(五) mybatis

作者: 间歇性丶神经病患者 | 来源:发表于2018-12-20 22:36 被阅读24次

    [toc]

    前言

    最近公司app项目2.5进入了收尾阶段,基本Task也都完成了,也就剩下小部分的UI走查和重构,所以重拾下SpringBoot学习。

    一开始就卡在了mybatis上面,实在是没用过...一开始还傻傻地问开发大佬:
    redis和mybatis的区别啥的...哎,真惭愧。

    hibernate和Mybatis的比较

    这个我还了解得不多,等我网罗好资料再来完善

    Mybatis 初步使用

    项目结构

    项目结构

    导入MyBatis

    在pom文件中导入

    <dependency>
       <groupId>org.mybatis.spring.boot</groupId>
       <artifactId>mybatis-spring-boot-starter</artifactId>
       <version>1.3.0</version>
    </dependency>
    

    导入MySql驱动

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    

    完整的pom文件如下:

    <?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 http://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.1.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.Ly</groupId>
        <artifactId>mybatis</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>mybatis</name>
        <description>Demo project for Spring Boot</description>
    
        <properties>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
    
            <!-- mysql 数据库驱动. -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.3.0</version>
            </dependency>
    
            <!-- 分页插件.  最低是4.1.5 -->
            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper</artifactId>
                <version>4.2.1</version>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    
    

    配置

    链接数据库配置

    spring.datasource.url = jdbc:mysql://localhost:3306/blog?serverTimezone=UTC
    spring.datasource.username = root
    spring.datasource.password = 123456
    spring.datasource.driverClassName = com.mysql.jdbc.Driver
    spring.datasource.max-active=20
    spring.datasource.max-idle=8
    spring.datasource.min-idle=8
    spring.datasource.initial-size=10
    
    logging.level.com.kfit=DEBUG
    

    配置MyBatis

    在application中配置Mapper扫描

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

    注意这里com.ly.mybatis.mapper对应的是我们包结构里面的mapper

    搭建实体类

    User类

    /**
     * Author: Ly
     * Data:2018/12/19-22:41
     * Description:
     */
    
    public class User {
        private int id;
        private String name;
        private Date updateTime;
        private SexEnums sex;
        private String email;
    
        public User() {
        }
    
        public User(int id, String name, Date updateTime, SexEnums sex, String email) {
            this.id = id;
            this.name = name;
            this.updateTime = updateTime;
            this.sex = sex;
            this.email = email;
        }
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Date getUpdateTime() {
            return updateTime;
        }
    
        public void setUpdateTime(Date updateTime) {
            this.updateTime = updateTime;
        }
    
        public SexEnums getSex() {
            return sex;
        }
    
        public void setSex(SexEnums sex) {
            this.sex = sex;
        }
    
        public String getEmail() {
            return email;
        }
    
        public void setEmail(String email) {
            this.email = email;
        }
    }
    
    

    定义Sex枚举

    BaseEnum

    /**
     * Author: Ly
     * Data:2018/12/20-21:08
     * Description:
     */
    public interface BaseEnum {
        int getValue();
    }
    
    

    SexEnums

    /**
     * Author: Ly
     * Data:2018/12/19-22:57
     * Description:
     */
    public enum SexEnums implements BaseEnum {
        MAN(1), WOMEN(2);
    
        SexEnums(int type) {
            this.type = type;
        }
    
        int type;
    
        @Override
        public int getValue() {
            return type;
        }
    }
    

    枚举工具类

    因为我们User里面使用了枚举,那前端该怎么传对应的值过来的?
    在之前做安卓的时候有这种情况,解决方法一般是:

    直接使用

    因为是app内部,所以直接使用枚举类就ok了,虽然这个是废话...

    枚举内部进行一个遍历

    但是如果是app外部,比如说和vue交互的时候,这个方法就不可以了,所以我会在枚举里面做文章,这样vue只需要传对应的index就那可以。

    public enum MODEL {
            //关注,粉丝
            FOLLOW("关注",0), FANS("粉丝",1);
    
            private String name;
            private int index;
            MODEL(String name,int index){
                this.name = name;
                this.index = index;
            }
    
            public static String getName(int index){
                for (MODEL m:MODEL.values()){
                    if (m.getIndex() == index){
                        return m.getName();
                    }
                }
                return null;
            }
    
            public static MODEL getType(int index){
                for (MODEL m:MODEL.values()){
                    if (m.getIndex() == index){
                        return m;
                    }
                }
                return null;
            }
    
            public String getName() {
                return name;
            }
    
            public void setName(String name) {
                this.name = name;
            }
    
            public int getIndex() {
                return index;
            }
    
            public void setIndex(int index) {
                this.index = index;
            }
        }
    
    使用Converter

    不过上面的方法感觉都比较low,在springboot里面我们可以用比较新的方法

    UniversalEnumConverterFactory
    /**
     * Author: Ly
     * Data:2018/12/20-21:07
     * Description:
     */
    public class UniversalEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    
        private static final Map<Class, Converter> converterMap = new WeakHashMap<>();
    
        @Override
        public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
            Converter result = converterMap.get(targetType);
            if(result == null) {
                result = new IntegerStrToEnum<T>(targetType);
                converterMap.put(targetType, result);
            }
            return result;
        }
    
        class IntegerStrToEnum<T extends BaseEnum> implements Converter<String, T> {
            private final Class<T> enumType;
            private Map<String, T> enumMap = new HashMap<>();
    
            IntegerStrToEnum(Class<T> enumType) {
                this.enumType = enumType;
                T[] enums = enumType.getEnumConstants();
                for(T e : enums) {
                    enumMap.put(e.getValue() + "", e);
                }
            }
    
    
            @Override
            public T convert(String source) {
                T result = enumMap.get(source);
                if(result == null) {
                    throw new IllegalArgumentException("No element matches " + source);
                }
                return result;
            }
        }
    }
    
    
    MyWebAppConfigurer配置文件
    /**
     * Author: Ly
     * Data:2018/12/20-21:06
     * Description:
     */
    @Configuration
    class MyWebAppConfigurer extends WebMvcConfigurerAdapter {
        @Override
        public void addFormatters(FormatterRegistry registry) {
            registry.addConverterFactory(new UniversalEnumConverterFactory());
        }
    }
    

    定义需要的mapper

    /**
     * Author: Ly
     * Data:2018/12/19-23:27
     * Description:
     */
    @Repository
    public  interface UserMapper {
    
    
        @Select("select * from User where name =#{name}")
        List<User> getUserListLikeName(String name);
    
        @Select("select * from user")
        List<User> findAllUser();
    
    
        @Select("select * from User where id= #{id}")
        User getUserById(long id);
    
        @Insert("insert into User(name,email,sex,updateTime) values (#{name},#{email},#{sex},#{updateTime})")
        @Options(useGeneratedKeys=true, keyColumn="id")
        void insert(User user);
    }
    

    定义需要的Service

    /**
     * Author: Ly
     * Data:2018/12/19-23:34
     * Description:
     */
    @Service
    public class UserService {
        private final UserMapper mUserMapper;
    
        @Autowired
        public UserService(UserMapper mUserMapper) {
            this.mUserMapper = mUserMapper;
        }
        public void addUser(User user){
            mUserMapper.insert(user);
        }
        public List<User> findAllUser(){
            return mUserMapper.findAllUser();
        }
        public List<User> getUserLikeName(String name) {
            return mUserMapper.getUserListLikeName(name);
        }
    }
    

    定义需要的Controller

    /**
     * Author: Ly
     * Data:2018/12/19-23:40
     * Description:
     */
    @RestController
    class UserController {
    
    
        private final UserService mUserService;
    
        @Autowired
        public UserController(UserService mUserService) {
            this.mUserService = mUserService;
        }
    
    
        @GetMapping("/findAllUser")
        public List<User> findAllUser(){
            return mUserService.findAllUser();
        }
        @GetMapping("/getUserLikeName")
        public List<User> getUserLikeName(@RequestParam(value = "name")String name){
            return mUserService.getUserLikeName(name);
        }
    
        @PostMapping("/addUser")
        public void addUser(User user){
            user.setUpdateTime(new Date());
            mUserService.addUser(user);
        }
    }
    
    

    进行测试

    查询数据

    image.png

    插入数据

    image.png

    相关文章

      网友评论

        本文标题:SpringBoot(五) mybatis

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