实现一对一是采用association方法:

<resultMap type="testId" id="users">
<association property="major" column="major" select="com.dao.MajorMapper.selectbyid"></association>
</resultMap>

  实现一对多是采用collection方法:

<resultMap type="major" id="major">
<id property="id" column="id"/>
<collection property="testids" column="id" select="com.dao.UserMapper.selectid"></collection>
</resultMap>

  下面进行实例:

  定义三个表及数据:

  可以看到testinfo表里定义一个id列对应test表里的id主键,是一对一的关系。并且这里为了测试,只给81和141的id设置testinfo信息。major表里是专业名称,是个一对多的关系。

  1.定义mybatis配置文件

  

<?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 resource="db.properties"></properties>
<typeAliases>
<package name="com.model"/>
</typeAliases> <environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="url" value="${jdbc.url}"/>
<property name="driver" value="${jdbc.driverClass}"/>
</dataSource> </environment>
</environments> <mappers>
<!-- <mapper resource="com/dao/UserMapper.xml"/> -->
<package name="com.dao"/>
</mappers>
</configuration>

  

jdbc.username=root
jdbc.password=123
jdbc.url=jdbc:oracle:thin:@localhost:1521:orcl
jdbc.driverClass=oracle.jdbc.OracleDriver

  

  2.定义实体类:

package com.model;
// Generated 2017-4-19 10:19:42 by Hibernate Tools 5.2.0.CR1 import java.math.BigDecimal; import org.apache.ibatis.type.Alias; /**
* TestId generated by hbm2java
*/
public class TestId { private BigDecimal id;
private String username;
private String password;
private Major major; public Major getMajor() {
return major;
} public void setMajor(Major major) {
this.major = major;
} public TestId() {
} public BigDecimal getId() {
return this.id;
} public void setId(BigDecimal id) {
this.id = id;
} public String getUsername() {
return this.username;
} public void setUsername(String username) {
this.username = username;
} public String getPassword() {
return this.password;
} public void setPassword(String password) {
this.password = password;
} public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof TestId))
return false;
TestId castOther = (TestId) other; return ((this.getId() == castOther.getId())
|| (this.getId() != null && castOther.getId() != null && this.getId().equals(castOther.getId())))
&& ((this.getUsername() == castOther.getUsername()) || (this.getUsername() != null
&& castOther.getUsername() != null && this.getUsername().equals(castOther.getUsername())))
&& ((this.getPassword() == castOther.getPassword()) || (this.getPassword() != null
&& castOther.getPassword() != null && this.getPassword().equals(castOther.getPassword())));
} public int hashCode() {
int result = 17; result = 37 * result + (getId() == null ? 0 : this.getId().hashCode());
result = 37 * result + (getUsername() == null ? 0 : this.getUsername().hashCode());
result = 37 * result + (getPassword() == null ? 0 : this.getPassword().hashCode());
return result;
} @Override
public String toString() {
return "TestId [id=" + id + ", username=" + username + ", password=" + password + ", major=" + major + "]";
} public TestId(BigDecimal id, String username, String password, Major major) {
super();
this.id = id;
this.username = username;
this.password = password;
this.major = major;
} }

  

package com.model;

import java.util.Date;

public class TestInfo {
private Integer ids;
private TestId testId;
private String address;
private Date birthday;
public Integer getIds() {
return ids;
}
public void setIds(Integer ids) {
this.ids = ids;
}
public TestId getTestId() {
return testId;
}
public void setTestId(TestId testId) {
this.testId = testId;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public TestInfo(Integer ids, TestId testId, String address, Date birthday) {
super();
this.ids = ids;
this.testId = testId;
this.address = address;
this.birthday = birthday;
}
public TestInfo() {
super();
}
@Override
public String toString() {
return "TestInfo [ids=" + ids + ", testId=" + testId + ", address=" + address + ", birthday=" + birthday + "]";
} }

  

package com.model;

import java.util.List;

public class Major {
private Integer id;
private String code;
private String name;
private List<TestId> testids; public List<TestId> getTestids() {
return testids;
}
public void setTestids(List<TestId> testids) {
this.testids = testids;
}
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;
}
public Major(Integer id, String code, String name, List<TestId> testids) {
super();
this.id = id;
this.code = code;
this.name = name;
this.testids = testids;
}
public Major() {
super();
}
@Override
public String toString() {
return "Major [id=" + id + ", code=" + code + ", name=" + name + ", testids=" + testids.size() + "]";
} }

  3.定义一个mybatis的工具类,获取mybatis核心sqlsessionfactory

package com.util;

import java.io.IOException;
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; /**
* mybatis工具类
* @author Administrator
*
*/
public class MybatisUtil {
private static SqlSessionFactory ssf;
private static SqlSession ss; /**
* 获取mybatis核心sqlsessionfactory
* @return
*/
private static SqlSessionFactory getSqlSessionFctory(){
InputStream it = null; try {
it = Resources.getResourceAsStream("mybatis-config.xml");
ssf= new SqlSessionFactoryBuilder().build(it);
ss=ssf.openSession();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} return ssf;
}
/**
* 获取sqlsession
* @return
*/
public static SqlSession getSqlSession(){
ss= getSqlSessionFctory().openSession();
return ss; }
public static void main(String[] args){
System.out.println(getSqlSession());
}
}

  4.定义接口

package com.dao;

import java.util.List;
import java.util.Map; import com.model.Major;
import com.model.TestId; public interface UserMapper {
/*public Integer add(TestId ti); public Integer delete(Integer id); public Integer update(TestId ti);
*/
public TestId select(Integer id); public List<TestId> selectlist(Map<String, Object> map); public List<TestId> selectid(Integer major);
}

  

package com.dao;

import java.util.List;

import com.model.TestInfo;

public interface UserInfoMapper {
public List<TestInfo> select();
}

  

package com.dao;

import java.util.List;

import com.model.Major;

/**
* 专业表操作
* @author Administrator
*
*/
public interface MajorMapper {
public List<Major> selectAll(); public Major selectbyid(Integer id);
}

  5.定义每个实体类的映射方法

<?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.dao.UserMapper"> <resultMap type="testId" id="users">
<association property="major" column="major" select="com.dao.MajorMapper.selectbyid"></association>
</resultMap> <!-- <insert id="add" parameterType="testId">
insert into test values(sq_mybatis.nextval,#{username},#{password})
</insert> <delete id="delete" parameterType="Integer">
delete test t where t.id=#{id}
</delete> <update id="update" parameterType="testId">
update test t set t.username=#{username},t.password=#{password} where t.id=#{id}
</update> --> <select id="select" parameterType="Integer" resultMap="users">
select * from test t where t.id=#{id}
</select> <select id="selectlist" parameterType="Map" resultMap="users">
select * from test t where t.username like #{username} and t.password like #{password}
</select> <select id="selectid" parameterType="Integer" resultMap="users">
select * from test t where t.major=#{major}
</select> </mapper>

  

<?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.dao.UserInfoMapper">
<!-- 一对一级连查询方法1 -->
<resultMap type="testInfo" id="userslist">
<id property="ids" column="ids"/> <result property="testId.id" column="id"/>
<result property="testId.username" column="username"/>
<result property="testId.password" column="password"/> <result property="address" column="address"/>
<result property="birthday" column="birthday"/>
</resultMap>
<!-- 一对一级连查询方法2 -->
<resultMap type="testInfo" id="userlist">
<association property="testId" column="id" select="com.dao.UserMapper.select"></association>
</resultMap> <select id="select" resultMap="userslist">
select * from testinfo ti left join test t on ti.id=t.id
</select>
</mapper>

  

<?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.dao.MajorMapper">
<!-- 一对多的查询方法 -->
<resultMap type="major" id="major">
<id property="id" column="id"/>
<collection property="testids" column="id" select="com.dao.UserMapper.selectid"></collection>
</resultMap>
<select id="selectAll" resultMap="major">
select * from major
</select> <select id="selectbyid" parameterType="Integer" resultMap="major" >
select * from major m where m.id=#{id}
</select>
</mapper>

  6.定义junit测试文件来进行测试

package com.util;

import static org.junit.Assert.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; import com.dao.UserMapper;
import com.model.TestId; public class Junit { private SqlSession ss;
private UserMapper um; @Before
public void setUp() throws Exception {
ss=MybatisUtil.getSqlSession();
um=ss.getMapper(UserMapper.class);
} @After
public void tearDown() throws Exception {
ss.commit();
ss.close();
} /*public void test() {
TestId ti = new TestId();
ti.setUsername("张张柳");
ti.setPassword("443221");
//int i =ss.insert("com.dao.UserMapper.add",ti);
int i=um.add(ti);
System.out.println(i);
} public void test1(){
int i = um.delete(401);
System.out.println(i);
} public void test2(){
TestId ti = new TestId();
ti.setId(new BigDecimal(441));
ti.setUsername("张张柳2");
ti.setPassword("443221"); um.update(ti);
}*/ /**
* 查询id为441的所有信息
*/
@Test
public void test3(){
TestId ti =um.select(441);
System.out.println(ti);
} public void tes4(){
Map<String, Object> map = new HashMap<String, Object>();
map.put("username", "张%");
map.put("password", "%2%");
List<TestId> list =um.selectlist(map);
for(TestId ti:list){
System.out.println(ti);
} }
/**
* 查询major为2的所有数据
*/
public void test5(){
List<TestId> list = um.selectid(2);
for(TestId ti:list){
System.out.println(ti);
}
} }

  

package com.util;

import static org.junit.Assert.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; import com.dao.UserInfoMapper;
import com.dao.UserMapper;
import com.model.TestId;
import com.model.TestInfo; public class Junit2 { private SqlSession ss;
private UserInfoMapper um; @Before
public void setUp() throws Exception {
ss=MybatisUtil.getSqlSession();
um=ss.getMapper(UserInfoMapper.class);
} @After
public void tearDown() throws Exception {
ss.commit();
ss.close();
} @Test
public void test() {
List<TestInfo> list = um.select();
for(TestInfo ti :list){
System.out.println(ti);
}
} }

  

package com.util;

import static org.junit.Assert.*;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; import com.dao.MajorMapper;
import com.model.Major;
import com.model.TestInfo; public class Junit3 {
private SqlSession ss;
private MajorMapper mm; @Before
public void setUp() throws Exception {
ss=MybatisUtil.getSqlSession();
mm=ss.getMapper(MajorMapper.class);
} @After
public void tearDown() throws Exception {
ss.commit();
ss.close();
} @Test
public void test2(){
Major m = mm.selectbyid(2);
System.out.println(m);
}
public void test() {
List<Major> list = mm.selectAll();
for(Major ti :list){
System.out.println(ti);
}
} }

  

Mybatis通过接口实现一对一及一对多的查询的更多相关文章

  1. 六 mybatis高级映射(一对一,一对多,多对多)

    1  订单商品数据模型 以订单商品数据为模型,来对mybaits高级关系映射进行学习.

  2. mybatis一对一 和 一对多 嵌套查询

    实际项目中的,接口对外VO  会出现 一对一 和 一对多的情况,举例:小区 下面有 楼栋  ,楼栋 下面有 房屋    ,   房屋里面又房间 小区Vo  : districtVo { id: nam ...

  3. mybatis高级映射(一对一,一对多)

    mybatis高级映射 一对一关联映射 需求:查询订单信息,关联查询用户信息(一个订单对应一个用户) (1)通过resultType实现 sql语句: select orders.* , USER.u ...

  4. mybatis学习记录六——一对一、一对多和多对多查询

    9       订单商品数据模型 9.1     数据模型分析思路 1.每张表记录的数据内容 分模块对每张表记录的内容进行熟悉,相当 于你学习系统 需求(功能)的过程. 2.每张表重要的字段设置 非空 ...

  5. MyBatis4——一对一、一对多关联查询

    关联查询: 一对一: 1.业务扩展类     核心:用resultType指定的类的属性包含多表查询的所有字段. 2.resultMap     通过添加属性成员建立两个类之间的连接 <!--利 ...

  6. MyBatis 详解(一对一,一对多,多对多)

    1.什么是MyBatis? MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且 ...

  7. Mybatis实现高级映射一对一、一对多查询

    终于把论文写得差不多了,系统也不急着完成,可以抽出点时间来完成这个系列的博客了.在写本博客之前我是惶恐不安的,高级映射一贯是持久层框架里的重中之重,小到自己开发小系统,大到企业级开发,表的存在从来就不 ...

  8. mybatis实现多表一对一,一对多,多对多关联查询

    原文:https://blog.csdn.net/m0_37787069/article/details/79247321 1.一对一关键字:association作用:针对pojo对象属性的映射  ...

  9. MyBatis --- 映射关系【一对一、一对多、多对多】,懒加载机制

    映射(多.一)对一的关联关系 1)若只想得到关联对象的id属性,不用关联数据表 2)若希望得到关联对象的其他属性,要关联其数据表 举例: 员工与部门的映射关系为:多对一 1.创建表 员工表 确定其外键 ...

随机推荐

  1. codeforce 599B Spongebob and Joke

    一道水题WA那么多发,也是醉了.f看成函数的话,其实就是判断一下反函数存不存在. 坑点,只能在定义域内判断,也就是只判断b[i].没扫一遍前不能确定Impossible. #include<bi ...

  2. squid如何屏蔽User-Agent为空的请求

    搞定了,反过来就行了acl has_user_agent browser ^ http_access deny !has_user_agent

  3. 深入理解计算机系统_3e 第九章家庭作业 CS:APP3e chapter 9 homework

    9.11 A. 00001001 111100 B. +----------------------------+ | Parameter Value | +--------------------- ...

  4. python_68_迭代器

    ''' 我们已经知道,可以直接作用于for循环的数据类型有以下几种: 一类是集合数据类型,如list.tuple.dict.set.str等: 一类是generator,包括生成器和带yield的ge ...

  5. Java 发送邮件工具类

    1.  Mail.java package util; import java.util.Date; import java.util.Properties; import javax.mail.Au ...

  6. 解决Postgresql服务启动又关闭的问题

    查看日志发现如下错误消息:%t LOG: could not receive data from client: An operation was attempted on something tha ...

  7. double类型的小数,四舍五入保留两位小数

    import java.math.BigDecimal; public class Kewai{ public static void main(String[] args) { double f = ...

  8. C语言字符,字符串,字节操作常用函数

    strlen 这个函数是在 string.h 的头文件中定义的 它的函数原型是 size_t strlen( const char ); size_t 是一个无符号整型,是这样定义的 typedef ...

  9. MySQL 5.7 在线启用和关闭GTID

    1.相关基础 MySQL 5.7.6之后GTID_MODE提供了两个新的选项分别为ON_PERMISSIVE和OFF_PERMISSIVEOFF_PERMISSIVE:不产生GTID事务, Slave ...

  10. 第十三篇、OC_UICollectionView的基本配置

    - (UICollectionView *) categoryCollectionView { if (! _categoryCollectionView) { // 创建布局 UICollectio ...