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.blog.ytso.com.User" /> 
	<typeAlias alias="book" type="com.blog.ytso.com.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="com.mysql.jdbc.Driver" /> 
			<property name="JDBC.ConnectionURL" value="jdbc:mysql://localhost:3306/ibatis" /> 
			<property name="JDBC.Username" value="root" /> 
			<property name="JDBC.Password" value="root" /> 
			<property name="Pool.MaximumActiveConnections" value="10" /> 
			<property name="Pool.MaximumIdleConnections" value="5" /> 
			<property name="Pool.MaximumCheckoutTime" value="120000" /> 
			<property name="Pool.TimeToWait" value="500" /> 
			<property name="Pool.PingQuery" value="select 1 from ACCOUNT" /> 
			<property name="Pool.PingEnabled" value="false" /> 
			<property name="Pool.PingConnectionsOlderThan" value="1" /> 
			<property name="Pool.PingConnectionsNotUsedFor" value="1" /> 
		</dataSource> 
	</transactionManager> 
	<sqlMap resource="com/blog.ytso.com/User.xml" /> 
</sqlMapConfig>

以上可能需要修改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,我们实现了关联数据的读取。


项目结构图:

ibatis实战之一对多关联详解编程语言

项目源码下载:http://download.csdn.net/detail/blog.ytso.com/7495501

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/14462.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论