mybatis collection的使用
Mybatis collection的使用
今天学习了mybatis中的collection使用,作为记录以后使用。首先看一下javabean的结构!
public class Article
{
private User user;
private String name;
private int id;
private Date time;
public class User
{
private int id;
private String name;
private List<Article> article;
用户和文章是一对多的关系!在查询用户的时候一次性直接查出用户的所有文章,虽然开发的时候一般不会使用此方法一次性查询出多的一方,但是作为学习还是有必要的!
用户配置文件为:
<?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="user">
<resultMap type="user" id="userMap">
<collection property="article" column="id" ofType="article"
select="user_selectArticle">
</collection>
</resultMap>
<select id="user_selectArticle" resultType="article" parameterType="int"
statementType="PREPARED">
select * from article
where user=#{id}
</select>
<select id="user_selectAll" resultMap="userMap" parameterType="user">
select * from user
</select>
<insert id="user_save" parameterType="user">
insert into user(name)
values(#{name})
</insert>
</mapper>
主要要注意的为ofType为集合中元素的类型,在此例子中集合类型为Article!
最后附上数据库表结构:
插入数据后查询的结果为:
@Test
public void testSelectAll()
{
User user = new User(2);
user.setName("d");
for (User u : service.findAll(user))
{
if (u.getArticle() != null)
System.out.println(u.getArticle().size());
System.out.println(u);
}
}
2
User [article=[Article [id=1, name=firstArticle, time=2013-11-3 0:00:00, user=null], Article [id=2, name=secondArticle, time=2013-11-3 0:00:00, user=null]], id=0, name=d]
0
User [article=[], id=0, name=d1]
0
User [article=[], id=0, name=d2]
0
User [article=[], id=0, name=d3]
0
User [article=[], id=0, name=testInsert]
0
User [article=[], id=0, name=testInsert]
集合数据成功查询出来!