MyBatis 中 resultType 与 resultMap 的几种返回类型,一对一、一对多

MyBatis 中 resultType 与 resultMap 的几种返回类型,一对一、一对多

一、返回集合

1.返回 JavaBean 集合

public List selectMyUserByNameLike(String name);

测试方法

public static void main(String[] args) {

SqlSession session = null;

try {

InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");

SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

session = sqlSessionFactory.openSession();

MyUserMapper mapper = session.getMapper(MyUserMapper.class);

List myUsers = mapper.selectMyUserByNameLike("%a%");

System.out.println(myUsers);

} catch (IOException e) {

e.printStackTrace();

} finally {

if (session != null) {

session.close();

}

}

}

2.返回 Map 集合

二、返回 Map

1.一条记录

public Map selectMyUserById(Integer id);

2.多条记录,需要指定 Map 的 Key 和 Value 的类型

// 指定 Map 的 Key 从记录中的 id 列获取

@MapKey("id")

public Map selectMyUserByGtId(Integer id);

三、返回 resultMap 自定义结果集封装

关于自动映射封装的配置

默认数据库字段与 JavaBean 对应不上时可开启驼峰命名或查询时使用别名:http://www.mybatis.org/mybatis-3/zh_CN/sqlmap-xml.html#Auto-mapping

1.自定义 JavaBean 的封装

确认是否成功可以关掉 MyBatis 的自动映射

public MyUser selectMyUserById(Integer id);

2.关联查询的封装,一对一,JavaBean 属性包含 JavaBean

public MyUser selectMyUserById(Integer id);

直接调用属性赋值

使用 association

使用 association 二次查询,即有两条 SQL

开启懒加载:在没有使用 Dept 的属性时,则只会加载 MyUser 的属性。即只会发送一条 SQL 语句,要使用 Dept 属性时才会发送第二条 SQL。不会一次性发送两条 SQL

3.关联查询的封装,一对多,JavaBean 属性包含 JavaBean 的集合

使用 collection

public Dept getDeptById(Integer id);

关闭懒加载,使用二次查询

public Dept getDeptByIdStep(Integer did);

public List selectMyUserByDid(Integer dId);

4.鉴别器 discriminator

上面测试中使用的实体类与数据

public class Dept {

private Integer id;

private String name;

private List myUsers;

public class MyUser {

private Integer id;

private String name;

private Integer age;

private Dept dept;

https://mybatis.org/mybatis-3/zh_CN/sqlmap-xml.html#Result_Maps

相关推荐

Merinthophobia是什么?
365bet假网站

Merinthophobia是什么?

📅 06-28 👁️ 4546
巫服的传说与作用
365bet假网站

巫服的传说与作用

📅 08-06 👁️ 8525
中华文明统一性的丰富内涵
365bet中文比分

中华文明统一性的丰富内涵

📅 10-29 👁️ 9107
中国古代家教
365bet中文比分

中国古代家教

📅 10-11 👁️ 5363
千壹理财
365bet假网站

千壹理财

📅 08-01 👁️ 8485
别墅地下室防水多少钱一平米?价格与施工要点解析
十大美国动漫排行榜 经典美国动画片推荐 美国高分动漫有哪些→榜中榜
GEM官网官方旗舰店
365bet中文比分

GEM官网官方旗舰店

📅 08-21 👁️ 2683
pp助手怎么下载?
365bet中文比分

pp助手怎么下载?

📅 08-26 👁️ 7927