一对一

创建数据表

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 关联映射的更多相关文章

  1. MyBatis学习(七)MyBatis关联映射之多对多映射

    对于数据库中的多对多关系建议使用一个中间表来维护关系. 1.创建四张表,分别为用户表,商品表,订单表,中间表. DROP TABLE IF EXISTS `t_user`; CREATE TABLE ...

  2. spring boot(9)-mybatis关联映射

    一对多 查询type表的某一条数据,并且要同时查出所有typeid与之配置的user,最终要得到一个以下类型的Type对象 public class Type { String id; String ...

  3. 0049 MyBatis关联映射--一对一关系

    世上的事务总不是孤立存在的,表现在Java类里面,则是类与类之间的关系,比如继承is-a.依赖use-a.关联has-a,反映在数据库中,则是表与表之间的关系,比如外键 关联关系存在着以下几种类型:一 ...

  4. Spring Boot (11) mybatis 关联映射

    一对多 查询category中的某一条数据,同时查询该分类下的所有Product. Category.java public class Category { private Integer id; ...

  5. mybatis关联映射一对一

    在项目开发中,会存在一对一的关系,比如一个人只有一个身份证,一个身份证只能给一个人使用,这就是一对一关系.一对一关系使用主外键关联. table.sql,在数据库中创建如下两个表并插入数据 CREAT ...

  6. mybatis关联映射一对多

    实际项目中也存在很多的一对多的情况,下面看看这个简单的例子 table.sql CREATE TABLE tb_clazz( id INT PRIMARY KEY AUTO_INCREMENT, CO ...

  7. mybatis关联映射多对多

    项目开发中,多对多关系也是非常常见的关系 在数据库中创建表的脚本 table.sql CREATE TABLE tb_user( id INT PRIMARY KEY AUTO_INCREMENT, ...

  8. MyBatis学习(六)MyBatis关联映射之一对多映射

    数据库中一对多通常使用主外键关联,外键应该在多方,即多方维护关系. 下面举一个简单实例来看看MyBatis怎么处理一对多的关系. 1.创建一个项目,导入所需jar包,导入db.properties配置 ...

  9. MyBatis(五):mybatis关联映射

    Mybatis中表与表之间的关系分为一下4类: 1)一对一 2)一对多 3)多对一 4)多对多 创建数据Demo表 数据库表: 用户表user:记录了购买商品的用户信息. 订单表orders:记录了用 ...

  10. 0050 MyBatis关联映射--一对多关系

    一对多关系更加常见,比如用户和订单,一个用户可以有多个订单 DROP TABLE IF EXISTS customer; /*用户表*/ CREATE TABLE customer( `pk` INT ...

随机推荐

  1. 主机网络ping: unknown host baidu.com问题解决

    本机环境: 系统:Centos 网络:NAT 虚拟机之前一直都可以连外网,但最近不能连了,现状如下: [root@vhost03 ~]# ping baidu.comping: unknown hos ...

  2. C# String字符串

    C#(静态String类) C#中提供了比较全面的字符串处理方法,很多函数都进行了封装为我们的编程工作提供了很大的便利.System.String是最常用的字符串操作类,可以帮助开发者完成绝大部分的字 ...

  3. Android viewpager + 可缩放的imageview

    http://files.cnblogs.com/files/liaolandemengxiang/PhotoWallFallsDemo.rar http://files.cnblogs.com/fi ...

  4. shell工具-sort

    sort sort命令是在Linux里非常有用,它将文件进行排序,并将排序结果标准输出 基本语法 sort [选项] [参数] 选项说明 选项 说明 -n 依照数值大小排序 -r 以相反的顺序排序 - ...

  5. 佛祖保佑,永不死机 - /etc/motd文件配置

    /etc/motd (message of to day:每日信息) 一.执行命令: cat <<EOT >/etc/motd _oo0oo_ (| -_- |) \ = / ___ ...

  6. springMVC一个Controller处理所有用户请求的并发问题

    有状态和无状态的对象基本概念: 有状态对象(Stateful Bean),就是有实例变量的对象 ,可以保存数据,是非线程安全的.一般是prototype scope. 无状态对象(Stateless ...

  7. ssh连接超慢解决

    手头有台Linux服务器ssh登录时超级慢,需要几十秒.其它服务器均没有这个问题.平时登录操作都默默忍了.今天终于忍不住想搞清楚到底什么原因.搜索了一下发现了很多关于ssh登录慢的资料,于是自己也学着 ...

  8. Delphi-idHttp-Post JSON用法 good

    从国外网站抄来的代码 Delphi source: http := TIdHttp.Create(nil);http.HandleRedirects := True;//允许头转向http.ReadT ...

  9. Android-Throwable: A WebView method was called on thread 'JavaBridge'.

    错误详情: 01-30 03:36:52.441 12000-12048/cn.h5 D/@@@: e.ttt:java.lang.RuntimeException: java.lang.Throwa ...

  10. [leet code 100] same tree

    1 题目 Given two binary trees, write a function to check if they are equal or not. Two binary trees ar ...