Mybatis 一对一

Mybatis

  1. OneToOne 
以人和身份证为例子,一人只能对应一张身份证,一张身份证一人使用,这就是一对一的关系.
  • 首先,在数据库中创建两个表,写入测试数据:
tb_card:

tb_person:(card_id foreign key)

  • 创建对应的bean:(get and set)
public class Card implements Serializable {
private int id;
private String code;
}

public class Person implements Serializable {
private int id;
private String name;
private String sex;
private int age;
private Card card;
}
  • 创建mapper接口,这里我只创建一个测试用的mapper接口
MybatisMapper:
public interface MybatisMapper {
Card selectCardById(int id);
Person selectPersonById(int id); 
}
  • 配置对应的mapper xml:
Card.xml:

Person.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.cen.mapper.MybatisMapper">
      <resultMap type="Person" id="personMappermap">
            <id property="id" column="id"></id>
            <result property="name" column="name"/>
            <result property="sex" column="sex"/>
            <result property="age" column="age"/>
            <association property="card" column="card_id" select="com.cen.mapper.MybatisMapper.selectCardById" javaType="Card"></association>
        </resultMap>
        <select id="selectPersonById" parameterType="int" resultMap="personMappermap">
            select * from tb_person where id = #{id}
        </select>
     </mapper>

编写测试:
public class MybatisTest {
private SqlSessionFactory sqlsessionF;
private SqlSession sqlSession;
private MybatisMapper mapper;
@Before
public void before() {
@SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"classpath:applicationContext.xml"
,"classpath:mybatis-config.xml","classpath:springMVC.xml"});//加载配置文件
sqlsessionF = (SqlSessionFactory)context.getBean("sqlSession");
    sqlSession = sqlsessionF.openSession();
    mapper = sqlSession.getMapper(MybatisMapper.class);
}
@Test
public void oneToOne() throws Exception{
Person p = mapper.selectPersonById(1);
System.out.println(p.getName()+p.getAge()+p.getSex());
System.out.println(p.getCard().getCode());
sqlSession.commit();
sqlSession.close();
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值