Mybatis一对一关系映射

一对一最典型的数据库关系就是用户和身份证了。

书中就是以这个例子来作为实现的。


数据库建库:



CREATE TABLE tb_card (
  id INT PRIMARY KEY AUTO_INCREMENT,
  CODE VARCHAR(18)
);
INSERT INTO tb_card (CODE) VALUES('62134219781203198');
INSERT INTO tb_card (CODE) VALUES('62134219741203198');
INSERT INTO tb_card (CODE) VALUES('62134219981203198');

CREATE TABLE tb_person (
  id INT PRIMARY KEY AUTO_INCREMENT,
  NAME VARCHAR(18),
  SEX VARCHAR(18),
  AGE INT,
  CARD_ID INT UNIQUE,
  FOREIGN KEY (CARD_ID) REFERENCES tb_card (id)
);
INSERT INTO tb_person (NAME, SEX, AGE, CARD_ID) VALUES ('jack', 'M', 23, 1);
INSERT INTO tb_person (NAME, SEX, AGE, CARD_ID) VALUES ('tom', 'F', 21, 2);
INSERT INTO tb_person (NAME, SEX, AGE, CARD_ID) VALUES ('john', 'M', 25, 3);

mybatis-config.xml


<?xm	l 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>
	<settings>
		<setting name="logImpl" value="LOG4J" />
	</settings>
	<typeAliases>
		<typeAlias alias="user" type="org.fkit.domain.User"/>
	</typeAliases>
	<environments default="dev">
		<environment id="dev">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver" />
				<property name="url" value="jdbc:mysql://IP/DB" />
				<property name="username" value="xxx" />
				<property name="password" value="xxx" />
			</dataSource>
		</environment>
	
	</environments>
	
	<mappers>
		<mapper resource="org/fkit/mapper/UserMapper.xml" />
		<mapper resource="org/fkit/mapper/PersonMapper.xml" />
		<mapper resource="org/fkit/mapper/CardMapper.xml" />
	</mappers>
</configuration>

log4j.properties


log4j.rootLogger=ERROR, stdout

log4j.logger.org.fkit.mapper.UserMapper=DEBUG

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

Card.java


package org.fkit.domain;

public class Card {
	private Integer id;
	private String code;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	@Override
	public String toString() {
		return "Card [id=" + id + ", code=" + code + "]";
	}
	
	

}

Person.java


package org.fkit.domain;

public class Person {
	private Integer id;
	private String name;
	private String sex;
	private Integer age;
	private Card card;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public Card getCard() {
		return card;
	}
	public void setCard(Card card) {
		this.card = card;
	}
	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", sex=" + sex + ", age=" + age + ", card=" + card + "]";
	}
	
	

}


FKSqlSessionFactory.java


package org.fkit.factory;

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 FKSqlSessionFactory {
	private static SqlSessionFactory sqlSessionFactory = null;
	
	static {
		try {
			InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static SqlSession getSqlSession() {
		return sqlSessionFactory.openSession();
	}
	public static SqlSessionFactory getSqlSessionFactory() {
		return sqlSessionFactory;
	}

}

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">
<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>

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">
<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" />
	</resultMap>
</mapper>

PersonMapper.java


package org.fkit.mapper;

import org.fkit.domain.Person;

public interface PersonMapper {
	Person selectPersonById(Integer id);

}

MyBatisTest.java


package org.fkit.tst;


import org.apache.ibatis.session.SqlSession;

import org.fkit.domain.Person;


import org.fkit.factory.FKSqlSessionFactory;
import org.fkit.mapper.PersonMapper;

public class MyBatisTest {

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		SqlSession session = FKSqlSessionFactory.getSqlSession();
		
		
		PersonMapper pm = session.getMapper(PersonMapper.class);
		Person p = pm.selectPersonById(1);
		System.out.println(p);
		System.out.println(p.getCard());
		session.commit();
		session.close();

	}

}

Mybatis一对一关系映射
上一篇:Python面试题


下一篇:Mybatis中的一对多及多对一举例