In actual development, we often encounter associated data. For example, a User object has several Book objects.
Each Book object describes a User. In this case, what should we do?
A separate Statement operation can be used to read user data and then call another Statement manually.
Return the corresponding book information according to the user ID). However, this is not a hassle. Let's take a look at how to operate the associated data in ibatis.
Ibatis provides support for Statement nesting. With Statement nesting, we can perform associated data operations.
The following steps demonstrate one-to-Multiple Association
1. Create a user (id, name, age) table and a book (id, name, uid) Table
2. POJO class
Public class User implements Serializable {private static final long serialVersionUID = 1L; private int id; private String name; private int age; /*** ibatis one-to-Multiple Association */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. Create a User. xml file
<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE sqlMap PUBLIC "-// iBATIS.com//DTD SQL Map 2.0 //" 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 "/> <! -- One-to-multiple query, A User corresponds to multiple books --> <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> <! -- Query the master table --> <select id = "getUser" parameterClass = "java. lang. String" resultMap = "get_user_result"> <! [CDATA [select * from user where id = # id #]> </select> <! -- Query a sub-table --> <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 sqlMapConfigPUBLIC "-//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/itmyhome/User.xml" /></sqlMapConfig>
You may need to modify the ConnectionURL, Username, and 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); // read the configuration file 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. Testing
Public class UserTest {public static void main (String [] args) {SqlMapClient sqlMap = MyAppSqlConfig. getSqlMapInstance (); try {/*** query user with ID 5. The following query assumes that data exists */List list = sqlMap. queryForList ("User. getUser "," 5 "); for (int I = 0; I <list. size (); I ++) {User user User = (User) list. get (I);/*** get the Book owned by the User */Set <Book> books = (Set <Book>) user. getBooks (); Iterator ite = books. iterator (); while (ite. hasNext () {Book book = (Book) ite. next (); System. out. println ("user:" + user. getName () + ", books:" + book. getName () ;}} catch (SQLException e) {e. printStackTrace ();}}}
GetBookByUserId is defined in resultMap to read the associated data.
Project Structure:
Project source code download: http://download.csdn.net/detail/itmyhome/7495501
Welcome to the JAVA technology exchange group: 74955800