SpringBoot(五) mybatis

[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);
    }
}

進行測試

查詢數據

插入數據

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章