Java基础-SSM之mybatis一对一外键关联

时间:2021-11-22 16:45:07

              Java基础-SSM之mybatis一对一外键关联

                                         作者:尹正杰

版权声明:原创作品,谢绝转载!否则将追究法律责任。

一.准备测试环境(创建数据库表)

 1>.创建husbandsfk和wifesfk表

 use yinzhengjie;

 create table husbandsfk(id int primary key auto_increment , hname varchar(20)) ;

 create table wifesfk(id int primary key  auto_increment , wname varchar(20) , hid int , CONSTRAINT fk_hid FOREIGN KEY (hid) references husbandsfk(id)) ;

 alter table wifesfk add constraint unq_hid unique (hid) ;

Java基础-SSM之mybatis一对一外键关联

2>.添加Maven依赖

 <?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.org.yinzhengjie</groupId>
<artifactId>Mybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.17</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.1</version>
</dependency>
</dependencies>
</project>

3>.目录结构如下:

Java基础-SSM之mybatis一对一外键关联

二.编写自定义类

 /*
@author :yinzhengjie
Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
EMAIL:y1053419035@qq.com
*/
package cn.org.yinzhengjie.mybatis.domain.one2one.fk; public class Husband {
private Integer id ;
private String hname ;
private Wife wife; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getHname() {
return hname;
} public void setHname(String hname) {
this.hname = hname;
} public Wife getWife() {
return wife;
} public void setWife(Wife wife) {
this.wife = wife;
}
}

Husband.java 文件内容

 /*
@author :yinzhengjie
Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
EMAIL:y1053419035@qq.com
*/
package cn.org.yinzhengjie.mybatis.domain.one2one.fk; public class Wife {
private Integer id ;
private String wname ;
private Husband husband ; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getWname() {
return wname;
} public void setWname(String wname) {
this.wname = wname;
} public Husband getHusband() {
return husband;
} public void setHusband(Husband husband) {
this.husband = husband;
}
}

Wife.java 文件内容

三.编写配置文件

 <?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>
<properties>
<property name="driver" value="com.mysql.jdbc.Driver"/>
<!--注意 : “?characterEncoding=utf-8&amp;autoReconnect=true&amp;failOverReadOnly=false&amp;allowMultiQueries=true” 表示开启批处理模式-->
<property name="url" value="jdbc:mysql://localhost:5200/yinzhengjie?characterEncoding=utf-8&amp;autoReconnect=true&amp;failOverReadOnly=false&amp;allowMultiQueries=true"/>
<property name="username" value="root"/>
<property name="password" value="yinzhengjie"/>
</properties> <!-- 我们使用typeAliases标签给我们自定义类起个别名。-->
<typeAliases>
<typeAlias type="cn.org.yinzhengjie.mybatis.domain.one2one.fk.Husband" alias="_HusbandFK" />
<typeAlias type="cn.org.yinzhengjie.mybatis.domain.one2one.fk.Wife" alias="_WifeFK" />
</typeAliases> <environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 我们使用mapper标签指定映射文件,使用resource指定具体的路径,如果没有写绝对路径,默认的根路径就在resources目录中-->
<mapper resource="HusbandFKMapper.xml"/>
<mapper resource="WifeFKMapper.xml"/>
</mappers>
</configuration>

mybatis-config.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="husbandsfk">
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
insert into husbandsfk(hname) values(#{hname}) ;
</insert> <select id="selectOne" resultMap="rm_Husband">
select
h.id hid,
h.hname hhname ,
w.id wid ,
w.wname wwname ,
w.hid whid
from
husbandsfk h left outer join wifesfk w on w.hid = h.id
where
h.id = #{id}
</select> <resultMap id="rm_Husband" type="_HusbandFK">
<id column="hid" property="id"/>
<result column="hhname" property="hname" />
<association property="wife" javaType="_WifeFK" column="whid">
<id column="wid" property="id"/>
<result column="wwname" property="wname"/>
<association property="husband" javaType="_HusbandFk" column="whid">
<id column="hid" property="id"/>
<result column="hhname" property="hname"/>
</association>
</association>
</resultMap>
</mapper>

HusbandFKMapper.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="wifesfk">
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
insert into wifesfk(wname , hid) values(#{wname} , #{husband.id}) ;
</insert> </mapper>

WifeFKMapper.xml 文件内容

四.编写测试代码

 /*
@author :yinzhengjie
Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
EMAIL:y1053419035@qq.com
*/
package cn.org.yinzhengjie.mybatis.test; import cn.org.yinzhengjie.mybatis.domain.one2one.fk.Husband;
import cn.org.yinzhengjie.mybatis.domain.one2one.fk.Wife;
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 org.junit.Test; import java.io.InputStream; /**
* 测试一对一
*/
public class TestOne2OneFK {
/**
* 测试插入
*/
@Test
public void testInsert() throws Exception {
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(in);
SqlSession sess = sf.openSession();
Husband h1 = new Husband();
h1.setHname("liyapeng");
Wife w1 = new Wife();
w1.setWname("wangfei");
h1.setWife(w1);
w1.setHusband(h1); sess.insert("husbandsfk.insert" , h1) ;
sess.insert("wifesfk.insert" , w1) ; sess.commit();
sess.close();
System.out.println("插入成功!");
} /**
* 测试查询
*/
@Test
public void testSelectOne() throws Exception {
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(in);
SqlSession sess = sf.openSession();
Husband husband = (Husband) sess.selectOne("husbandsfk.selectOne", 1);
System.out.println(husband.getHname());
sess.commit();
sess.close();
}
}

  运行以上代码查看数据库内容如下:

Java基础-SSM之mybatis一对一外键关联