数据库
/*
Navicat MySQL Data Transfer
Source Server : localhost_3306
Source Server Version : 50559
Source Host : localhost:3306
Source Database : mybatis3
Target Server Type : MYSQL
Target Server Version : 50559
File Encoding : 65001
Date: 2019-11-03 15:41:10
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `tb_card`
-- ----------------------------
DROP TABLE IF EXISTS `tb_card`;
CREATE TABLE `tb_card` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(18) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_card
-- ----------------------------
INSERT INTO `tb_card` VALUES ('1', '423501198009191038');
-- ----------------------------
-- Table structure for `tb_person`
-- ----------------------------
DROP TABLE IF EXISTS `tb_person`;
CREATE TABLE `tb_person` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(18) NOT NULL,
`sex` varchar(18) NOT NULL,
`age` int(11) NOT NULL DEFAULT '0',
`card_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `card_id` (`card_id`),
CONSTRAINT `card_id` FOREIGN KEY (`card_id`) REFERENCES `tb_card` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_person
-- ----------------------------
INSERT INTO `tb_person` VALUES ('1', 'jack', '男', '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">
<!-- 根标签 -->
<configuration>
<!-- 指定mybatis 所用日志的具体实现 -->
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
<!--<properties resource="db.properties"/>-->
<!-- 环境配置, 即连接的数据库。可以配置多个,default:指定采用哪个环境 -->
<environments default="test">
<!-- id:唯一标识 -->
<environment id="test">
<!-- 指定事务管理器类型,type="JDBC"指直接使用了JDBC的提交和回滚设置 -->
<transactionManager type="JDBC" />
<!-- 数据源,池类型的数据源 -->
<!-- dateSoure指数据源配置, POOLED是JDBC连接对象的数据源连接池的实现。 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis3?serverTimezone=UTC" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<!-- mappers 告诉mybatis到哪里去找持久化类的映射文件 -->
<mappers>
<mapper resource="mapper/CardMapper.xml"/>
<mapper resource="mapper/PersonMapper.xml"/>
</mappers>
</configuration>
CardMapper.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="nuc.edu.cn.mapper.CardMapper">
<select id="selectCardById" parameterType="int" resultType="nuc.edu.cn.pojo.Card">
select * from tb_card where id = #{id}
</select>
</mapper>
PersonMapper.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="nuc.edu.cn.mapper.PersonMapper">
<select id="selectPerSonById" parameterType="int" resultMap="personMapper">
select * from tb_person where id=1
</select>
<resultMap id="personMapper" type="nuc.edu.cn.pojo.Person">
<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="nuc.edu.cn.mapper.CardMapper.selectCardById"
javaType="nuc.edu.cn.pojo.Card"/>
</resultMap>
</mapper>
jar包
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>nuc.edu</groupId>
<artifactId>mybatis-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mybatis-3</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--添加Thymeleaf依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--mybatis包依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<!--会自动引入log4j以及slf4j-api-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
java代码
KFSqlSessionFactory.java
package nuc.edu.cn.factoty;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
/**
* @Author: Rwenjie
* @ProjectName: mybatis-3
* @Description:
* @Date: 2019/11/3 14:24
**/
public class KFSqlSessionFactory {
private static SqlSessionFactory sqlSessionFactory = null;
//初始化创建的SqlSessionFactory对象
static {
try {
//读取mybatis-config.xml文件
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//获取SqlSession 对象的静态方法
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession();
}
//获取SqlSessionFactory的静态方法
public static SqlSessionFactory getSqlSessionFactory() {
return sqlSessionFactory;
}
}
CardMapper.java
import nuc.edu.cn.pojo.Card;
import nuc.edu.cn.pojo.Person;
public interface CardMapper {
Card selectCardById(Integer id);
}
PersonMapper.java
package nuc.edu.cn.mapper;
import nuc.edu.cn.pojo.Person;
terface PersonMapper {
Person selectPerSonById(Integer id);
}
Card.java
package nuc.edu.cn.pojo;
import java.io.Serializable;
/**
* @Author: Rwenjie
* @ProjectName: mybatis-3
* @Description:
* @Date: 2019/11/3 13:46
**/
public class Card implements Serializable {
private Integer id;//主键 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 nuc.edu.cn.pojo;
import java.io.Serializable;
/**
* @Author: Rwenjie
* @ProjectName: mybatis-3
* @Description:
* @Date: 2019/11/3 13:43
**/
public class Person implements Serializable {
private Integer id; //主键id
private String name; //姓名
private String sex; //性别
private String 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 String getAge() {
return age;
}
public void setAge(String 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 +
'}';
}
}
测试主函数
OneToOne.java
package nuc.edu.cn.test;
import nuc.edu.cn.factoty.KFSqlSessionFactory;
import nuc.edu.cn.mapper.CardMapper;
import nuc.edu.cn.mapper.PersonMapper;
import nuc.edu.cn.pojo.Card;
import nuc.edu.cn.pojo.Person;
import org.apache.ibatis.session.SqlSession;
/**
* @Author: Rwenjie
* @ProjectName: mybatis-3
* @Description:
* @Date: 2019/11/3 14:30
**/
public class OneToOne {
public static void main(String[] args){
//创建session实例
SqlSession session = KFSqlSessionFactory.getSqlSession();
//获得mapper接口的代理对象
//CardMapper cm = session.getMapper(CardMapper.class);
PersonMapper pm = session.getMapper(PersonMapper.class);
//直接调用接口的方法,查询id为1的Person数据
Person person = pm.selectPerSonById(1);
//Card card = cm.selectCardById(1);
//打印Person对象
System.out.println(person);
//打印person对象的关联CardB
System.out.println(person.getCard());
//提交事务
session.commit();
//关闭session
session.close();
}
}
日志
log4j.properties
log4j.rootLogger=DEBUG,A1
log4j.logger.org.apache=DEBUG
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n