MyBatis 一对一关系

来源:互联网 发布:全面战争系列优化渣 编辑:程序博客网 时间:2024/05/16 02:02

引入架包


配置文件

数据库配置文件



配置MyBatisConfig文件

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configurationPUBLIC "-//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 mapperPUBLIC "-//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.seeAllList<Object> selectList = session.selectList("test.seeAll");System.out.println(selectList);//关闭sessionsession.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>


测试类

@Testpublic 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>

测试类

//方法三测试@Testpublic 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;}

测试类

//方法四测试@Testpublic 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);}

运行结果




原创粉丝点击