一、认识 MyBatis()
1、MyBatis
(
https://github.com/mybatis/mybatis-3
)
A、⼀款优秀的持久层框架
B、⽀持定制化
SQL
、存储过程和⾼级映射
2、Jpa和MyBatis的区别
A、JPA是Java EE的一部分,提供了一种对象关系映射(ORM)技术,将Java类映射到关系型数据库表中。JPA提供了标准化的API,使开发人员可以使用面向对象的方式来操作数据,而不需要编写SQL语句。JPA可以使用Hibernate等实现来实现其规范。
B、MyBatis是一个轻量级的持久层框架,使用XML文件来描述SQL语句和映射关系,通过SQL语句与Java方法之间的映射来实现数据的持久化操作。相比于JPA,MyBatis更加灵活,可以直接编写SQL语句,以及更好的支持存储过程和复杂的查询。
3、在
Spring
中使⽤
MyBatis
A、MyBatis Spring Adapter
(
https://github.com/mybatis/spring
)
B、MyBatis Spring-Boot-Starter
(
https://github.com/mybatis/spring)(springboot里)
二、简单配置(application.properties)
1、mybatis.mapper-locations = classpath*:mapper/**/*.xml (mybatis映射文件位置)
2、mybatis.type-aliases-package
= 类型别名的包名(指定 MyBatis 应该扫描的类型别名所在的包名。
)
3、mybatis.type-handlers-package = TypeHandler扫描包名(定 MyBatis 应该扫描的 TypeHandler 所在的包名。TypeHandler 可以在 MyBatis 将数据库查询结果转换为 Java 对象时进行类型转换,
)
4、mybatis.configuration.map-underscore-to-camel-case = true(将下划线转换为驼峰规则)
三、Mapper的定义与配置
1、@MapperScan
配置扫描位置
2、@Mapper
定义接⼝
3、映射的定义
—— XML 或
注解或混用
四、代码
1、pom.xml中添加依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
2、application.properties
mybatis.type-handlers-package=geektime.spring.data.mybatisdemo.handler
mybatis.configuration.map-underscore-to-camel-case=true
3、schema.sql
create table t_coffee (
id bigint not null auto_increment,
name varchar(255),
price bigint not null,
create_time timestamp,
update_time timestamp,
primary key (id)
);
4、handler.MoneyTypeHandler(实现Money类型到Long类型的转换)
package geektime.spring.data.mybatisdemo.handler;
/**
* 在 Money 与 Long 之间转换的 TypeHandler,处理 CNY 人民币
*/
public class MoneyTypeHandler extends BaseTypeHandler<Money> {
@Override// 设置值时的操作,将人民币Money类型转换为Long类型
public void setNonNullParameter(PreparedStatement ps, int i, Money parameter/*传入Money类型*/, JdbcType jdbcType) throws SQLException {
ps.setLong(i, parameter.getAmountMinorLong());
}
@Override//取值时的操作
public Money getNullableResult(ResultSet rs, String columnName) throws SQLException {
return parseMoney(rs.getLong(columnName));
}
@Override//取值时的操作
public Money getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return parseMoney(rs.getLong(columnIndex));
}
@Override//取值时的操作
public Money getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return parseMoney(cs.getLong(columnIndex));
}
private Money parseMoney(Long value) {//将Long类型转换为人民币类型
return Money.of(CurrencyUnit.of("CNY"), value / 100.0);
}
}
5、model下的Coffee
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Coffee {
private Long id;
private String name;
private Money price;
private Date createTime;
private Date updateTime;
}
6、mapper下的CoffeeMapper
package geektime.spring.data.mybatisdemo.mapper;
@Mapper
public interface CoffeeMapper {
//插入
@Insert("insert into t_coffee (name, price, create_time, update_time)"
+ "values (#{name}, #{price}, now(), now())")
@Options(useGeneratedKeys = true)
int 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);
}
7、主类
package geektime.spring.data.mybatisdemo;
@SpringBootApplication
@Slf4j
@MapperScan("geektime.spring.data.mybatisdemo.mapper")//扫描我的Mapper
public class MybatisDemoApplication implements ApplicationRunner {
@Autowired
private CoffeeMapper coffeeMapper;
public static void main(String[] args) {
SpringApplication.run(MybatisDemoApplication.class, args);
}
@Override
public void run(ApplicationArguments args) throws Exception {
//创建了两个Coffee
Coffee c = Coffee.builder().name("espresso")
.price(Money.of(CurrencyUnit.of("CNY"), 20.0)).build();
int count = coffeeMapper.save(c);//插入
log.info("Save {} Coffee: {}", count, c);
c = Coffee.builder().name("latte")
.price(Money.of(CurrencyUnit.of("CNY"), 25.0)).build();
count = coffeeMapper.save(c);//插入
log.info("Save {} Coffee: {}", count, c);
c = coffeeMapper.findById(c.getId());//查询
log.info("Find Coffee: {}", c);
}
}
8、结果