mybatis关联映射一对一
在项目开发中,会存在一对一的关系,比如一个人只有一个身份证,一个身份证只能给一个人使用,这就是一对一关系。一对一关系使用主外键关联。
table.sql,在数据库中创建如下两个表并插入数据
CREATE TABLE T_CARD(
ID INT PRIMARY KEY AUTO_INCREMENT,
CODE VARCHAR(20)
);
INSERT INTO T_CARD(CODE)VALUES('130113198701274657');
CREATE TABLE T_PERSON(
ID INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(20) DEFAULT NULL,
SEX CHAR(20) DEFAULT NULL,
AGE INT(11) DEFAULT NULL,
CARD_ID INT UNIQUE,
FOREIGN KEY(CARD_ID) REFERENCES T_CARD(ID)
);
INSERT INTO T_PERSON(NAME,SEX,AGE,CARD_ID) VALUES('张三','男','23',1);
mybatis-config.xml
<?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">
<!-- XML 配置文件包含对 MyBatis 系统的核心设置 -->
<configuration>
<!-- 指定 MyBatis 所用日志的具体实现 -->
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
<environments default="mysql">
<!-- 环境配置,即连接的数据库。 -->
<environment id="mysql">
<!-- 指定事务管理类型,type="JDBC"指直接简单使用了JDBC的提交和回滚设置 -->
<transactionManager type="JDBC"/>
<!-- dataSource指数据源配置,POOLED是JDBC连接对象的数据源连接池的实现。 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://192.168.47.151:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!-- mappers告诉了MyBatis去哪里找持久化类的映射文件 -->
<mappers>
<mapper resource="mapper/CardMapper.xml"/>
<mapper resource="mapper/PersonMapper.xml"/>
</mappers>
</configuration>
PersonMapper.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">
<!-- namespace指用户自定义的命名空间。 -->
<mapper namespace="com.rookie.bigdata.mapper.PersonMapper">
<parameterMap type="com.rookie.bigdata.domain.Person" id="parameterPersonMap">
<parameter property="id"/>
<parameter property="name"/>
<parameter property="sex"/>
<parameter property="age"/>
</parameterMap>
<insert id="insertPerson" parameterMap="parameterPersonMap">
<selectKey keyProperty="id" resultType="int" order="AFTER">
SELECT LAST_INSERT_ID() AS ID
</selectKey>
INSERT INTO t_person(name,sex,age,card_id)
VALUES(#{name},#{sex},#{age},#{card.id}) <!--记得不要有逗号-->
</insert>
<!-- 根据id查询Person,返回resultMap -->
<select id="selectPersonById" parameterType="int"
resultMap="personMapper">
SELECT * from t_person where id = #{id}
</select>
<!-- 映射Peson对象的resultMap -->
<resultMap type="com.rookie.bigdata.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 -->
<association property="card" column="card_id"
select="com.rookie.bigdata.mapper.CardMapper.selectCardById"
javaType="com.rookie.bigdata.domain.Card"/>
</resultMap>
</mapper>
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">
<!-- namespace指用户自定义的命名空间。 -->
<mapper namespace="com.rookie.bigdata.mapper.CardMapper">
<!-- 根据id查询Card,返回Card对象 -->
<select id="selectCardById" parameterType="int" resultType="com.rookie.bigdata.domain.Card">
SELECT * from t_card where id = #{id}
</select>
<parameterMap type="com.rookie.bigdata.domain.Card" id="cardMap">
<parameter property="id"/>
<parameter property="code"/>
</parameterMap>
<insert id="insertCard" parameterMap="cardMap">
<selectKey keyProperty="id" resultType="int" order="AFTER">
SELECT LAST_INSERT_ID() AS ID
</selectKey>
INSERT INTO T_CARD(id,code)
VALUES(?,?)
</insert>
</mapper>
Card.java
public class Card implements Serializable {
private Integer id; // 主键id
private String code; // 身份证编号
}
Person.java
public class Person implements Serializable {
private Integer id; // 主键id
private String name; // 姓名
private String sex; // 性别
private Integer age; // 年龄
// 人和身份证是一对一的关系,即一个人只有一个身份证
private Card card;
CardMapper.java
public interface CardMapper {
void insertCard(Card card);
}
PersonMapper.java
public interface PersonMapper {
/**
* 根据id查询Person
*/
Person selectPersonById(Integer id);
/**
* 插入数据
* @param person
*/
void insertPerson(Person person);
}
SqlSessionFactoryUtil.java
package com.rookie.bigdata.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
public class SqlSessionFactoryUtil {
private static SqlSessionFactory sqlSessionFactory = null;
// 初始化创建SqlSessionFactory对象
static{
try {
// 读取mybatis-config.xml文件
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
// 获取SqlSession对象的静态方法
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
// 获取SqlSessionFactory的静态方法
public static SqlSessionFactory getSqlSessionFactory() {
return sqlSessionFactory;
}
}
测试代码进行增查操作
package com.rookie.bigdata.test;
import com.rookie.bigdata.domain.Card;
import com.rookie.bigdata.domain.Person;
import com.rookie.bigdata.mapper.CardMapper;
import com.rookie.bigdata.mapper.PersonMapper;
import com.rookie.bigdata.utils.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.transaction.Transaction;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.junit.Test;
public class OneToOneTest {
@Test
public void test() throws Exception {
// 创建Session实例
SqlSession session = SqlSessionFactoryUtil.getSqlSession();
// 获得mapper接口的代理对象
PersonMapper pm = session.getMapper(PersonMapper.class);
// 直接调用接口的方法,查询id为1的Peson数据
Person p = pm.selectPersonById(1);
// 打印Peson对象
System.out.println(p);
// 打印Person对象关联的Card对象
System.out.println(p.getCard());
// 提交事务
session.commit();
// 关闭Session
session.close();
}
@Test
public void test1() throws Exception {
SqlSession sqlSession = SqlSessionFactoryUtil.getSqlSession();
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Transaction tx = transactionFactory.newTransaction(sqlSession
.getConnection());
Card card = new Card();
card.setCode("130442154542048521");
Person person = new Person();
person.setName("lisi");
person.setSex("男");
person.setAge(30);
person.setCard(card);
PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
CardMapper cardMapper = sqlSession.getMapper(CardMapper.class);
cardMapper.insertCard(card);
personMapper.insertPerson(person);
System.out.println(card.getId());
tx.commit();
}
}
进行测试完美解决