1对1的关系-人和身份证的关系
1、数据库:
person 表:
card:
2、javabean:
person:
public class Person implements Serializable {
private Integer id;
private String name;
private String sex;
private Integer age;
private Card card;
card:
public class Card implements Serializable {
private Integer id;
private String code;
3、mapper.java文件
person:
public interface StudentMapper {
// 根据id查询学生信息
Student selectStudentById(Integer id);
}
card:
public interface CardMapper {
Card selectCardById(Integer id);
}
4、xml文件:
person:
<mapper namespace="org.fkit.mapper.PersonMapper">
<select id="selectPersonById" parameterType="int" resultMap="personMapper">
select * from tb_person where id=#{id};
</select>
<resultMap type="org.fkit.domain.Person" id="personMapper">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="sex" column="sex"/>
<result property="age" column="age"/>
<association property="card" column="card_id" select="org.fkit.mapper.CardMapper.selectCardById" javaType="org.fkit.domain.Card">
</association>
</resultMap>
</mapper>
card:
<mapper namespace="org.fkit.mapper.CardMapper">
<select id="selectCardById" parameterType="int" resultType="org.fkit.domain.Card">
select * from tb_card where id=#{id};
</select>
</mapper>
测试类:
public class OneToOneTest {
public static void main(String[] args) throws Exception {
// 读取mybatis-config.xml文件
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
// 初始化mybatis,创建SqlSessionFactory类的实例
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream);
// 创建Session实例
SqlSession session = sqlSessionFactory.openSession();
//获得mapper接口的带来对象
PersonMapper pm=session.getMapper(PersonMapper.class);
Person p=pm.selectPersonById(1);
// 插入数据
// session.insert("org.fkit.mapper.UserMapper.save", user);
System.out.println(p);
System.out.println(p.getCard());
// 提交事务
session.commit();
// 关闭Session
session.close();
}
}
打印结果:
Person [id=1, name=windy, sex=男, age=25, card=Card [id=1, code=430682199012053635]]
Card [id=1, code=430682199012053635]