讓我們讀MyBatis ducuments,MyBatis3 - Mapper XML Files。 對於這種O/R Mapper,您需要創建指示實際模型類的映射器文件。之後,你應該寫一些配置來連接表。
DDL
我猜你的表設置像以下:
CREATE TABLE `person` (
`id` INT(10)
, `first_name` VARCHAR(18)
, `last_name` VARCHAR(18)
, `kind` VARCHAR(1)
, `age` INT);
CREATE TABLE `skill` (
`id` INT(10)
, `person_id` INT(10)
, `desc` VARCHAR(200)
);
INSERT INTO `person`(`id`, `first_name`, `last_name`, `kind`, `age`)
VALUES (1, 'John', 'Smith', 'E', 33)
, (2, 'Jane', 'Smith', 'A', 24)
, (3, 'Jonny', 'Smith', 'B', 55)
, (4, 'J', 'J', 'T', 45)
, (5, 'Alan', 'Turing', 'C', 4);
INSERT INTO `skill`(`id`, `person_id`, `desc`)
VALUES (1, 1, 'John Smith is Engineer')
, (2, 2, 'Jane Smith is Artist')
, (3, 3, 'Jonny Smith is Butcher')
, (4, 4, 'J.J is Teacher')
, (5, 5, 'Alan Turing is Computer');
配置之後,你可以加入一個關鍵的兩個表。這是您的Pokemon
列表。
SELECT * FROM `person` p
LEFT JOIN `skill` s
ON s.person_id = p.id;
SQLFiddle鏈接→SQL Fiddle
我相信你person_id
可以確定記錄唯一。
模型類
Person類
// @Data <-- lombok can generate getter/setter easily
public class Person {
private Integer id;
private String firstName;
private String lastName;
private String kind; // <-- it might be better to use enum
private Integer age;
// with getter/setter or annotations
}
技能類
// @Data
public class Skill {
private Integer id;
private Integer personId;
private String desc;
// with getter/setter or annotations
}
加入PersonSkill類
@Data
public class PersonSkill {
private Integer id;
private String firstName;
private String lastName;
private String kind;
private Integer age;
private Integer skillId;
private String desc;
}
個映射文件
XML配置到結果集保存爲模型類
PersonSkillMapper.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="jp.gr.java_conf.hangedman.mybatis_join_sample.mappers.PersonSkillMapper">
<resultMap id="personSkillResultMap" type="PersonSkill">
<result property="id" column="id" />
<result property="firstName" column="first_name" />
<result property="lastName" column="last_name" />
<result property="kind" column="kind" />
<result property="age" column="age" />
<result property="skillId" column="skill_id" />
<result property="desc" column="desc" />
</resultMap>
<select id="selectList" resultMap="personSkillResultMap">
SELECT
p.*
, s.id AS skill_id
, s.desc AS desc
FROM `person` p
LEFT JOIN `skill` s
ON s.person_id = p.id
</select>
</mapper>
運行
public class App {
public static void main(String[] args) throws IOException {
try (InputStream in = App.class.getResourceAsStream("/mybatis-config.xml")) {
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
try (SqlSession session = factory.openSession()) {
List<PersonSkill> pskills = session
.selectList("jp.gr.java_conf.hangedman.mybatis_join_sample.mappers.PersonSkillMapper.selectList");
for (PersonSkill ps : pskills) {
System.out.println(ps.toString());
}
}
}
}
}
PS 如果您想創建一些可變屬性,則可能需要使用Generics
。請評論,如果你想使用它。