首页 > 代码库 > ibatis实战之一对多关联

ibatis实战之一对多关联

在实际开发中,我们常常遇到关联数据的情况,如User对象拥有若干Book对象

每个Book对象描述了归属于一个User信息,这种情况下,我们应该如何处理?

通过单独的Statement操作固然可以实现(通过Statement用于读取用户数据,再手工调用另外一个Statement

根据用户ID返回对应的book信息).不过这样未免失之繁琐.下面我们就看看在ibatis中,如何对关联数据进行操。

ibatis中,提供了Statement嵌套支持,通过Statement嵌套,我们即可实现关联数据的操作。

如下步骤演示一对多关联

1、创建user(id,name,age)表和book(id,name,uid)表

2、POJO类

public class User implements Serializable {

	private static final long serialVersionUID = 1L;
	private int id;
	private String name;
	private int age;
	/**
	 * ibatis一对多关联
	 */
	private Set<Book> books = new HashSet<Book>();
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}

	public Set<Book> getBooks() {
		return books;
	}
	public void setBooks(Set<Book> books) {
		this.books = books;
	}
}
public class Book {
	private int id;
	private String name;
	
	public int getId() {
		return id;
	}
	
	public void setId(int id) {
		this.id = id;
	}
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
}

3、创建User.xml文件

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE sqlMap  
PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"  
"http://www.ibatis.com/dtd/sql-map-2.dtd">
<sqlMap namespace="User">
	<typeAlias alias="user" type="com.itmyhome.User" />
	<typeAlias alias="book" type="com.itmyhome.Book"/>
 	
 	<!-- 一对多查询,一个User对应多个Book -->
	<resultMap id="get_user_result" class="user">
		<result property="id" column="id"/>
		<result property="name" column="name"/>
		<result property="age" column="age"/>
		<result property="books" column="id" select="User.getBookByUserId"/>
	</resultMap>
	
	<!-- 查询主表 -->
	<select id="getUser" parameterClass="java.lang.String" resultMap="get_user_result">
		<![CDATA[
			select * from user where id = #id# 
		]]>
	</select>
	
	<!-- 查询子表 -->
	<select id="getBookByUserId" parameterClass="int" resultClass="book">
		<![CDATA[
		select *
		from book 
		where uid = #uid# 
		]]>
	</select>
	
</sqlMap>

4、SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
"http://www.ibatis.com/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
	<settings 
		cacheModelsEnabled="true" 
		enhancementEnabled="true"
		lazyLoadingEnabled="true"
		errorTracingEnabled="true"
		maxRequests="32"
		maxSessions="10"
		maxTransactions="5"
		useStatementNamespaces="true" />
	<transactionManager type="JDBC">
		<dataSource type="SIMPLE">
			<property name="JDBC.Driver" value=http://www.mamicode.com/"com.mysql.jdbc.Driver" />>以上可能需要修改ConnectionURL,Username,Password

5、MyAppSqlConfig.java

import java.io.Reader;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

public class MyAppSqlConfig {
	private static final SqlMapClient sqlMap;
	static {
		try {
			String resource = "SqlMapConfig.xml";
			Reader reader = Resources.getResourceAsReader(resource); //读取配置文件 
			sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("Error initializing MyAppSqlConfig class. Cause: " + e);
		}
	}
	public static SqlMapClient getSqlMapInstance() {
		return sqlMap;
	}
}

6、测试类

public class UserTest {
	public static void main(String[] args) {
		SqlMapClient sqlMap = MyAppSqlConfig.getSqlMapInstance();
		try {
			/**
			 * 查询ID为5的用户,以下查询假设有数据存在
			 */
			List list = sqlMap.queryForList("User.getUser","5");
			for(int i=0;i<list.size();i++){
				User user = (User)list.get(i);
				/**
				 * 得到User所拥有的Book
				 */
				Set<Book> books = (Set<Book>)user.getBooks();
				Iterator ite = books.iterator();
				while(ite.hasNext()){
					Book book = (Book)ite.next();
					System.out.println("用户:"+user.getName()+",书籍: "+book.getName());
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

这里通过在resultMap中定义嵌套查询getBookByUserId,我们实现了关联数据的读取。


项目结构图:


项目源码下载:http://download.csdn.net/detail/itmyhome/7495501


欢迎加入JAVA技术交流群:74955800