One of the latest MyBatis feature is the ability to use Annotations or XML to do One-to-One or One-to-Many queries. Let’s start
with an example, as usual im using PostgreSQL, Netbeans 6.9 and MyBatis 3.0.2.

First is a simple database with 2 different tables,

CREATE DATABASE test
CREATE TABLE master
(
nama CHARACTER VARYING(30) NOT NULL,
usia SMALLINT,
CONSTRAINT idnama PRIMARY KEY (nama)
)
CREATE TABLE contoh
(
id INTEGER NOT NULL,
nama CHARACTER VARYING(30),
alamat CHARACTER VARYING(50),
CONSTRAINT id PRIMARY KEY (id)
)
ALTER TABLE
contoh ADD CONSTRAINT master FOREIGN KEY (nama) REFERENCES master (nama)
ON DELETE CASCADE
ON UPDATE CASCADE insert into master (nama, usia) values ('pepe', 17);
insert into master (nama, usia) values ('bubu', 19); insert into contoh (id, nama, alamat) values (1, 'bubu', 'Tangerang');
insert into contoh (id, nama, alamat) values (2, 'pepe', 'Jakarta');
insert into contoh (id, nama, alamat) values (3, 'bubu', 'Singapore');
insert into contoh (id, nama, alamat) values (4, 'pepe', 'Kuburan');

My java bean, as my java object representation of my database tables,

package com.edw.bean;

import java.util.List;

public class Master {

    private String nama;
private Short usia;
private List<Contoh> contohs; // other setters and getters @Override
public String toString() {
return "Master{" + "nama=" + nama + " usia=" + usia + " contohs=" + contohs + '}';
}
}
package com.edw.bean;

public class Contoh {

    private Integer id;
private String nama;
private String alamat;
private Master master; // other setters and getters @Override
public String toString() {
return "Contoh{" + "id=" + id + " nama=" + nama + " alamat=" + alamat + " master=" + master + '}';
}
}

My XML files for table Contoh and Master queries, please take a look at association tags and collection tags. The association
element deals with a has-one type
relationship. While collection deals with a has-lots-of type
relationship.

<?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.edw.mapper.MasterMapper" >
<!-- result maps -->
<resultMap id="ResultMap" type="com.edw.bean.Master" >
<id column="nama" property="nama" />
<result column="usia" property="usia" />
<!-- collections of Contoh -->
<collection property="contohs" ofType="com.edw.bean.Contoh"
column="nama" select="selectContohFromMaster" />
</resultMap> <!-- one to many select -->
<select id="selectUsingXML" resultMap="ResultMap" parameterType="java.lang.String" >
SELECT
master.nama,
master.usia
FROM
test.master
WHERE master.nama = #{nama}
</select> <select id="selectContohFromMaster"
parameterType="java.lang.String"
resultType="com.edw.bean.Contoh">
SELECT
id,
nama,
alamat
FROM
test.contoh
WHERE
nama = #{nama}
</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.edw.mapper.ContohMapper" >
<!-- result maps -->
<resultMap id="BaseResultMap" type="com.edw.bean.Contoh" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="nama" property="nama" jdbcType="VARCHAR" />
<result column="alamat" property="alamat" jdbcType="VARCHAR" /> <!-- one to one -->
<association property="master" column="nama" javaType="com.edw.bean.Master"
select="selectMasterFromContoh"/>
</resultMap> <!-- one to one select -->
<select id="selectUsingXML" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
SELECT
contoh.id,
contoh.nama,
contoh.alamat
FROM
test.contoh
WHERE
id = #{id,jdbcType=INTEGER}
</select> <select id="selectMasterFromContoh"
parameterType="java.lang.String"
resultType="com.edw.bean.Master">
SELECT
master.nama,
master.usia
FROM
test.master
WHERE
nama = #{nama}
</select>
</mapper>

This is my main xml configuration to handle my database connections,

<?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="UNPOOLED">
<property name="driver" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://localhost:5432/test"/>
<property name="username" value="postgres"/>
<property name="password" value="password"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/edw/xml/ContohMapper.xml" />
<mapper resource="com/edw/xml/MasterMapper.xml" />
</mappers>
</configuration>

and a java class to load my XML files

package com.edw.config;

import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class MyBatisSqlSessionFactory { protected static final SqlSessionFactory FACTORY; static {
try {
Reader reader = Resources.getResourceAsReader("com/edw/xml/Configuration.xml");
FACTORY = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e){
throw new RuntimeException("Fatal Error. Cause: " + e, e);
}
} public static SqlSessionFactory getSqlSessionFactory() {
return FACTORY;
}
}

These are my mapper interfaces, i put my annotation queries here. Please take a note at @Many and @One annotations.
MyBatis use @One to map a single property value of a complex type, while @Many for mapping a collection property of a complex types.

package com.edw.mapper;

import com.edw.bean.Contoh;
import com.edw.bean.Master;
import java.util.List; import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select; public interface MasterMapper { Master selectUsingXML(String nama); /*
* one to many Select.
*/
@Select("SELECT master.nama, master.usia FROM test.master WHERE master.nama = #{nama}")
@Results(value = {
@Result(property="nama", column="nama"),
@Result(property="usia", column="usia"),
@Result(property="contohs", javaType=List.class, column="nama",
many=@Many(select="getContohs"))
})
Master selectUsingAnnotations(String nama); @Select("SELECT contoh.id, contoh.nama, contoh.alamat FROM test.contoh WHERE contoh.nama = #{nama}")
List<Contoh> getContohs(String nama);
}
package com.edw.mapper;

import com.edw.bean.Contoh;
import com.edw.bean.Master;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select; public interface ContohMapper { Contoh selectUsingXML(Integer nama); /*
* one to one Select.
*/
@Select("SELECT contoh.id, contoh.nama, contoh.alamat FROM test.contoh WHERE contoh.id = #{id}")
@Results(value = {
@Result(property = "nama", column = "nama"),
@Result(property = "alamat", column = "alamat"),
@Result(property = "master", column = "nama", one=@One(select = "getMaster"))
})
Contoh selectUsingAnnotations(Integer id); @Select("SELECT master.nama, master.usia FROM test.master WHERE master.nama = #{nama}")
Master getMaster(String nama);
}

Here is my main java class

package com.edw.main;

import com.edw.bean.Contoh;
import com.edw.bean.Master;
import com.edw.config.MyBatisSqlSessionFactory;
import com.edw.mapper.ContohMapper;
import com.edw.mapper.MasterMapper;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger; public class Main { private static Logger logger = Logger.getLogger(Main.class); public Main() {
} private void execute() throws Exception{
SqlSession session = MyBatisSqlSessionFactory.getSqlSessionFactory().openSession();
try {
MasterMapper masterMapper = session.getMapper(MasterMapper.class); // using XML queries ------------------------------
Master master = masterMapper.selectUsingXML("pepe");
logger.debug(master); List<Contoh> contohs = master.getContohs();
for (Contoh contoh : contohs) {
logger.debug(contoh);
} // using annotation queries ------------------------------
master = masterMapper.selectUsingAnnotations("pepe");
logger.debug(master); List<Contoh> contohs2 = master.getContohs();
for (Contoh contoh : contohs2) {
logger.debug(contoh);
} // using XML queries ------------------------------
ContohMapper contohMapper = session.getMapper(ContohMapper.class);
Contoh contoh = contohMapper.selectUsingXML(1);
logger.debug(contoh.getMaster()); // using annotation queries ------------------------------
contoh = contohMapper.selectUsingAnnotations(1);
logger.debug(contoh); session.commit();
} finally {
session.close();
}
} public static void main(String[] args) throws Exception {
try {
Main main = new Main();
main.execute();
} catch (Exception exception) {
logger.error(exception.getMessage(), exception);
}
}
}

And this is what happen on my java console, im using log4j to do all the loggings.

DEBUG java.sql.Connection:27 - ooo Connection Opened
DEBUG java.sql.PreparedStatement:27 - ==> Executing: SELECT master.nama, master.usia FROM test.master WHERE master.nama = ?
DEBUG java.sql.PreparedStatement:27 - ==> Parameters: pepe(String)
DEBUG java.sql.ResultSet:27 - <== Columns: nama, usia
DEBUG java.sql.ResultSet:27 - <== Row: pepe, 17
DEBUG java.sql.PreparedStatement:27 - ==> Executing: SELECT id, nama, alamat FROM test.contoh WHERE nama = ?
DEBUG java.sql.PreparedStatement:27 - ==> Parameters: pepe(String)
DEBUG java.sql.ResultSet:27 - <== Columns: id, nama, alamat
DEBUG java.sql.ResultSet:27 - <== Row: 2, pepe, Jakarta
DEBUG java.sql.ResultSet:27 - <== Row: 4, pepe, Kuburan
DEBUG com.edw.main.Main:32 - Master{nama=pepe usia=17 contohs=[Contoh{id=2 nama=pepe alamat=Jakarta master=null}, Contoh{id=4 nama=pepe alamat=Kuburan master=null}]}
DEBUG com.edw.main.Main:36 - Contoh{id=2 nama=pepe alamat=Jakarta master=null}
DEBUG com.edw.main.Main:36 - Contoh{id=4 nama=pepe alamat=Kuburan master=null}
DEBUG java.sql.PreparedStatement:27 - ==> Executing: SELECT master.nama, master.usia FROM test.master WHERE master.nama = ?
DEBUG java.sql.PreparedStatement:27 - ==> Parameters: pepe(String)
DEBUG java.sql.ResultSet:27 - <== Columns: nama, usia
DEBUG java.sql.ResultSet:27 - <== Row: pepe, 17
DEBUG java.sql.PreparedStatement:27 - ==> Executing: SELECT contoh.id, contoh.nama, contoh.alamat FROM test.contoh WHERE contoh.nama = ?
DEBUG java.sql.PreparedStatement:27 - ==> Parameters: pepe(String)
DEBUG java.sql.ResultSet:27 - <== Columns: id, nama, alamat
DEBUG java.sql.ResultSet:27 - <== Row: 2, pepe, Jakarta
DEBUG java.sql.ResultSet:27 - <== Row: 4, pepe, Kuburan
DEBUG com.edw.main.Main:41 - Master{nama=pepe usia=17 contohs=[Contoh{id=2 nama=pepe alamat=Jakarta master=null}, Contoh{id=4 nama=pepe alamat=Kuburan master=null}]}
DEBUG com.edw.main.Main:45 - Contoh{id=2 nama=pepe alamat=Jakarta master=null}
DEBUG com.edw.main.Main:45 - Contoh{id=4 nama=pepe alamat=Kuburan master=null}
DEBUG java.sql.PreparedStatement:27 - ==> Executing: SELECT contoh.id, contoh.nama, contoh.alamat FROM test.contoh WHERE id = ?
DEBUG java.sql.PreparedStatement:27 - ==> Parameters: 1(Integer)
DEBUG java.sql.ResultSet:27 - <== Columns: id, nama, alamat
DEBUG java.sql.ResultSet:27 - <== Row: 1, bubu, Tangerang
DEBUG java.sql.PreparedStatement:27 - ==> Executing: SELECT master.nama, master.usia FROM test.master WHERE nama = ?
DEBUG java.sql.PreparedStatement:27 - ==> Parameters: bubu(String)
DEBUG java.sql.ResultSet:27 - <== Columns: nama, usia
DEBUG java.sql.ResultSet:27 - <== Row: bubu, 19
DEBUG com.edw.main.Main:51 - Master{nama=bubu usia=19 contohs=null}
DEBUG java.sql.PreparedStatement:27 - ==> Executing: SELECT contoh.id, contoh.nama, contoh.alamat FROM test.contoh WHERE contoh.id = ?
DEBUG java.sql.PreparedStatement:27 - ==> Parameters: 1(Integer)
DEBUG java.sql.ResultSet:27 - <== Columns: id, nama, alamat
DEBUG java.sql.ResultSet:27 - <== Row: 1, bubu, Tangerang
DEBUG java.sql.PreparedStatement:27 - ==> Executing: SELECT master.nama, master.usia FROM test.master WHERE master.nama = ?
DEBUG java.sql.PreparedStatement:27 - ==> Parameters: bubu(String)
DEBUG java.sql.ResultSet:27 - <== Columns: nama, usia
DEBUG java.sql.ResultSet:27 - <== Row: bubu, 19
DEBUG com.edw.main.Main:55 - Contoh{id=1 nama=bubu alamat=Tangerang master=Master{nama=bubu usia=19 contohs=null}}
DEBUG java.sql.Connection:27 - xxx Connection Closed

my
log4j.properties

# Global logging configuration
log4j.rootLogger=DEBUG,stdout # Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p %c:%L - %m%n

Beginning MyBatis 3 Part 2 : How to Handle One-to-Many and One-to-One Selects的更多相关文章

  1. MyBatis(3.2.3) - Configuring MyBatis using XML, typeHandlers

    As discussed in the previous chapter, MyBatis simplifies the persistent logic implementation by abst ...

  2. MyBatis学习总结(一)——ORM概要与MyBatis快速起步

    程序员应该将核心关注点放在业务上,而不应该将时间过多的浪费在CRUD中,多数的ORM框架都把增加.修改与删除做得非常不错了,然后数据库中查询无疑是使用频次最高.复杂度大.与性能密切相关的操作,我们希望 ...

  3. [翻译.每月一译.每日一段]Exploring Fonts with DirectWrite and Modern C++

    Windows with C++ Exploring Fonts with DirectWrite and Modern C++ Kenny Kerr DirectWrite is an incred ...

  4. js实现省市区联动

    先来看看效果图吧,嘻嘻~~~~~~~~~~~~~~~~~~~· 代码在下面: 示例一: html: <!DOCTYPE html> <html> <head> &l ...

  5. 我为什么放弃使用MyBatis3的Mapper注解

    最近在使用MyBatis3做项目.在使用注解实现Mapper的时候遇到了比较奇葩的问题:在实现数据的batch insert的时候总是报错.好不容易可以正常插入了,但是又不能返回自增的主键id到实体b ...

  6. 我为什么放弃使用mybatis3的mapper注解了

    原文链接 最近在使用MyBatis3做项目.在使用注解实现Mapper的时候遇到了比较奇葩的问题:在实现数据的batch insert的时候总是报错.好不容易可以正常插入了,但是又不能返回自增的主键i ...

  7. select2插件改造之设置自定义选项 源码

    改造特性: 适应业务需要,选项里面包含“其他”其它”,可以点击填写并设置自定义选项 效果图: 具体代码不做阐述,如有类似需求,请私信.主要源码: /* Copyright 2012 Igor Vayn ...

  8. Building microservices with ASP.NET Core (without MVC)(转)

    There are several reasons why it makes sense to build super-lightweight HTTP services (or, despite a ...

  9. android surfaView surfaHolder video 播放

    主文件 package cn.com.sxp;import android.app.Activity;import android.media.AudioManager;import android. ...

随机推荐

  1. FreeCodeCamp:Title Case a Sentence

    要求: 确保字符串的每个单词首字母都大写,其余部分小写. 像'the'和'of'这样的连接符同理. 结果: titleCase("I'm a little tea pot") 应该 ...

  2. 关于MyEclipse启动时的插件启动(Maven4MyEclipse)

    在myEclipse的应用中有许多插件在开发的时候都用不到,那么,这些插件在启动myEclipse的时候一起启动的越少越好了 Maven4Myeclipse update 每当启动myEclipse的 ...

  3. win7 VMware Workstation Centos6.5虚机桥接上网设置 详解(靠谱)

    1.VMware Workstation 设置 2. vim /etc/sysconfig/network-scripts/ifcfg-eth0 NAME="System eth0" ...

  4. USB CCID协议和PC/SC标准

    CCID是USB Chip/Smart Card Interface Devices,也就是USB芯片智能卡接口设备,是USB规范下的一种设备类型.就像HID设备一样,需要参考USB规范来写固件程序来 ...

  5. F#实现的单链表(函数式的思想)

    // 在 http://fsharp.net 上了解有关 F# 的更多信息 // 请参阅“F# 教程”项目以获取更多帮助. type list = | Nil | Cons of int * list ...

  6. HDU 4734 F(x) 2013 ACM/ICPC 成都网络赛

    传送门:http://acm.hdu.edu.cn/showproblem.php?pid=4734 数位DP. 用dp[i][j][k] 表示第i位用j时f(x)=k的时候的个数,然后需要预处理下小 ...

  7. 在VS上配置OpenCV

    这几篇帖子讲的挺仔细的,而且不坑,结合看看就没问题了~~ http://www.cnblogs.com/cuteshongshong/p/4057193.html http://my.phirobot ...

  8. [Swust OJ 1132]-Coin-collecting by robot

          题目链接:          http://acm.swust.edu.cn/problem/1132/ Time limit(ms): 1000 Memory limit(kb): 65 ...

  9. 兼容性问题( css)

    记录平时遇见的兼容性问题,有更好的解决办法希望各位提出,会持续更新 提出时间 问题描述 解决方案 2014/7/15 table下面使用img或者其他元素例如embed会产生,对应的空隙,假如使用文字 ...

  10. 如何设置ssh安全只允许用户从指定的IP登陆

    原文链接: 如何设置ssh安全只允许用户从指定的IP登陆 由于开发上传文件需要  在服务器上开启  允许用户名和密码ssh登录.这样不太安全.百度后参考文章现在ssh用户名和密码登录的ip. 登录服务 ...