mybatis 关联映射
一对一
创建数据表
CREATE TABLE `tb_card` (
`id` int NOT NULL AUTO_INCREMENT ,
`code` varchar() NULL ,
PRIMARY KEY (`id`)
);
insert into tb_card(code) values('');
CREATE TABLE tb_person(id int not null PRIMARY KEY auto_increment,name VARCHAR(),sex VARCHAR(),age int,card_id int UNIQUE);
INSERT INTO tb_person(name,sex,age,card_id) VALUES('jack','男',,);
目录结构
Card
package com.example.demo.domain; import java.io.Serializable; public class Card implements Serializable {
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;
}
}
Person
package com.example.demo.domain; import java.io.Serializable; public class Person implements Serializable {
private Integer id;
private String name;
private String sex;
private Integer age;
private Card card; public Card getCard() {
return card;
} public void setCard(Card card) {
this.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;
}
}
CardMapper
package com.example.demo.mapper; import com.example.demo.domain.Card; public interface CardMapper {
Card selectCardById(Integer id);
}
PersonMapper
package com.example.demo.mapper; import com.example.demo.domain.Person; public interface PersonMapper {
Person selectPersonById(Integer id);
}
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="com.example.demo.mapper.CardMapper">
<!--<insert id="save" parameterType="com.example.demo.domain.Card" useGeneratedKeys="true">-->
<!--INSERT INTO tb_card(code) VALUES (#{code})-->
<!--</insert>-->
<select id="selectCardById" parameterType="int" resultType="com.example.demo.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="com.example.demo.mapper.PersonMapper">
<!--<insert id="save" parameterType="com.example.demo.domain.Person" useGeneratedKeys="true">-->
<!--INSERT INTO tb_person(name,sex,age,card_id) VALUES (#{name},#{sex},#{age},#{card_id})-->
<!--</insert>-->
<select id="selectPersonById" parameterType="int" resultMap="personMapper">
SELECT * FROM tb_person WHERE id=#{id}
</select>
<resultMap id="personMapper" type="com.example.demo.domain.Person">
<id property="id" column="id"></id>
<result property="name" column="name"></result>
<result property="sex" column="sex"></result>
<result column="age" property="age"></result>
<association property="card" column="card_id" select="com.example.demo.mapper.CardMapper.selectCardById"
javaType="com.example.demo.domain.Card"></association>
</resultMap>
</mapper>
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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://192.168.31.146:3306/mydb"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="CardMapper.xml"></mapper>
<mapper resource="PersonMapper.xml"></mapper>
</mappers>
</configuration>
OnoToOneTest
package com.example.demo.test; import com.example.demo.domain.Person;
import com.example.demo.mapper.PersonMapper;
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.IOException;
import java.io.InputStream; public class OnoToOneTest {
public static void main(String[] args) throws IOException {
InputStream inputStream= Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session=factory.openSession();
PersonMapper pm=session.getMapper(PersonMapper.class);
Person p=pm.selectPersonById();
System.out.println(p);
System.out.println(p.getCard());
session.commit();
session.close();
}
}
运行结果:
这里特别需要注意的是CardMapper.xml和PersonMapper.xml的位置。
一对多
Clazz
package com.example.demo.domain; import java.io.Serializable;
import java.util.List; public class Clazz implements Serializable {
private Integer id;
private String code;
private String name;
private List<Student> students; public List<Student> getStudents() {
return students;
} public void setStudents(List<Student> students) {
this.students = students;
} 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;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
}
Student
package com.example.demo.domain; import java.io.Serializable; public class Student implements Serializable {
private Integer id;
private String name;
private String sex;
private Integer age;
private Clazz clazz; 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 Clazz getClazz() {
return clazz;
} public void setClazz(Clazz clazz) {
this.clazz = clazz;
}
}
ClazzMapper.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="com.example.demo.mapper.ClazzMapper"> <select id="selectClazzById" parameterType="int"
resultMap="clazzResultMap">
SELECT * FROM tb_clazz WHERE id=#{id}
</select>
<resultMap id="clazzResultMap" type="com.example.demo.domain.Clazz">
<id column="id" property="id"></id>
<result property="code" column="code"></result>
<result column="name" property="name"></result>
<collection property="students" javaType="ArrayList" column="id" ofType="com.example.demo.domain.Student"
select="com.example.demo.mapper.StudentMapper.selectStudentByClazzId" fetchType="lazy">
<id property="id" column="id"></id>
<result property="name" column="name"></result>
<result property="sex" column="sex"></result>
<result property="age" column="age"></result>
</collection>
</resultMap>
</mapper>
StudentMapper.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="com.example.demo.mapper.StudentMapper"> <select id="selectStudentById" parameterType="int" resultType="com.example.demo.domain.Student">
SELECT * FROM tb_Student WHERE id=#{id}
</select>
<select id="selectStudentByClazzId" parameterType="int" resultType="com.example.demo.domain.Student">
SELECT * FROM tb_student WHERE clazz_id=#{id}
</select>
</mapper>
ClazzMapper
package com.example.demo.mapper; import com.example.demo.domain.Clazz; public interface ClazzMapper {
Clazz selectClazzById(Integer id);
}
StudentMapper
package com.example.demo.mapper; import com.example.demo.domain.Student; public interface StudentMapper {
Student selectStudentByClazzId(Integer id);
}
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>
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://192.168.31.146:3306/mydb"/>
<property name="username" value="root"/>
<property name="password" value="weiwei1207"/>
</dataSource>
</environment>
</environments> <mappers>
<mapper resource="CardMapper.xml"></mapper>
<mapper resource="PersonMapper.xml"></mapper>
<mapper resource="ClazzMapper.xml"></mapper>
<mapper resource="StudentMapper.xml"></mapper>
</mappers> </configuration>
注意这里添加了settings配置延迟加载
OneToManyTest
package com.example.demo.test; import com.example.demo.domain.Clazz;
import com.example.demo.domain.Student;
import com.example.demo.mapper.ClazzMapper;
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.IOException;
import java.io.InputStream; public class OneToManyTest {
public static void main(String[] args) throws IOException {
InputStream inputStream= Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session=factory.openSession();
ClazzMapper mapper=session.getMapper(ClazzMapper.class);
Clazz clazz=mapper.selectClazzById();
System.out.println(clazz.getId()+" "+clazz.getCode()+" "+clazz.getName());
for(Student student:clazz.getStudents()){
System.out.println(student.getId()+" "+student.getName());
}
}
}
数据库
运行结果
修改StudentMapper
package com.example.demo.mapper; import com.example.demo.domain.Student; public interface StudentMapper {
Student selectStudentByClazzId(Integer id);
Student selectStudentById(Integer id);
}
修改StudentMapper.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="com.example.demo.mapper.StudentMapper"> <select id="selectStudentById" parameterType="int" resultMap="studentResultMap">
SELECT * FROM tb_student a JOIN tb_clazz b ON a.clazz_id=b.id WHERE a.id=#{id}
</select>
<resultMap id="studentResultMap" type="com.example.demo.domain.Student">
<id property="id" column="id"></id>
<result property="name" column="name"></result>
<result property="sex" column="sex"></result>
<result property="age" column="age"></result>
<association property="clazz" javaType="com.example.demo.domain.Clazz">
<id property="id" column="id"></id>
<result property="code" column="code"></result>
<result column="name" property="name"></result>
</association>
</resultMap>
<select id="selectStudentByClazzId" parameterType="int" resultType="com.example.demo.domain.Student">
SELECT * FROM tb_student WHERE clazz_id=#{id}
</select>
</mapper>
修改OneToManyTest
StudentMapper mapper=session.getMapper(StudentMapper.class);
Student student=mapper.selectStudentById();
System.out.println(student.getId()+" "+student.getName()+" "+student.getClazz().getCode()+" "+student.getClazz().getName());
运行
mybatis 关联映射的更多相关文章
- MyBatis学习(七)MyBatis关联映射之多对多映射
对于数据库中的多对多关系建议使用一个中间表来维护关系. 1.创建四张表,分别为用户表,商品表,订单表,中间表. DROP TABLE IF EXISTS `t_user`; CREATE TABLE ...
- spring boot(9)-mybatis关联映射
一对多 查询type表的某一条数据,并且要同时查出所有typeid与之配置的user,最终要得到一个以下类型的Type对象 public class Type { String id; String ...
- 0049 MyBatis关联映射--一对一关系
世上的事务总不是孤立存在的,表现在Java类里面,则是类与类之间的关系,比如继承is-a.依赖use-a.关联has-a,反映在数据库中,则是表与表之间的关系,比如外键 关联关系存在着以下几种类型:一 ...
- Spring Boot (11) mybatis 关联映射
一对多 查询category中的某一条数据,同时查询该分类下的所有Product. Category.java public class Category { private Integer id; ...
- mybatis关联映射一对一
在项目开发中,会存在一对一的关系,比如一个人只有一个身份证,一个身份证只能给一个人使用,这就是一对一关系.一对一关系使用主外键关联. table.sql,在数据库中创建如下两个表并插入数据 CREAT ...
- mybatis关联映射一对多
实际项目中也存在很多的一对多的情况,下面看看这个简单的例子 table.sql CREATE TABLE tb_clazz( id INT PRIMARY KEY AUTO_INCREMENT, CO ...
- mybatis关联映射多对多
项目开发中,多对多关系也是非常常见的关系 在数据库中创建表的脚本 table.sql CREATE TABLE tb_user( id INT PRIMARY KEY AUTO_INCREMENT, ...
- MyBatis学习(六)MyBatis关联映射之一对多映射
数据库中一对多通常使用主外键关联,外键应该在多方,即多方维护关系. 下面举一个简单实例来看看MyBatis怎么处理一对多的关系. 1.创建一个项目,导入所需jar包,导入db.properties配置 ...
- MyBatis(五):mybatis关联映射
Mybatis中表与表之间的关系分为一下4类: 1)一对一 2)一对多 3)多对一 4)多对多 创建数据Demo表 数据库表: 用户表user:记录了购买商品的用户信息. 订单表orders:记录了用 ...
- 0050 MyBatis关联映射--一对多关系
一对多关系更加常见,比如用户和订单,一个用户可以有多个订单 DROP TABLE IF EXISTS customer; /*用户表*/ CREATE TABLE customer( `pk` INT ...
随机推荐
- 深入理解,函数声明、函数表达式、匿名函数、立即执行函数、window.onload的区别.
一.函数声明.函数表达式.匿名函数1.函数声明:function fnName () {…};使用function关键字声明一个函数,再指定一个函数名,叫函数声明. 2.函数表达式 var fnNam ...
- tlink平台数据转发 c# 控制台程序
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.N ...
- Codeforces Round #535 (Div. 3) 1108C - Nice Garland
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.t ...
- KVM学习(初步安装与使用)
本机环境介绍 本次使用Vmware workstation 12 pro版本号为12.5.2 build-4638234.虚拟机操作系统版本如下 [root@node2 ~]# cat /etc/re ...
- Yeoman安装和使用详解
Yeoman generator-react-webpack 一 什么是Yeoman Yeoman帮助我们创建项目,提供更好的工具来使我们的项目更多样化. Yeoman提供generator系统,一个 ...
- 关于java弱引用
最近在学java虚拟机相关的东西,看了一篇微信的推送 在此分享https://mp.weixin.qq.com/s/oLhZWWWIVc90cNUBukkqHw 一.强引用 强引用就是我们经常使用的 ...
- 第5件事 做一个有taste的产品人
1.taste的意思是品位,也就是说产品经理应该是一个有品位的产品人.什么叫品位呢?品位指的是对事物有分辨与鉴赏的能力.品位是形象的展示,品位是内在气质的复出,品位是人生价值的体验,品位是道德修养的内 ...
- [翻译] ASP.NET WebAPI 中的异常处理
原文链接:https://docs.microsoft.com/en-us/aspnet/web-api/overview/error-handling/exception-handling 本文介绍 ...
- WinForm POST上传与后台接收
前端 using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using ...
- Entity Framework 6 多对多增改操作指南
问题描述 在很多系统中,存在多对多关系的维护.如下图: 这种多对多结构在数据库中大部分有三个数据表,其中两个主表,还有一个关联表,关联表至少两个字段,即左表主键.右表主键. 如上图,其中的Suppli ...