1、MyBatis是什么?
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
2、快速入门
- 引入MyBatis坐标
mysql
mysql-connector-java
8.0.21
org.mybatis
mybatis
3.5.4
- 创建数据表
- 创建实体类
- 编写映射配置文件
- 编写核心配置文件
- 测试
public class MyBatisTest {
@Test
public void test1() throws IOException {
//获取核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
//获取session工厂对象
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
//获取session会话对象
SqlSession sqlSession = build.openSession();
//执行操作
List userList = sqlSession.selectList("userMapper.getAll");
System.out.println(userList);
//释放资源
sqlSession.close();
}
}
2、映射配置文件概述
3、简单CRUD
public class MyBatisTest {
@Test
public void test1() throws IOException {
User user = new User();
user.setId(10002);
user.setUsername("dog");
user.setPassword("123");
//获取核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
//获取session工厂对象
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
//获取session会话对象
SqlSession sqlSession = build.openSession();
//执行查询操作
//List userList = sqlSession.selectList("userMapper.getAll");
//执行新增操作
int insert = sqlSession.insert("userMapper.addUser", user);
//执行更新操作
//int update = sqlSession.update("userMapper.updUser", user);
//执行删除操作
//int delete = sqlSession.delete("userMapper.delUser", user);
//当执行增、删、改操作时,MyBatis默认不自动提交事务
sqlSession.commit();
//释放资源
sqlSession.close();
}
}
insert into ts_user values (#{id}, #{username}, #{password})
update ts_user set username = #{username} where id = #{id}
delete from ts_user where id = #{id}
4、dao整合(代理方式)
- dao层mapper接口
public interface UserMapper {
List getList();
User getUser(int id);
}
- 映射配置
- 调用测试
public class MyBatisTest {
@Test
public void myTest() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取接口代理对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List list = mapper.getList();
System.out.println(list);
User user = mapper.getUser(10000);
System.out.println(user);
}
}
5、动态sql
- if、where、set
UPDATE `ts_user`
username = #{username}
password = #{password}
WHERE id = #{id}
- foreach
1、collection:包括list,array,map三个值,分别代表传入参数是集合或数组类型
2、item:元素别名
3、separator:间隔符
4、open:前缀
5、close:后缀
6、index:当前下标
6、sql片段
- 片段抽取
SELECT id,username,password FROM `ts_user`
- 片段引入
7、sql场景举例
- 一对一查询,查询订单信息同时包括用户信息
Order实体类中包含用户信息对象属性
public class Order {
private int id;
private int goodsId;
private String goodsName;
private double totalAmount;
private User user;
Order表映射配置文件
- 一对多查询,查询用户信息及用户所有订单信息
User实体类中增加Order类型的List集合属性,并给与set、get方法
public class User {
private int id;
private String username;
private String password;
private List orderList;
public List getOrderList() {
return orderList;
}
public void setOrderList(List orderList) {
this.orderList = orderList;
}
在UserMapper.xml中配置查询数据映射关系
返回结果
User{id=10000, username='judy', password='null',
orderList=[
Order{id=10001, goodsId=1001, goodsName='镭射鼠标', totalAmount=129.0, user=null},
Order{id=10003, goodsId=1022, goodsName='联想笔记本', totalAmount=5399.0, user=null}
]}
注意:collection或者association标签里面都需要写property属性,该标签属性代表了实体类中属性的名称,指定实体类属性类型时,对应的实体类属性类型如果是集合,就用ofType,并且ofType的值是集合中存储元素的类型;不是集合就用javaType,并且javaType的值是实体类中属性的类型
8、使用注解
- 配置包内注解扫描
- 普通CRUD
public interface UserMapper {
@Select("select * from ts_user")
List getList();
@Select("select * from ts_user where id = #{id}")
User getUser(int id);
- 一对一查询
public interface OrderMapper {
@Select("select * from ts_order where id = #{id}")
@Results({
@Result(property = "id", column = "id", id = true),
@Result(property = "goodsId", column = "goods_id"),
@Result(property = "goodsName", column = "goods_name"),
@Result(property = "totalAmount", column = "total_amount"),
@Result(
property = "user",
column = "user_id",
javaType = User.class,
one = @One(select = "com.study.mybatis.dao.UserMapper.getUser")
)
})
Order getOrderInfo(int id);
}
- 一对多查询
@Select("select * from ts_user where id = #{id}")
@Results({
@Result(property = "id", column = "id", id = true),
@Result(property = "username", column = "username"),
@Result(
property = "orderList",
column = "id",
javaType = List.class,
many = @Many(select = "com.study.mybatis.dao.OrderMapper.getOrderListByUserId")
)
})
User getOrderList(int id);
@Select("select * from ts_order where user_id = #{id}")
List getOrderListByUserId(int id);