入门案例
引入jar包
创建一个与数据库的user表对应的User类
public class User {
private Integer id;
private String username;
private String sex;
private Date birthday;
private String address;
private String uuid2;
public User(String username, String sex, Date birthday, String address) {
this.username = username;
this.sex = sex;
this.birthday = birthday;
this.address = address;
}
public User() {
}
public String getUuid2() {
return uuid2;
}
public void setUuid2(String uuid2) {
this.uuid2 = uuid2;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday + ", address="
+ address + ", uuid2=" + uuid2 + "]";
}
}
配置User类的配置文件user.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">
<!--
namespace:命名空间,用于隔离sql语句后续有重要作用
#{}:占位符,相当于jdbc的问号
-->
<mapper namespace="user">
<!--
id:sql的id,语句的唯一标识
parameterType:入参的数据类型
resultType:返回结果的数据类型
-->
<select id="getUserById" parameterType="int" resultType="pojo.User">
SELECT
`id`,
`username`,
`birthday`,
`sex`,
`address`
FROM
`mybatis`.`user`
where id = #{id}
</select>
</mapper>
配置SqlMapConfig.xml配置文件
约束
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
在<configuration>标签中配置环境以及pojo类的配置文件
<configuration>
<!-- 和spring整合后 environments配置将废除 -->
<environments default="development">
<environment id="development">
<!-- 使用jdbc事务管理 -->
<transactionManager type="JDBC" />
<!-- 数据库连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql:///mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<mappers>
<!-- 这里配置映射文件会基于classpath查找,mybatis是classpath(config文件夹)下的一个文件夹-->
<mapper resource="mybatis/UserMapper.xml"/>
</mappers>
<configuration>
测试
@Test
public void testGetUserById() throws IOException{
//创建SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//创建核心配置文件的输入流
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//通过输入流创建SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
//创建sqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//执行查询
User user1 = sqlSession.selectOne("user.getUserById", 1);
System.out.println(user1);
//释放资源
sqlSession.close();
}
将测试类中创建工厂的方法封装程工具类
public class SqlSessionFactoryUtil {
private static SqlSessionFactory sqlSessionFactory;
static{
try {
//创建SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//创建核心配置文件的输入流
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//通过输入流创建SqlSessionFactory对象
sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getSqlSessionFactory() {
return sqlSessionFactory;
}
}
模糊查询
#{ }, ${ }
user.xml中添加配置
<!--
${}:字符串拼接指令,如果入参为普通数据类型则大括号中只能写value
如果返回值是一个集合,类型只需写每一个元素的类型
-->
<select id="getUserByUsername" parameterType="string" resultType="pojo.User">
SELECT
`id`,
`username`,
`birthday`,
`sex`,
`address`
FROM
`mybatis`.`user`
<!-- 对应MybatisTest中sql语句不同 -->
<!-- where username like #{name} -->
where username like '%${value}%'
</select>
@Test
public void TestGetUserByUserName(){
SqlSession sqlSession = SqlSessionFactoryUtil.getSqlSessionFactory().openSession();
// List<User> list = sqlSession.selectList("user.getUserByUsername", "%张%");
// DEBUG [main] - ==> Preparing: SELECT `id`, `username`, `birthday`, `sex`, `address` FROM `mybatis`.`user` where username like ?
// DEBUG [main] - ==> Parameters: %张%(String)
List<User> list = sqlSession.selectList("user.getUserByUsername", "张");
// DEBUG [main] - ==> Preparing: SELECT `id`, `username`, `birthday`, `sex`, `address` FROM `mybatis`.`user` where username like '%张%'
// DEBUG [main] - ==> Parameters:
for (User user : list) {
System.out.println(user);
}
sqlSession.close();
}
添加用户
useGeneratedKeys(主键返回)--------select last_insert_id()
在insertUser方法上配置useGeneratedKeys属性,相当于执行了select last_insert_id(),测试方法中就可以得到这个值
<!--
这里useGeneratedKeys="true" keyProperty="id"配套使用相当于下面selectKey中内容
使MabytisTest中插入的数据得到id
-->
<insert id="insertUser" parameterType="pojo.User" useGeneratedKeys="true" keyProperty="id">
<!-- 主键返回
selectKey:主键返回
resultType:主键数据类型
order:指定selectKey何时执行
-->
<!--
<selectKey keyProperty="id" resultType="int" order="AFTER" >
select last_insert_id()
</selectKey>
-->
insert into `mybatis`.`user` (
`username`,
`birthday`,
`sex`,
`address`
)
values
(
#{username},
#{birthday},
#{sex},
#{address}
);
</insert>
@Test
public void TestInsertUser(){
SqlSession sqlSession = SqlSessionFactoryUtil.getSqlSessionFactory().openSession();//如果这里传参为true,就表示自动提交事务
User user = new User("张三1111","1",new Date(),"湖北");
sqlSession.insert("user.insertUser", user);
System.out.println(user);//得到了插入的这条数据的id
//User [id=29, username=张三1111, sex=1, birthday=Wed Aug 15 16:38:25 CST 2018, address=湖北]
//提交事务
sqlSession.commit();
sqlSession.close();
}
添加用户
useGeneratedKeys(主键返回)--------select UUID()
设置在插入前就自动生成uuid,这个可以用selectKey标签,也可以用useGeneratedKeys,类似上面
<insert id="insertUserUUID" parameterType="pojo.User" >
<selectKey keyProperty="uuid2" resultType="string" order="BEFORE" >
select UUID()
</selectKey>
insert into `mybatis`.`user` (
`username`,
`birthday`,
`sex`,
`address`,
`uuid2`
)
values
(
#{username},
#{birthday},
#{sex},
#{address},
#{uuid2}
);
</insert>
@Test
public void TestInsertUserUUID(){
SqlSession sqlSession = SqlSessionFactoryUtil.getSqlSessionFactory().openSession();//如果这里传参为true,就表示自动提交事务
User user = new User("张三","1",new Date(),"湖北");
sqlSession.insert("user.insertUserUUID", user);
System.out.println(user);//得到了插入的这条数据的uuid
//User [id=null, username=张三, sex=1, birthday=Wed Aug 16 16:38:25 CST 2018, address=湖北 19BD-ED6B-C4D6-45FB-BC4C-7884-29B7-21F9]
//提交事务
sqlSession.commit();
sqlSession.close();
}
dao开发方式
比如根据id查询用户信息
原始dao开发方式
(user.xml和SqlMapConfig.xml中配置如上)
创建一个userDao接口
public interface UserDao {
/**根据用户ID查询用户信息
* @param id
* @return
*/
User getUserById(Integer id);
}
创建一个接口的实现类
public class UserDaoImpl implements UserDao {
@Override
public User getUserById(Integer id) {
SqlSession sqlSession = SqlSessionFactoryUtils.getSqlSessionFactory().openSession();
User user = sqlSession.selectOne("user.getUserById", id);
sqlSession.close();
return user;
}
}
测试
public class UserDaoTest {
@Test
public void testGetUserById() {
UserDao userDao = new UserDaoImpl();
User user = userDao.getUserById(30);
System.out.println(user);
}
动态代理方式
动态代理开发规则:
1.namespace必须是接口的全路径名
2.接口的方法名必须与sql的id一致
3.接口的入参必须与parameterType类型一致
4.接口的返回值必须与resultType类型一致
创建UserMapper接口
public interface UserMapper {
/**根据用户ID查询用户信息
* @param id
* @return
*/
User getUserById(Integer id);
}
创建一个UserMapper.xml映射文件(要在核心配置文件中配置UserMapper.xml)
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
动态代理开发规则:
1.namespace必须是接口的全路径名
2.接口的方法名必须与sql的id一致
3.接口的入参必须与parameterType类型一致
4.接口的返回值必须与resultType类型一致
-->
<mapper namespace="mapper.UserMapper">
<select id="getUserById" parameterType="int" resultType="pojo.User">
SELECT
`id`,
`username`,
`birthday`,
`sex`,
`address`
FROM
`mybatis`.`user`
where id = #{id}
</select>
</mapper>
测试
public class UserMapperTest {
@Test
public void testGetUserById() {
// 加载配置得到SqlSession
SqlSession sqlSession = SqlSessionFactoryUtils.getSqlSessionFactory().openSession();
// 获取代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// 查询数据
User user = userMapper.getUserById(30);
System.out.println(user);
// 关闭资源
sqlSession.close();
}
}
SqlMapConfig.xml
<!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">
<!-- 使用jdbc事务管理 -->
<transactionManager type="JDBC" />
<!-- 数据库连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql:///mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mybatis/UserMapper.xml"/>
</mappers>
<configuration>
由于是dtd约束,所以标签的顺序必须与Content Model一致
properties
比如上面配置数据库连接池时数据库相关的数据
可以用properties标签引入外部的jdbc.properties文件
<properties resource="jdbc.properties">
<!-- 先加载内部标签内容,再加载外部文件,所以即使这里配置的name错误,使用的外部的配置文件里配置的name,只要配置文件中没配错就不影响 -->
<property name="jdbc.username" value="root1111"/>
</properties>
引入外部配置文件后,配置数据库连接池时数据库相关的数据就可以改成(value为${配置文件中的键名})
<!-- 数据库连接池 -->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClass}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
typeAliases
别名的配置
别名 | 映射的类型 |
---|---|
_byte | byte |
_long | long |
_short | short |
_int | int |
_integer | int |
_double | double |
_float | float |
_boolean | boolean |
string | String |
byte | Byte |
long | Long |
short | Short |
int | Integer |
double | Double |
float | Float |
boolean | Boolean |
date | Date |
decimal | BigDecimal |
blgDecimal | BigDecimal |
map | Map |
<!-- 别名 -->
<typeAliases>
<!-- 单个别名定义,别名使用不区分大小写,这里配的是user,使用时也可以用UsEr -->
<!-- <typeAlias type="pojo.User" alias="user"/> -->
<!-- 别名包扫描器:别名是这个包中的类的全称,不区分大小写 ,推荐方式(不用一个个去配)-->
<package name="pojo"/>
</typeAliases>
mappers
映射文件的加载
传统dao的开发方式配置映射文件(如上)
<mappers>
<mapper resource="mybatis/UserMapper.xml"/>
</mappers>
类扫描
比如上面测试动态代理方式开发dao
UserMapper和UserMapper.xml两个文件必须都在mapper包下
<mappers>
<!--
映射文件:
class扫描器:
1.接口文件必须与映射文件同一目录下
2.接口文件名称必须与映射文件名称相同
-->
<mapper class="mapper.UserMapper"/>
</mappers>
包扫描
<mappers>
<!--
映射文件 :
package扫描器(推荐):
1.接口文件必须与映射文件同一目录下
2.接口文件名称必须与映射文件名称相同
-->
<package name="mapper"/>
</mappers>
ResultMap
比如要获取数据库中的订单列表
pojo类:
public class Order {
private Integer id;
private Integer userId;
private String number;
private Date createtime;
private String note;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number == null ? null : number.trim();
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note == null ? null : note.trim();
}
@Override
public String toString() {
return "Order [id=" + id + ", userId=" + userId + ", number=" + number + ", createtime=" + createtime
+ ", note=" + note + "]";
}
}
数据库的order表
order类中用户ID为userId,而数据库中用户ID字段为user_id
所以执行以下操作后,查出来的用户ID为null
public interface OrderMapper {
/**
* 获取用户订单列表
* @return
*/
List<Order> getOrderList();
}
<?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="mapper.OrderMapper">
<select id="getOrderList" resultType="pojo.Order">
SELECT
`id`,
`user_id`,
`number`,
`createtime`,
`note`
FROM `order`
</select>
</mapper>
@Test
public void testGetOrderList() {
SqlSession sqlSession = SqlSessionFactoryUtils.getSqlSessionFactory().openSession();
//获取OrderMapper的代理实现
OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class);
List<Order> list = orderMapper.getOrderList();
for (Order order : list) {
System.out.println(order);
}
sqlSession.close();
}
解决办法:
OrderMapper.xml中的sql语句中给用户ID配置别名
<?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="mapper.OrderMapper">
<select id="getOrderList" resultType="pojo.Order">
SELECT
`id`,
`user_id` userId,
`number`,
`createtime`,
`note`
FROM `order`
</select>
</mapper>
使用ResultMap
<?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="mapper.OrderMapper">
<resultMap type="pojo.Order" id="order_list_map">
<!-- <id>用于映射主键 -->
<id property="id" column="id"/>
<!-- 普通字段用<result>映射 -->
<result property="userId" column="user_id"/>
<result property="number" column="number"/>
<result property="createtime" column="createtime"/>
<result property="note" column="note"/>
</resultMap>
<!-- 使用resultMap -->
<select id="getOrderListMap" resultMap="order_list_map">
SELECT
`id`,
`user_id`,
`number`,
`createtime`,
`note`
FROM `order`
</select>
</mapper>
@Test
public void testGetOrderListMap() {
SqlSession sqlSession = SqlSessionFactoryUtils.getSqlSessionFactory().openSession();
//获取OrderMapper的代理实现
OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class);
List<Order> list = orderMapper.getOrderListMap();
for (Order order : list) {
System.out.println(order);
}
sqlSession.close();
}
动态sql
if,where标签
<select id="getUserByPojo" parameterType="pojo.User" resultType="pojo.User">
SELECT
`id`,
`username`,
`birthday`,
`sex`,
`address`
FROM
`mybatis`.`user`
<!--if标签
where 1= 1
<if test="username != null and username != ''">
and username like '%${username}%'
</if>
<if test="sex != null and sex != ''">
and sex = #{sex}
</if>
-->
<!-- where标签自动补上where关键字,同时处理多余的and,用了where标签就不能再手动加上where关键字
<where>
<if test="username != null and username != ''">
and username like '%${username}%'
</if>
<if test="sex != null and sex != ''">
and sex = #{sex}
</if>
</where>
-->
</select>
sql片段
<!-- sql片段的抽取 -->
<sql id="user_sql">
`id`,
`username`,
`birthday`,
`sex`,
`address`
</sql>
foreach标签
比如数据库中有id从1到40的user的记录,但需求是得到id为1,25,29,30,35的用户,可以使用foreach标签
public class QueryVo {
private User user;
private List<Integer> ids;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<Integer> getIds() {
return ids;
}
public void setIds(List<Integer> ids) {
this.ids = ids;
}
}
完整的sql语句为
SELECT
`id`,
`username`,
`birthday`,
`sex`,
`address`
FROM `mybatis`.`user`
WHERE id IN(1,25,29,30,35)
<select id="getUserByIds" parameterType="pojo.QueryVo" resultType="pojo.User">
SELECT
<include refid="user_sql"/>
FROM
`mybatis`.`user`
<where>
<!--
foreach循环标签:
collection:要遍历的集合
open:循环开始之前输出的内容
item:循环变量
separator:分隔符
close:循环结束后输出的内容
-->
<foreach collection="ids" open="id IN (" item="uId" separator="," close=")">
#{uId}
</foreach>
</where>
</select>
@Test
public void testGetUserByIds(){
SqlSession sqlSession = SqlSessionFactoryUtil.getSqlSessionFactory().openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
QueryVo queryVo = new QueryVo();
queryVo.setIds(Arrays.asList(1,25,29,30,35));
List<User> users = userMapper.getUserByIds(queryVo);
for (User user2 : users) {
System.out.println(user2);
}
sqlSession.close();
}
一对一关联查询
resultType
查询订单,关联用户
public class Order {
private Integer id;
private Integer userId;
private String number;
private Date createtime;
private String note;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number == null ? null : number.trim();
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note == null ? null : note.trim();
}
@Override
public String toString() {
return "Order [id=" + id + ", userId=" + userId + ", number=" + number + ", createtime=" + createtime
+ ", note=" + note + " + "]";
}
}
public class OrderUser extends Order {
private String username;
private String adress;
public OrderUser() {
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
@Override
public String toString() {
return "OrderUser [username=" + username + ", adress=" + adress + ", getId()=" + getId() + ", getUserId()="
+ getUserId() + ", getNumber()=" + getNumber() + ", getCreatetime()=" + getCreatetime() + ", getNote()="
+ getNote() + ", toString()=" + super.toString() + ", getClass()=" + getClass() + ", hashCode()="
+ hashCode() + "]";
}
}
<select id="getOrderUser" resultType="pojo.OrderUser">
SELECT
o.`id`,
o.`user_id`,
o.`number`,
o.`createtime`,
o.`note`,
u.username,
u.address
FROM
mybatis.`order` o
LEFT JOIN mybatis.`user` u
ON u.`id` = o.`user_id`;
</select>
public interface OrderMapper {
List<OrderUser> getOrderUser();
}
@Test
public void testGetOrderUser() {
SqlSession sqlSession = SqlSessionFactoryUtils.getSqlSessionFactory().openSession();
OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class);
List<OrderUser> list = orderMapper.getOrderUser();
for (OrderUser orderUser : list) {
System.out.println(orderUser);
}
sqlSession.close();
}
resultMap
使用关联查询时,比如Order类中有四个属性,即使只有一个属性类中和表中名称不相同,其他属性也都要配置
这里Order类中要加上User属性
<resultMap type="pojo.Order" id="order_user_map">
<!-- <id>用于映射主键 -->
<id property="id" column="id"/>
<!-- 普通字段用<result>映射 -->
<result property="userId" column="user_id"/>
<result property="number" column="number"/>
<result property="createtime" column="createtime"/>
<result property="note" column="note"/>
<!-- association用于配置一对一关系
property:order里面的User属性
javaType:user的数据类型,支持别名
-->
<association property="user" javaType="pojo.User">
<id property="id" column="user_id"/>
<result property="username" column="username"/>
<result property="address" column="address"/>
<result property="birthday" column="birthday"/>
<result property="sex" column="sex"/>
</association>
</resultMap>
<!-- 一对一关联查询:resultMap使用 -->
<select id="getOrderUserMap" resultMap="order_user_map">
SELECT
o.`id`,
o.`user_id`,
o.`number`,
o.`createtime`,
o.`note`,
u.username,
u.address,
u.birthday,
u.sex
FROM
`order` o
LEFT JOIN `user` u
ON u.id = o.user_id
</select>
一对多关联查询
查询用户,关联订单,一个用户有多个订单
用户类中有订单的集合
public class User {
private Integer id;
private String username;
private String sex;
private Date birthday;
private String address;
private String uuid2;
private List<Order> orders;
public User(String username, String sex, Date birthday, String address) {
this.username = username;
this.sex = sex;
this.birthday = birthday;
this.address = address;
}
public User() {
}
public List<Order> getOrders() {
return orders;
}
public void setOrders(List<Order> orders) {
this.orders = orders;
}
public String getUuid2() {
return uuid2;
}
public void setUuid2(String uuid2) {
this.uuid2 = uuid2;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday + ", address="
+ address + ", uuid2=" + uuid2 + ", orders=" + orders + "]";
}
}
<resultMap type="pojo.User" id="user_order_map">
<id property="id" column="id"/>
<result property="username" column="username"/>
<result property="address" column="address"/>
<result property="sex" column="sex"/>
<result property="birthday" column="birthday"/>
<!--
collection配置一对多
prorty:User中的orders属性
ofType:由于orders是多的一方,那么ofType对应orders的元素的类型
-->
<collection property="orders" ofType="pojo.Order">
<!-- id用于映射主键 -->
<id property="id" column="oid"/>
<!-- 普通字段用<result>映射 -->
<result property="userId" column="id" />
<result property="number" column="number" />
<result property="createtime" column="createtime" />
<result property="note" column="note" />
</collection>
</resultMap>
<select id="getUserOrderMap" resultMap="user_order_map">
SELECT
u.`id`,
u.`uuid2`,
u.`username`,
u.`address`,
u.`sex`,
u.`birthday`,
o.`id` oid,
o.`user_id`,
o.`number`,
o.`createtime`,
o.`note`
FROM
mybatis.`user` u
LEFT JOIN mybatis.`order` o
ON u.`id` = o.`user_id`;
</select>
public interface UserMapper {
List<User> getUserOrderMap();
}
@Test
public void testGetUserOrderMap(){
SqlSession sqlSession = SqlSessionFactoryUtil.getSqlSessionFactory().openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> users = userMapper.getUserOrderMap();
for (User user2 : users) {
System.out.println(user2);
}
sqlSession.close();
}