//一对一关联查询,以订单为中心 关联用户查询
image.png image.png
image.png
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 写Sql语句 -->
<mapper namespace="com.ryan.mybatis.pojo.OrderDao">
<!-- public List<Order> selectOrder();
-->
<resultMap type="Order" id="order">
<id column="user_id" property="userId"/>
<result column="id" property="id"/>
<result column="number" property="number"/>
<association property="user" javaType="User">
<id column="user_id" property="id"/>
<result column="username" property="username"/>
</association>
</resultMap>
<select id="selectOrder" resultMap="order">
SELECT
o.id,
o.user_id,
o.number,
o.createtime,
u.id,
u.username
FROM
`order` o
LEFT JOIN `USER` u ON o.user_id = u.id
</select>
</mapper>
package com.ryan.mybatis.pojo;
import java.util.List;
public interface OrderDao {
//一对一关联查询,以订单为中心 关联用户查询
public List<Order> selectOrder();
}
package com.ryan.mybatis.pojo;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
public class Test1 {
@Test
public void demo1() throws IOException {
String resource="sqlMapConfig.xml";
InputStream in = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(in);
SqlSession sqlSession = sqlSessionFactory.openSession();
OrderDao user2=sqlSession.getMapper(OrderDao.class);
List<Order> selectList = user2.selectOrder();
for (Order user4 : selectList) {
System.out.println(user4);
}
}
}
package com.ryan.mybatis.pojo;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer id;
private String username;// 用户姓名
private String sex;// 性别
private Date birthday;// 生日
private String address;// 地址
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", sex=" + sex
+ ", birthday=" + birthday + ", address=" + address + "]";
}
}
网友评论