AuthorMapper.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="com.cj.dao.AuthorDao">
<resultMap type="Author" id="auresult">
<id column="id" property="id"/>
<result column="username" property="username"/>
<!-- 配置关联对象。其中:
property属性值为当前Blog对象的关联对象名;
ofType属性值为关联对象属性所属的完全限定类名或别名;
select属性值为所请求的select映射的ID,该select使用子查询获取其所关联的属性对象;
column属性值为关联主键ID -->
<collection property="list" ofType="Blog" select="selblog" column="id"></collection>
</resultMap>
<select id="selblog" resultType="Blog" parameterType="int">
select * from blog where author_id = #{id}
</select>
<select id="listau" resultMap="auresult" parameterType="int">
select * from author where id = #{id}
</select>
</mapper>
AuthorDao
package com.cj.dao;
import com.cj.entity.Author;
public interface AuthorDao {
public Author listau(int id);
}
Author
package com.cj.entity;
import java.util.ArrayList;
import java.util.List;
public class Author {
private int id;
private String username;
private String password;
private String address;
private String phone;
private List<Blog> list = new ArrayList<Blog>();
public List<Blog> getList() {
return list;
}
public void setList(List<Blog> list) {
this.list = list;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Author() {
super();
// TODO Auto-generated constructor stub
}
public Author(int id, String username, String password, String address,
String phone) {
super();
this.id = id;
this.username = username;
this.password = password;
this.address = address;
this.phone = phone;
}
}
test测试
package com.cj.test;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.cj.dao.BlogDao;
/**
* <p>Title: Test.java</p>
* @作者: 曹大爷
* @时间:2017-2-5 上午11:40:09
*/
public class Test {
public static void main(String[] args) throws Exception {
SqlSession openSession = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("config.xml")).openSession();
BlogDao mapper = openSession.getMapper(BlogDao.class);
//查询作者所发布的博客
AuthorDao mapper2 = openSession.getMapper(AuthorDao.class);
Author listau = mapper2.listau(2);
System.out.println(listau.getUsername());
for (Blog blog : listau.getList()) {
System.out.println(blog.getTitle());
}
}
}
Mybatis关联关系配置(一对多)
原文:http://www.cnblogs.com/cj870522/p/6368171.html