1.Mybatis多表查询
1.1 一对一查询
1.1.1 一对一查询的模型
用户表和订单表的关系为,一个用户有多个订单,一个订单只从属于一个用户
一对一查询的需求:查询一个订单,与此同时查询出该订单所属的用户
1.1.2一对一查询的语句
对应的sql语句:select * from orders o,user u where o.uid=u.id;
1.1.3 创建Order和User实体
public class Order {
private int id;
private Date ordertime;
private double total;
//代表当前订单从属于哪一个客户
private User user;
}
public class User {
private int id;
private String username;
private String password;
private Date birthday;
}
1.1.4 创建OrderMapper接口
public interface OrderMapper {
List<Order> findAll();
}
1.1.5 配置OrderMapper.xml
<mapper namespace="com.itheima.mapper.OrderMapper">
<resultMap id="orderMap" type="com.itheima.domain.Order">
<result column="uid" property="user.id"></result>
<result column="username" property="user.username"></result>
<result column="password" property="user.password"></result>
<result column="birthday" property="user.birthday"></result>
</resultMap>
<select id="findAll" resultMap="orderMap">
select * from orders o,user u where o.uid=u.id
</select>
</mapper>
其中还可以配置如下:
<resultMap id="orderMap" type="com.itheima.domain.Order">
<result property="id" column="id"></result>
<result property="ordertime" column="ordertime"></result>
<result property="total" column="total"></result>
<association property="user" javaType="com.itheima.domain.User">
<result column="uid" property="id"></result>
<result column="username" property="username"></result>
<result column="password" property="password"></result>
<result column="birthday" property="birthday"></result>
</association>
</resultMap>
1.2 一对多查询
1.2.1 一对多查询的模型
用户表和订单表的关系为,一个用户有多个订单,一个订单只从属于一个用户
一对多查询的需求:查询一个用户,与此同时查询出该用户具有的订单
1.2.2 一对多查询的语句
对应的sql语句:select *,o.id oid from user u left join orders o on u.id=o.uid;
1.2.3写User 实体
package com.blb.domain;
import java.util.Date;
import java.util.List;
public class User {
private int id;
private String username;
private String password;
private List<Order> orderList;
private Date birthday;
public List<Order> getOrderList() {
return orderList;
}
public void setOrderList(List<Order> orderList) {
this.orderList = orderList;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", orderList=" + orderList +
", birthday=" + birthday +
'}';
}
}
xml配置
<mapper namespace="com.blb.dao.UserMapper">
<resultMap id="userMap" type="com.blb.domain.User">
<id property="id" column="uid"></id>
<result column="username" property="username"></result>
<result column="password" property="password"></result>
<result column="birthday" property="birthday"></result>
<collection property="orderList" ofType="com.blb.domain.Order">
<id column="oid" property="id"></id>
<result column="orderTime" property="orderTime"></result>
<result column="total" property="total"></result>
</collection>
</resultMap>
<sql id="selectUser"> select * from user</sql>
<!--查询操作 -->
<select id="findall" resultMap="userMap" >
SELECT *,o.id oid FROM USER u,orders o WHERE u.id=o.uid
</select>
</mapper>
1.3多对多查询
对多多查询一般有个中间表进行关联,有多个集合
1.4总结
一对一查询:使用< resultMap > 做配置
一对多查询:使用< resultMap > + < collection > 做配置
多对多查询:使用< resultMap > + < collection > 做配置
2.Mybatis的注解开发
2.1 MyBatis的常用注解
这几年来注解开发越来越流行,Mybatis也可以使用注解开发方式,这样我们就可以减少编写Mapper
映射文件了。我们先围绕一些基本的CRUD来学习,再学习复杂映射多表操作。
@Insert:实现新增
@Update:实现更新
@Delete:实现删除
@Select:实现查询
@Result:实现结果集封装
@Results:可以与@Result 一起使用,封装多个结果集
@One:实现一对一结果集封装
@Many:实现一对多结果集封装
UserMapper.java
public interface UserMapper {
public List<User> findall();
@Insert("insert into user values (#{id},#{username},#{password},#{birthday})")
public void save(User user);
public List<User> findByCondition (User user);
public List<User> findByIdList(List<Integer> list);
@Select("select * from user")
public List<User> find();
@Update(" update user set username=#{username}, password=#{password} where id=#{id}")
public void update(User user);
@Delete("delete from user where id=#{id}")
public void delete(int i);
}
测试类
public class MybatisTest {
private UserMapper mapper;
@Before
public void before() throws IOException {
InputStream resource = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resource);
SqlSession sqlSession = build.openSession(true);
mapper = sqlSession.getMapper(UserMapper.class);
}
/**
* 查询
*/
@Test
public void text1()
{
List<User> findall = mapper.find();
for(User user:findall)
{
System.out.println(user);
}
}
/**
* 添加
*/
@Test
public void text2()
{
User user=new User();
user.setUsername("王五");
user.setPassword("123456");
user.setBirthday(new Date());
mapper.save(user);
}
/**
* 修改
*/
@Test
public void text3()
{
User user=new User();
user.setUsername("王五");
user.setPassword("123456");
user.setId(7);
user.setBirthday(new Date());
mapper.save(user);
}
/**
* 删除
*/
@Test
public void text4()
{
mapper.delete(11);
}
}
2.3 MyBatis的注解实现复杂映射开发
实现复杂关系映射之前我们可以在映射文件中通过配置来实现,使用注解开发后,我们可以使用@Results注解,@Result注解,@One注解,@Many注解组合完成复杂关系的配置
2.4一对一查询
2.4.1 一对一查询的模型
用户表和订单表的关系为,一个用户有多个订单,一个订单只从属于一个用户
一对一查询的需求:查询一个订单,与此同时查询出该订单所属的用户
2.4.2 一对一查询的语句
对应的sql语句:
select * from orders;
select * from user where id=查询出订单的uid;
查询的结果如下:
2.4.3 创建Order和User实体
public class Order {
private int id;
private Date ordertime;
private double total;
//代表当前订单从属于哪一个客户
private User user;
}
public class User {
private int id;
private String username;
private String password;
private Date birthday;
}
2.4.4 创建OrderMapper接口
public interface OrderMapper {
List<Order> findAll();
}
2.4.5 使用注解配置Mapper
public interface OrderMapper {
@Select("select * from orders")
@Results({
@Result(id=true,property = "id",column = "id"),
@Result(property = "ordertime",column = "ordertime"),
@Result(property = "total",column = "total"),
@Result(property = "user",column = "uid",
javaType = User.class,
one = @One(select = "com.itheima.mapper.UserMapper.findById"))
})
List<Order> findAll();
}
public interface UserMapper {
@Select("select * from user where id=#{id}")
User findById(int id);
}
2.4.6 测试结果
@Test
public void testSelectOrderAndUser() {
List<Order> all = orderMapper.findAll();
for(Order order : all){
System.out.println(order);
}
}
2.5 一对多查询
2.5.1 一对多查询的模型
用户表和订单表的关系为,一个用户有多个订单,一个订单只从属于一个用户
一对多查询的需求:查询一个用户,与此同时查询出该用户具有的订单
2.5.2 一对多查询的语句
对应的sql语句:
select * from user;
select * from orders where uid=查询出用户的id;
查询的结果如下:
2.5.3 修改User实体
public class Order {
private int id;
private Date ordertime;
private double total;
}
public class User {
private int id;
private String username;
private String password;
private Date birthday;
//代表当前用户具备哪些订单
private List<Order> orderList;
}
2.5.4 创建UserMapper接口
List<User> findAllUserAndOrder();
2.5.5 使用注解配置Mapper
public interface UserMapper {
@Select("select * from user")
@Results({
@Result(id = true,property = "id",column = "id"),
@Result(property = "username",column = "username"),
@Result(property = "password",column = "password"),
@Result(property = "birthday",column = "birthday"),
@Result(property = "orderList",column = "id",
javaType = List.class,
many = @Many(select = "com.itheima.mapper.OrderMapper.findByUid"))
})
List<User> findAllUserAndOrder();
}
public interface OrderMapper {
@Select("select * from orders where uid=#{uid}")
List<Order> findByUid(int uid);
}
2.5.6 测试结果
@Test
public void text3() throws IOException {
InputStream resource = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resource);
SqlSession sqlSession = build.openSession();
UserMapper usermapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.findUserAndOrder();
List<User> all = userMapper.findAllUserAndOrder();
for(User user : all){
System.out.println(user);
}
}
2.6 多对多查询
2.6.1 多对多查询的模型
用户表和角色表的关系为,一个用户有多个角色,一个角色被多个用户使用
多对多查询的需求:查询用户同时查询出该用户的所有角色
2.6.2 多对多查询的语句
对应的sql语句:
select * from user;
select * from role r,user_role ur where r.id=ur.role_id and ur.user_id=用户的id
查询的结果如下:
2.6.3 创建Role实体,修改User实体
public class User {
private int id;
private String username;
private String password;
private Date birthday;
//代表当前用户具备哪些订单
private List<Order> orderList;
//代表当前用户具备哪些角色
private List<Role> roleList;
}
public class Role {
private int id;
private String rolename;
}
2.6.4 添加UserMapper接口方法
List<User> findAllUserAndRole();
2.6.5 使用注解配置Mapper
public interface UserMapper {
@Select("select * from user")
@Results({
@Result(id = true,property = "id",column = "id"),
@Result(property = "username",column = "username"),
@Result(property = "password",column = "password"),
@Result(property = "birthday",column = "birthday"),
@Result(property = "roleList",column = "id",
javaType = List.class,
many = @Many(select = "com.itheima.mapper.RoleMapper.findByUid"))
})
List<User> findAllUserAndRole();}
public interface RoleMapper {
@Select("select * from role r,user_role ur where r.id=ur.role_id and ur.user_id=#{uid}")
List<Role> findByUid(int uid);
}
2.6.6 测试结果
@Test
public void text3() throws IOException {
InputStream resource = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resource);
SqlSession sqlSession = build.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> all = mapper.findAllUserAndRole();
for(User user : all){
System.out.println(user);
}
}