1. mybatis简单介绍
MyBatis 是一款优秀的持久层框架。mybatis也是一个ORM框架。
2. quick start 快速开始(springboot +mybatis)
springboot 引入依赖和配置
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>springboot的配置和数据源配置
server:
port: 10520
#数据源配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/demo?serverTimezone=UTC
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
#日志级别一定要debug级别,否则mybatis日志无法看到
logging:
level:
io.xuehao: debugmybatis配置
mybatis所需的文件类型
- 数据库中表映射的对象 -> domain包
- 操作的接口 ->mapper包
- 接口xml文件 映射的实现 ->resources/mapping
配置文件
mybatis:
mapper-locations: classpath:/mapping/*.xml
type-aliases-package: io.xuehao.domain创建一个订单模型的持久化层代码
1. 创建了domain
2.创建了接口,使用了@mapper注解。有两个作用:1. 是让mybatis框架认识这个接口 2. 让spring 管理这个bean。
3. 创建xml 映射文件。使用<mapper>节点。mapper namespace属性是java接口的完整路径。
进行CRUD操作
1. 插入
首先定义接口,然后编写xml的映射文件。
<insert id="insert">
INSERT INTO `demo`.`sale_order` (`order_code`, `status`, `amount`, `create_user`)
VALUES (#{orderCode}, #{status}, #{amount}, #{createUser});
</insert>id对应接口中的方法。取值用#{} 来取值。
2. 查询
使用map作为参数。xml中取值通过map的key来获取值。
接口:
SaleOrder query(Map map);xml:
<select id="query" resultType="io.xuehao.domain.SaleOrder">
SELECT * from sale_order WHERE order_code = #{orderCode}
</select>3. 更新
接口:
/**
* 更新订单
*
* @param saleOrder
* @param code
* @param isDelete
* @return
*/
int update(@Param(value = "saleOrder") SaleOrder saleOrder, @Param(value = "code") String code, @Param(value = "isDelete") Integer isDelete);xml:
<update id="update">
update `demo`.`sale_order` SET `status` = #{saleOrder.status}
where `order_code` = #{code} and `is_delete` = #{isDelete}
</update>多个参数必须要用@param注解起别名。引用时通过 #{别名.}取值