MyBatis一对一关系映射

以用户和身份证为例,一名用户只有一张身份证,一张身份证只属于一名用户;用户表t_user、身份证表t_card。PS:以懒加载方式查询关联的实体并测试,MyBatis版本3.3.1

一.SQL

用户表t_user

create table t_user
(
   id                   bigint(20) not null auto_increment comment 'id',
   user_name            varchar(100) comment '姓名',
   user_age             int comment '年龄',
   card_id              bigint(20) comment '身份证id',
   primary key (id)
);
alter table t_user comment '用户表';
alter table t_user add constraint FK_Reference_2 foreign key (card_id)
      references t_card (id) on delete restrict on update restrict;
身份证表t_card

create table t_card
(
   id                   bigint(20) not null auto_increment comment 'id',
   card_code            varchar(50) comment '卡号',
   primary key (id)
);
alter table t_card comment '身份证表';

二.pojo类

用户User.java

public class User {
	private Long id;
	private String user_name;
	private Integer user_age;
	private Card card;//身份证,一对一
	get、set略
}

身份证Card.java

public class Card {
	private Long id;
	private String card_code;
	get、set略
}

三.MyBatis配置

1.mybatis.xml

<!-- 打开延迟加载的开关 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 将积极加载改为消息加载即按需加载 -->  
<setting name="aggressiveLazyLoading" value="false"/>

2.UserMapper.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.my.mybatis.mapper.UserMapper">	
	
	<resultMap type="com.my.mybatis.pojo.User" id="userMap">
		<!-- 主键 -->
		<id property="id" column="user_id"/>
		<!-- 普通属性 -->
		<result property="user_name" column="user_name"/>
		<result property="user_age" column="user_age"/>
		
		<!-- 与身份证一对一,懒加载方式 -->
		<association property="card" javaType="com.my.mybatis.pojo.Card"
			column="card_id" select="com.my.mybatis.mapper.CardMapper.findById" />
	</resultMap>
	
	<select id="findById" parameterType="long" resultMap="userMap">
		select t.id user_id, t.*
		from t_user t
		where t.id = #{id}
	</select>
</mapper>

3.CardMapper.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.my.mybatis.mapper.CardMapper">	
	
	<resultMap type="com.my.mybatis.pojo.Card" id="cardMap">
		<id property="id" column="card_id"/>
		<result property="card_code" column="card_code"/>
	</resultMap>
	
	<select id="findById" parameterType="long" resultMap="cardMap">
		select t.id card_id, t.*
		from t_card t 
		where t.id = #{id}
	</select>
</mapper>

四.测试

1.UserMapper.java

/**
 * 根据id查询用户
 * @param id 用户id
 * @return 用户信息,未查询到返回null
 * */
public User findById(Long id);

2.CardMapper.java

/**
 * 根据id身份证
 * @param id 身份证id
 * @return 身份证信息,未查询到返回null
 * */
public Card findById(Long id);

3.测试

public void testOneToOne() throws Exception {
	InputStream inputStream = org.apache.ibatis.io.Resources.getResourceAsStream("mybatis.xml");
	SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
	SqlSession session = sqlSessionFactory.openSession();

	UserMapper userMapper = session.getMapper(UserMapper.class);
	User user = userMapper.findById(1L);

	System.out.println(user.getUser_name());
	System.out.println(user.getCard().getCard_code());

	session.commit();
	session.close();
}

五.注

1.设置懒加载方式查询关联的实体,可以在mybatis.xml进行全局配置,如
<!-- 打开延迟加载的开关 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 将积极加载改为消息加载即按需加载 -->  
<setting name="aggressiveLazyLoading" value="false"/>

也可以在assocation、collection等标签中设置fetchType属性

fetchType="lazy" <!-- 懒加载 -->
fetchType="eager" <!-- 立即加载 -->
2.本例测试结果:

首先查询出用户信息,之后在执行user.getCard().getCard_code()时再查询出身份证信息;如果不执行该语句,则不会查询身份证信息

DEBUG - ==>  Preparing: select t.id user_id, t.* from t_user t where t.id = ? 
DEBUG - ==> Parameters: 1(Long)
DEBUG - <==      Total: 1
小明
DEBUG - ==>  Preparing: select t.id card_id, t.* from t_card t where t.id = ? 
DEBUG - ==> Parameters: 1(Long)
DEBUG - <==      Total: 1
201706240001


猜你喜欢

转载自blog.csdn.net/mytt_10566/article/details/78522532