通过MyBatis操作数据库

时间:2020-07-30 01:48:35   收藏:0   阅读:122

MyBatis是一款优秀的持久层框架,同样也是做OR Mapping的。与JPA不同,MyBatis里面需要我们自己来定制sql。

MyBatis和JPA的选择

其实如果业务比较操作比较简单使用JPA加hibernate还是比较方便的。但是如果业务复杂即sql映射也复杂这个时候还是使用mybatis比较方便。另外在bat更多的使用是mybatis,这样dba对所写的业务sql能够有更强的把控。

SpringBoot中使用MyBatis

添加依赖

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

简单配置

Mapper的定义与扫描

MyBatis中映射有两种 一种是使用xml一种是使用注解(两者的选择,对于简单的场景使用注解比较方便;但是对于复杂的查询业务还是使用xml的方式比较方便)。另外使用@MapperScan配置扫描Mapper文件的位置,使用@Mapper注解标识Mapper文件。如下代码是使用注解的使用定义的Mapper文件的映射,并使用@Mapper注解标识是Mapper文件。

/**
 * Created by zhangdd on 2020/7/29
 */
@Mapper
public interface CoffeeMapper {
    @Insert("insert into t_coffee (name, price, create_time, update_time)"
            + "values (#{name}, #{price}, now(), now())")
    @Options(useGeneratedKeys = true)
    Long save(Coffee coffee);

    @Select("select * from t_coffee where id = #{id}")
    @Results({
            @Result(id = true, column = "id", property = "id"),
            @Result(column = "create_time", property = "createTime"),
            // map-underscore-to-camel-case = true 可以实现一样的效果
            // @Result(column = "update_time", property = "updateTime"),
    })
    Coffee findById(@Param("id") Long id);
}

调用Mapper方法执行sql

package com.lucky.spring;

import com.lucky.spring.mapper.CoffeeMapper;
import com.lucky.spring.model.Coffee;
import lombok.extern.slf4j.Slf4j;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.lucky.spring.mapper")
@Slf4j
public class Application implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Autowired
    private CoffeeMapper coffeeMapper;

    @Override
    public void run(String... args) throws Exception {
        Coffee c = Coffee.builder().name("espresso")
                .price(Money.of(CurrencyUnit.of("CNY"), 20.0)).build();
        Long id = coffeeMapper.save(c);
        log.info("Coffee {} => {}", id, c);

        c = coffeeMapper.findById(id);
        log.info("Coffee {}", c);
    }
}

打印结果如下

2020-07-29 22:20:53.251  INFO 78971 --- [           main] com.lucky.spring.Application             : Coffee 1 => Coffee(id=5, name=espresso, price=CNY 20.00, createTime=null, updateTime=null)
2020-07-29 22:20:53.265  INFO 78971 --- [           main] com.lucky.spring.Application             : Coffee Coffee(id=1, name=espresso, price=CNY 20.00, createTime=Wed Jul 29 22:07:31 CST 2020, updateTime=Wed Jul 29 22:07:31 CST 2020)

可以看到有时候插入数据后,我们需要这个数据的ID;同时查询数据的时间格式不一定是我们所需要的。这些场景如何结局呢?如下:

时间返回格式 和 显示null值字段

#所有日期格式
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
# 所有字段都不过滤 null值也显示
spring.jackson.default-property-inclusion=always

获取插入数据的自增ID

使用注解的映射Mapper文件

使用@Options注解的useGeneratedKeys属性。useGeneratedKeys设为true是表示使用jdbc的getGeneratedKeys方法来取出数据的主键值(默认为false)

使用xml映射

同样也是使用 useGeneratedKeys 设置为true,keyProperty标记返回的主键值传递给某个具体的属性

<insert id="add2" parameterType="employee"  useGeneratedKeys="true" keyProperty="id">
	insert into employee(username) values(#{username})
</insert>
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!