---------------------siwuxie095
MyBatis 一对一查询
以订单和用户为例,即 相对订单来说,一个订单只能属于一个用户
PS:实际上,订单和用户的关系是一对多,这里采用了相对的概念,
从单向看,就是一对一
需求如下:
根据订单号查询订单,并查询出下单人(用户)的信息
具体实现:
先创建数据库 mybatis_db, 再创建表 t_order 和 t_user,并插入
若干数据,其中:各自的主键分别是 order_id 和 user_id,且为自
动增长,另外:t_order 中的 user_id 为外键
创建实体类
Order.java:
package com.siwuxie095.entity;
public class Order {
private Integer orderId; private String orderNo; private Integer userId;
public Integer getOrderId() { return orderId; } public void setOrderId(Integer orderId) { this.orderId = orderId; }
public String getOrderNo() { return orderNo; }
public void setOrderNo(String orderNo) { this.orderNo = orderNo; }
public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; }
@Override public String toString() { return "Order [orderId=" + orderId + ", orderNo=" + orderNo + ", userId=" + userId + "]"; }
} |
User.java:
package com.siwuxie095.entity;
public class User { private Integer userId; private String userName; private String userSex;
public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; }
public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; }
public String getUserSex() { return userSex; } public void setUserSex(String userSex) { this.userSex = userSex; }
@Override public String toString() { return "User [userId=" + userId + ", userName=" + userName + ", userSex=" + userSex + "]"; }
} |
接下来 …
(一)第一种实现:创建一个类扩展 Order 类(继承,不推荐)
1、创建实体类,继承 Order 类
OrderAndUser.java:
package com.siwuxie095.entity;
public class OrderAndUser extends Order {
private String userName; private String userSex;
public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; }
public String getUserSex() { return userSex; } public void setUserSex(String userSex) { this.userSex = userSex; }
@Override public String toString() { return "OrderAndUser [userName=" + userName + ", userSex=" + userSex + ", toString()=" + super.toString() + "]"; }
} |
2、创建映射器接口
OrderMapper.java:
package com.siwuxie095.mapper;
import com.siwuxie095.entity.OrderAndUser;
public interface OrderMapper {
/** * 根据订单号查询订单和下单人(用户)信息 * @param orderNo * @return */ OrderAndUser getOrderAndUser(String orderNo); } |
3、创建 MyBatis 映射配置文件
OrderMapper.xml:
<?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">
<mapper namespace="com.siwuxie095.mapper.OrderMapper">
<select id="getOrderAndUser" resultType="OrderAndUser"> <!-- 具体的 SQL 语句,其中:通过 #{} 占位符 获取传入的参数
注意:因为这里只有一个参数,所以大括号中可任意,建议 和实体类属性对应(不是和数据库表字段对应,这里相同只 是巧合) --> select o.*, u.user_name, u.user_sex from t_order o left join t_user u on o.user_id=u.user_id where order_no=#{orderNo} </select>
</mapper> |
4、创建 MyBatis 核心配置文件
mybatis-config.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 开启自动驼峰命名规则映射 --> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings>
<!-- 配置类型别名 --> <typeAliases> <typeAlias type="com.siwuxie095.entity.OrderAndUser" alias="OrderAndUser"/> </typeAliases>
<!-- 配置环境(environments):包括事务管理和连接池 --> <environments default="development"> <environment id="development">
<!-- 配置事务管理器 --> <transactionManager type="JDBC" />
<!-- 配置数据源:这里使用 MyBatis 内置连接池 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <!-- jdbc:mysql://localhost:3306/mybatis_db 可省略为 jdbc:mysql:///mybatis_db --> <property name="url" value="jdbc:mysql:///mybatis_db" /> <property name="username" value="root" /> <property name="password" value="8888" /> </dataSource>
</environment> </environments>
<!-- 引入映射配置文件 --> <mappers> <mapper resource="com/siwuxie095/mapper/OrderMapper.xml"/> </mappers>
</configuration> |
5、创建单元测试类
MyBatisOneToOneTest.java:
package com.siwuxie095.test;
import java.io.IOException; import java.io.InputStream;
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;
import com.siwuxie095.entity.OrderAndUser; import com.siwuxie095.mapper.OrderMapper;
public class MyBatisOneToOneTest {
/** * 手动加上 @Test 以进行单元测试(将自动导入 JUnit 4 的 jar 包) * * 选中方法名,右键->Run As->JUint Test */ @Test public void testGetOrderAndUser() throws IOException{
String resource="mybatis-config.xml"; InputStream inputStream=Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession=sqlSessionFactory.openSession();
OrderMapper orderMapper=sqlSession.getMapper(OrderMapper.class); OrderAndUser orderAndUser = orderMapper.getOrderAndUser("D5221"); System.out.println(orderAndUser);
sqlSession.close(); } } |
工程结构目录一览:
(二)第二种实现:在 Order 类中添加 User 对象(面向对象,推荐)
1、修改实体类
Order.java:
package com.siwuxie095.entity;
public class Order {
private Integer orderId; private String orderNo; private Integer userId;
// 在 Order 类中添加一个 User 对象,表示关系为一对一 private User user;
public User getUser() { return user; } public void setUser(User user) { this.user = user; }
public Integer getOrderId() { return orderId; } public void setOrderId(Integer orderId) { this.orderId = orderId; }
public String getOrderNo() { return orderNo; }
public void setOrderNo(String orderNo) { this.orderNo = orderNo; }
public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; }
@Override public String toString() { return "Order [orderId=" + orderId + ", orderNo=" + orderNo + ", userId=" + userId + ", user=" + user + "]"; }
} |
2、创建映射器接口
OrderMapper.java:
package com.siwuxie095.mapper;
import com.siwuxie095.entity.Order;
public interface OrderMapper {
/** * 根据订单号查询订单和下单人(用户)信息 * @param orderNo * @return */ Order getOrderAndUser(String orderNo); } |
3、创建 MyBatis 映射配置文件
OrderMapper.xml:
<?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">
<mapper namespace="com.siwuxie095.mapper.OrderMapper">
<!-- 此时,resultType 自动映射已经不能满足,所以需要使用 resultMap 手动映射 --> <select id="getOrderAndUser" resultMap="orderAndUserResultMap"> <!-- 具体的 SQL 语句,其中:通过 #{} 占位符 获取传入的参数
注意:因为这里只有一个参数,所以大括号中可任意,建议 和实体类属性对应(不是和数据库表字段对应,这里相同只 是巧合) --> select o.*, u.user_name, u.user_sex from t_order o left join t_user u on o.user_id=u.user_id where order_no=#{orderNo} </select>
<!-- 注意:如果 resultMap 标签中没有嵌套映射,其 autoMapping 属性默认为 true, 反之则为 false。即 如果 resultMap 标签中没有 association、collection 等 标签,其 autoMapping 属性默认为 true,反之则为 false
所以这里要将 autoMapping 属性手动改为 true,当然,把所有属性一一写出来直 接映射也可以,这样就不用改 autoMapping 属性了 --> <resultMap type="Order" id="orderAndUserResultMap" autoMapping="true"> <id column="order_id" property="orderId"/> <!-- association 标签用于指定 Order 类中的 User 对象 --> <association property="user" javaType="User" autoMapping="true"> <id column="user_id" property="userId"/> </association> </resultMap>
</mapper> |
4、创建 MyBatis 核心配置文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 开启自动驼峰命名规则映射 --> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings>
<!-- 配置类型别名 --> <typeAliases> <typeAlias type="com.siwuxie095.entity.Order" alias="Order"/> <typeAlias type="com.siwuxie095.entity.User" alias="User"/> </typeAliases>
<!-- 配置环境(environments):包括事务管理和连接池 --> <environments default="development"> <environment id="development">
<!-- 配置事务管理器 --> <transactionManager type="JDBC" />
<!-- 配置数据源:这里使用 MyBatis 内置连接池 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <!-- jdbc:mysql://localhost:3306/mybatis_db 可省略为 jdbc:mysql:///mybatis_db --> <property name="url" value="jdbc:mysql:///mybatis_db" /> <property name="username" value="root" /> <property name="password" value="8888" /> </dataSource>
</environment> </environments>
<!-- 引入映射配置文件 --> <mappers> <mapper resource="com/siwuxie095/mapper/OrderMapper.xml"/> </mappers>
</configuration> |
5、创建单元测试类
MyBatisOneToOneTest.java:
package com.siwuxie095.test;
import java.io.IOException; import java.io.InputStream;
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;
import com.siwuxie095.entity.Order; import com.siwuxie095.mapper.OrderMapper;
public class MyBatisOneToOneTest {
/** * 手动加上 @Test 以进行单元测试(将自动导入 JUnit 4 的 jar 包) * * 选中方法名,右键->Run As->JUint Test */ @Test public void testGetOrderAndUser() throws IOException{
String resource="mybatis-config.xml"; InputStream inputStream=Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession=sqlSessionFactory.openSession();
OrderMapper orderMapper=sqlSession.getMapper(OrderMapper.class); Order order = orderMapper.getOrderAndUser("D5221"); System.out.println(order);
sqlSession.close(); } } |
工程结构目录一览:
【made by siwuxie095】