MyBatis 一对一关系

引入架包


配置文件

数据库配置文件



配置MyBatisConfig文件

<?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>
	<!-- 引入连接数据库文件 -->
	<properties resource="db.properties"></properties>
	<!-- 配置别名(即在mapper配置文件用到类时的名字),这里设置类的别名即为类的名称 -->
	<typeAliases>
		<package name="com.mingde.po"/>
	</typeAliases>
	<!-- 配置开发环境 -->
	<environments default="development">
		<environment id="development">
			<!-- 配置事务 -->
			<transactionManager type="JDBC" />		
			<dataSource type="POOLED">
				<property name="driver" value="${driver}"/>
				<property name="url" value="${url}"/>
				<property name="username" value="${username}"/>
				<property name="password" value="${password}"/>
			</dataSource>
		</environment>
	</environments>
	<!-- 引入映射SQL语句文件 -->
	<mappers>
		<!-- 引入指定的SQL语句mapper映射文件 -->
		<mapper resource="com\mingde\mapper\mapper.xml" />
		<!-- 引入整个包所有的SQL语句mapper映射文件 -->
		<!-- <package name="com.mingde.mapper"/> -->
	</mappers>
	
</configuration>

配置MybatisUtils (SqlSessionFactory工厂)

package com.mingde.utils;

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;

public class MyBatisUtils {

	//加载引入资源文件,创建工厂(该工厂内部会解析MyBatis配置文件,根据数据库配置,别名配置和mapper的sql映射文件,去找到该映射文件去执行SQL语句)
	private static SqlSessionFactory getSqlSessionFactory()throws Exception{
		//利用流的方式将MyBatis配置文件引入,然后根据配置文件的内容创建工厂
		InputStream inputStram = Resources.getResourceAsStream("myBatisConfig.xml");
		//将MyBatis配置文件已流方式引,创建SqlSession工厂
		return  new SqlSessionFactoryBuilder().build(inputStram); 
	}
	
	//打开该工厂,进行运行操作;(后面加上参数:‘true’,表示当执行增删改时自动commit提交,这样就不用每次都手动session.commit()去提交)
	//若后面的参数不写,则默认为false,得每次自己手动去session.commit()提交;
	public static SqlSession getSqlSession()throws Exception{
		return getSqlSessionFactory().openSession(true);
	}
	
	
}


Mapper配置文件(见下方各个方法的不同配置)


方法一:继承关系

实体类




Mapper.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="test">
	<!-- 查询所有的员工并同时将其关联的身份ID查询出来 -->
	<!-- 方法一:【一对一关联】  使用自定义类Employee -->
	<select id="seeAll" resultType="Employee">
		select * from employee e,idcard i where e.eid=i.id
	</select>
</mapper>

测试类

	public static void main(String[] args) throws Exception {
		//引用已打开准备好的工厂
		SqlSession session = MyBatisUtils.getSqlSession();
		//调用mapper.xml的方法,调用的方式为:mapper.xml文件里的‘namespace的值+id的值’,如:test.seeAll
		List<Object> selectList = session.selectList("test.seeAll");
		System.out.println(selectList);
		//关闭session
		session.close();
	}

运行结果





方法二:一对一关联关系

实体类:

public class Employee {

	private int eid; 
	private String ename; 
	private String sex; 
	private int age; 
	private String birth;

public class IdCard {
	private int id ;
	private String card;
	private String guoji;
	
	private Employee emp;	//一对一关系

Mapper.xml配置

<!-- 方法二: -->
	<!-- 定义ResultMap -->
	<resultMap type="IdCard" id="IdCards">
		<id column="id" property="id" />
		<result column="card" property="card" />
		<result column="guoji" property="guoji" />
		<!-- 映射关联属性 emp-->
		<association property="emp" javaType="Employee">
			<id column="eid" property="eid" />
			<result column="ename" property="ename" />
			<result column="sex" property="sex" />
			<result column="age" property="age" />
			<result column="birth" property="birth" />
		</association>
	</resultMap>
	<!-- 查询所有 -->
	<select id="seeAll2" resultMap="IdCards">
		select * from idCard c ,Employee e where e.eid=c.id
	</select>
	<!-- 根据id查询 -->
	<select id="findOne2"  resultMap="IdCards">
		select * from idCard c ,Employee e where e.eid=c.id and id=#{value}
	</select>


测试类

	@Test
	public void test2() throws Exception {
		SqlSession session = MyBatisUtils.getSqlSession();
		List<Object> list = session.selectList("test.seeAll2");
		System.out.println(list);
		Object object = session.selectOne("test.findOne2", 1001);
		System.out.println(object);
	}

运行结构:




方法三:一对一关联关系:延迟加载(建议用该方法,较实用)

实体类与方法二的一致(一对一关联关系,一个类中的属性定义另一个类)

Mapper.xml配置

	<!-- 方法三:延迟加载 -->
	<resultMap type="IdCard" id="IdCards3">
		<id column="id" property="id"/>
		<!-- 映射关联属性 emp -->
		<!-- 下面的映射的条件是进入select方法进行该定义的方法查,然后返回对象,查询的参数为column的内容,一旦用该方法的话,默认的是懒加载 fetchType="lazy",该条件可写可不写 -->
		<!-- 实现对用户信息进行延迟加载 select:指定延迟加载需要执行的方法 ,column为列的外建-->
		<association property="emp" javaType="Employee" column="id" select="findID" />
	</resultMap>
	<!-- 上面懒加载的方法 -->
	<select id="findID" resultType="Employee" parameterType="int" >
		select * from Employee where eid=#{value}
	</select>
	
	<!-- 查询所有 -->
	<select id="seeAll3" resultMap="IdCards3">
		select * from idCard 
	</select>
	<!-- 根据id查询 -->
	<select id="findOne3" resultMap="IdCards3" parameterType="int">
		select * from idCard c where id=#{value}
	</select>

测试类

	//方法三测试
	@Test
	public void test3() throws Exception {
		SqlSession session = MyBatisUtils.getSqlSession();
		List<Object> list = session.selectList("test.seeAll3");
		System.out.println(list);
		Object object = session.selectOne("test.findOne3", 1001);
		System.out.println(object);
	}

运行结果:




方法四:注解(注解不用定义Mapper.xml配置文件)

定义接口

package com.mingde.dao;

import java.util.List;

import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;


import com.mingde.po.IdCard;


public interface IdCardDao {
	
	//查询所有
	@Select("select * from idCard ")
	//在注解中定义ResultMap
	@Results(id="IdCards",value={
			@Result(column="id",property="id"),
			@Result(column="card",property="card"),
			@Result(column="guoji",property="guoji"),
			@Result(property="emp",column="id",one=@One(select="com.mingde.dao.EmpDao.findEmp",fetchType=FetchType.LAZY))
			//上面的select写对应的类的方法
	})
	public List<IdCard> SeeAll() throws Exception;
	
	
	//根据id查询单个对象
	@Select("select * from idCard whereid=#{value} ")
	@ResultMap("IdCards") //使用上面定义好的ResultMap方法
	public IdCard findIdCardById(int id)throws Exception;
}

package com.mingde.dao;

import org.apache.ibatis.annotations.Select;

import com.mingde.po.Employee;

public interface EmpDao {

	
	@Select("select * from Employee where eid=#{value}")
	public Employee findEmp(int eid)throws Exception;
	
}

测试类

	//方法四测试
	@Test
	public void test4() throws Exception {
		SqlSession session = MyBatisUtils.getSqlSession();
		IdCardDao mapper = session.getMapper(IdCardDao.class);
		List seeAll = mapper.SeeAll();
		System.out.println(seeAll);
		IdCard obj = mapper.findIdCardById(1001);
		System.out.println(obj);
	}

运行结果




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis中的一对一关系映射是通过使用association元素来实现的。在给定的范例中,Person和IdCard之间的一对一关系被映射成了Java对象的关系。具体来说,Person对象中有一个名为idCard的属性,该属性引用了一个IdCard对象。这个映射是通过在PersonMapper.xml文件中的resultMap元素中定义的association元素来完成的。 在association元素中,我们可以指定关联属性的名称、数据库中对应的列名,以及关联属性的类型。此外,我们还可以使用select属性来指定一个额外的SQL语句,以在查询Person对象时一起查询关联的IdCard对象。在给定的例子中,select属性的值为"com.wx.mapper.IdCardMapper.searchIdCard",表示在查询Person对象时,同时查询关联的IdCard对象。 在Java代码中调用一对一关系映射的方法可以使用MyBatis的SqlSession对象的selectOne或selectList方法。在给定的例子中,使用了selectList方法来查询id为1的Person对象,并将结果存储在名为list3的List对象中。然后使用System.out.println打印出查询结果。 总结来说,MyBatis中的一对一关系映射可以通过在resultMap中使用association元素来设置关联属性,并在查询时使用select属性来同时查询关联对象的信息。通过调用SqlSession的selectOne或selectList方法可以执行一对一关系映射的查询操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Mybatis中的一对一关系映射](https://blog.csdn.net/Altitude_/article/details/101206178)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值