`

Hibernate集合映射

阅读更多
准备找工作,重新整理一下Hibernate,今天做了集合映射的测试,以前是使用MyEclipse自动生成,今天开始手动配置。
在手动配置的过程中还真是出了不少问题,少包,漏写这漏写那,不过还好,很快都把错误排除了。
其中这个问题记录一下:
No CurrentSessionContext configured!" 异常
之前都是getSession()或用spring整合做web,所以没有注意到单独使用hibernate时如果用SessionFactory.getCurrentSession()要配置上这个:
<property name="current_session_context_class">thread</property>
为当前Session指定一个策略。
Set集合测试
build.xml
Xml代码 复制代码
  1. <?xml version="1.0"?>  
  2. <project default="main" basedir=".">  
  3.     <property name="src" value="src"/>  
  4.     <property name="bin" value="bin"/>  
  5.     <property name="lib" value="lib"/>  
  6.     <property name="xdoclet.home" value="D:/xdoclet-plugins-1.0.3"/>  
  7.     <path id="xdoclet.task.classpath">  
  8.         <fileset dir="${xdoclet.home}/lib">  
  9.             <include name="**/*.jar"/>  
  10.         </fileset>  
  11.         <fileset dir="${xdoclet.home}/plugins">  
  12.             <include name="**/*.jar"/>  
  13.         </fileset>  
  14.     </path>  
  15.        
  16.     <taskdef    
  17.         name="xdoclet"  
  18.         classname="org.xdoclet.ant.XDocletTask"  
  19.         classpathref="xdoclet.task.classpath"  
  20.     />  
  21.     <target name="生成配置文件">  
  22.         <xdoclet>  
  23.             <fileset dir="${src}/pojo/">  
  24.                 <include name="**/*.java"/>  
  25.             </fileset>  
  26.             <component  
  27.                 classname="org.xdoclet.plugin.hibernate.HibernateConfigPlugin"  
  28.                     destdir="${src}"  
  29.                     version="3.0"  
  30.                     hbm2ddlauto="update"  
  31.                     jdbcurl="jdbc:mysql://localhost/hib"  
  32.                     jdbcdriver="com.mysql.jdbc.Driver"  
  33.                     jdbcusername="root"  
  34.                     jdbcpassword="520"  
  35.                     dialect="org.hibernate.dialect.MySQLDialect"  
  36.                     showsql="true"     
  37.             />  
  38.         </xdoclet>  
  39.     </target>    
  40.        
  41.     <target name="生成映射文件">  
  42.         <xdoclet>  
  43.             <fileset dir="${src}/pojo">  
  44.                 <include name="**/*.java"/>  
  45.             </fileset>  
  46.             <component    
  47.                 classname="org.xdoclet.plugin.hibernate.HibernateMappingPlugin"  
  48.                 version="3.0"  
  49.                 destdir="${src}"  
  50.             />  
  51.         </xdoclet>  
  52.     </target>  
  53. </project>  
<?xml version="1.0"?>
<project default="main" basedir=".">
	<property name="src" value="src"/>
    <property name="bin" value="bin"/>
	<property name="lib" value="lib"/>
	<property name="xdoclet.home" value="D:/xdoclet-plugins-1.0.3"/>
	<path id="xdoclet.task.classpath">
		<fileset dir="${xdoclet.home}/lib">
			<include name="**/*.jar"/>
		</fileset>
		<fileset dir="${xdoclet.home}/plugins">
			<include name="**/*.jar"/>
		</fileset>
	</path>
	
	<taskdef 
		name="xdoclet"
		classname="org.xdoclet.ant.XDocletTask"
		classpathref="xdoclet.task.classpath"
	/>
	<target name="生成配置文件">
		<xdoclet>
			<fileset dir="${src}/pojo/">
				<include name="**/*.java"/>
			</fileset>
			<component
				classname="org.xdoclet.plugin.hibernate.HibernateConfigPlugin"
					destdir="${src}"
					version="3.0"
					hbm2ddlauto="update"
					jdbcurl="jdbc:mysql://localhost/hib"
					jdbcdriver="com.mysql.jdbc.Driver"
					jdbcusername="root"
					jdbcpassword="520"
					dialect="org.hibernate.dialect.MySQLDialect"
					showsql="true"	
			/>
		</xdoclet>
	</target>	
	
	<target name="生成映射文件">
		<xdoclet>
			<fileset dir="${src}/pojo">
				<include name="**/*.java"/>
			</fileset>
			<component 
				classname="org.xdoclet.plugin.hibernate.HibernateMappingPlugin"
				version="3.0"
				destdir="${src}"
			/>
		</xdoclet>
	</target>
</project>

Hibernate.cfg.xml

Xml代码 复制代码
  1. <?xml version="1.0" encoding="ISO-8859-1"?>  
  2. <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
  3.   
  4. <hibernate-configuration>  
  5.   <session-factory>  
  6.     <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>  
  7.     <property name="hibernate.connection.url">jdbc:mysql://localhost/hib</property>  
  8.     <property name="hibernate.connection.username">root</property>  
  9.     <property name="hibernate.connection.password">520</property>  
  10.     <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>  
  11.     <property name="hibernate.show_sql">true</property>  
  12.     <property name="hibernate.hbm2ddl.auto">update</property>  
  13.     <property name="current_session_context_class">thread</property>  
  14.     <mapping resource="pojo/Customer.hbm.xml"/>  
  15.     <mapping resource="pojo/Img.hbm.xml"/>  
  16.   </session-factory>  
  17. </hibernate-configuration>  
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
  <session-factory>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost/hib</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">520</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <property name="current_session_context_class">thread</property>
    <mapping resource="pojo/Customer.hbm.xml"/>
    <mapping resource="pojo/Img.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

Customer.java
Java代码 复制代码
  1. package pojo;   
  2. import java.util.Date;   
  3. import java.util.HashSet;   
  4. import java.util.Set;   
  5. /**  
  6.  * @author Administrator  
  7.  *@hibernate.class  
  8.  *  table=T_Customer  
  9.  */  
  10. public class Customer {   
  11.     /**  
  12.      * @hibernate.id  
  13.      * column="cid"  
  14.      *  generator-class="native"  
  15.      */  
  16.     private int id;   
  17.     /**  
  18.      * @hibernate.property  
  19.      *  column="name"  
  20.      */  
  21.     private String name;   
  22.     /**  
  23.      * @hibernate.property  
  24.      *  column="data"  
  25.      */  
  26.     private Date data;   
  27.     /**  
  28.      * @hibernate.property  
  29.      *  column="address"  
  30.      */  
  31.     private String address;   
  32.     /**  
  33.      * @hibernate.set   
  34.      * table="T_Img"  
  35.      * @hibernate.key  
  36.      *  column="cid"  
  37.      * @hibernate.element  
  38.      * column="name"  
  39.      * type="string"  
  40.      */  
  41.     private Set img;   
  42.     }  
package pojo;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
/**
 * @author Administrator
 *@hibernate.class
 *	table=T_Customer
 */
public class Customer {
	/**
	 * @hibernate.id
	 * column="cid"
	 * 	generator-class="native"
	 */
	private int id;
	/**
	 * @hibernate.property
	 * 	column="name"
	 */
	private String name;
	/**
	 * @hibernate.property
	 *  column="data"
	 */
	private Date data;
	/**
	 * @hibernate.property
	 *  column="address"
	 */
	private String address;
	/**
	 * @hibernate.set 
	 * table="T_Img"
	 * @hibernate.key
	 *  column="cid"
	 * @hibernate.element
	 * column="name"
	 * type="string"
	 */
	private Set img;
	}

Img.java
Java代码 复制代码
  1. package pojo;   
  2. /**  
  3.  *   
  4.  * @author Administrator  
  5.  *@hibernate.class  
  6.  *  table="T_Img"  
  7.  */  
  8. public class Img {   
  9.     /**  
  10.      * @hibernate.id  
  11.      * column="img_id"  
  12.      *  generator-class="native"  
  13.      */  
  14.     private int id;   
  15.     /**  
  16.      * @hibernate.property  
  17.      *  column="name"  
  18.      */  
  19.     private String name;   
  20. }  
package pojo;
/**
 * 
 * @author Administrator
 *@hibernate.class
 *	table="T_Img"
 */
public class Img {
	/**
	 * @hibernate.id
	 * column="img_id"
	 * 	generator-class="native"
	 */
	private int id;
	/**
	 * @hibernate.property
	 * 	column="name"
	 */
	private String name;
}


//manager
Java代码 复制代码
  1. public class CustomerManagerImpl extends BaseManager implements CustomerManager {      
  2.     public void addCustomer(Customer customer) {   
  3.         Session session=getSession();   
  4.         Transaction tr = session.beginTransaction();   
  5.         session.save(customer);   
  6.         tr.commit();   
  7.         closeSession(session);   
  8.     }   
  9.     public void delCustomer(int id) {   
  10.         Session session=getSession();   
  11.         Transaction tr = session.beginTransaction();   
  12.         Customer customer=(Customer)session.load(Customer.class, id);   
  13.         session.delete(customer);   
  14.         tr.commit();   
  15.         closeSession(session);   
  16.     }   
  17. }  
public class CustomerManagerImpl extends BaseManager implements CustomerManager {	
	public void addCustomer(Customer customer) {
		Session session=getSession();
	 	Transaction tr = session.beginTransaction();
		session.save(customer);
		tr.commit();
		closeSession(session);
	}
	public void delCustomer(int id) {
		Session session=getSession();
	 	Transaction tr = session.beginTransaction();
	 	Customer customer=(Customer)session.load(Customer.class, id);
		session.delete(customer);
		tr.commit();
		closeSession(session);
	}
}

//测试类
Java代码 复制代码
  1. public class CustomerManagerImplTest extends TestCase {    
  2.     CustomerManagerImpl m=new CustomerManagerImpl();   
  3.     public void testAddCustomer() {   
  4.         Customer c=new Customer();   
  5.         c.setName("死亡骑士");   
  6.         c.setAddress("五一九路");   
  7.         c.setData(new Date());   
  8.         Set img=new HashSet();   
  9.         img.add("aaa");   
  10.         img.add("bbb");   
  11.         img.add("aaa");   
  12.         c.setImg(img);   
  13.         m.addCustomer(c);   
  14.     }   
  15.   
  16.     public void testDelCustomer() {   
  17.         m.delCustomer(2);   
  18.     }   
  19. }  
public class CustomerManagerImplTest extends TestCase {	
	CustomerManagerImpl m=new CustomerManagerImpl();
	public void testAddCustomer() {
		Customer c=new Customer();
		c.setName("死亡骑士");
		c.setAddress("五一九路");
		c.setData(new Date());
		Set img=new HashSet();
		img.add("aaa");
		img.add("bbb");
		img.add("aaa");
		c.setImg(img);
		m.addCustomer(c);
	}

	public void testDelCustomer() {
		m.delCustomer(2);
	}
}

数据库中添加aaa、bbb字段,把重复的项去了。
List映射
将Customer.java中img注释改成如下
Java代码 复制代码
  1. /**  
  2.  * @hibernate.list   
  3.  * table="T_Img"  
  4.  * @hibernate.key  
  5.  *  column="cid"  
  6.  * @hibernate.list-index  
  7.  *  column="ind"  
  8.  * @hibernate.element  
  9.  *  type="string"  
  10.  *  column="name"  
  11.  */  
  12. private List img;  
	/**
	 * @hibernate.list 
	 * table="T_Img"
	 * @hibernate.key
	 *  column="cid"
	 * @hibernate.list-index
	 * 	column="ind"
	 * @hibernate.element
	 *  type="string"
	 *  column="name"
	 */
	private List img;

在Img.java中添加一个索引字段ind
Java代码 复制代码
  1. /**  
  2.  * @hibernate.property  
  3.  * column="ind"  
  4.  */  
  5. private int ind;  
	/**
	 * @hibernate.property
	 * column="ind"
	 */
	private int ind;

OK其它都和Set一样
数据库中添加aaa、bbb、aaa字段。充许添加重复项。

Map映射
和Set差不多,只是加了一个index项作为map的key
Customer.java改动
Java代码 复制代码
  1. /**  
  2.  * @hibernate.map   
  3.  * table="T_Img"  
  4.  * @hibernate.key  
  5.  *  column="cid"  
  6.  * @hibernate.index  
  7.  *  column="imgname"  
  8.  *  type="string"  
  9.  * @hibernate.element  
  10.  *  type="int"  
  11.  *  column="size"  
  12.  */  
  13. private Map img;  
	/**
	 * @hibernate.map 
	 * table="T_Img"
	 * @hibernate.key
	 *  column="cid"
	 * @hibernate.index
	 * 	column="imgname"
	 *  type="string"
	 * @hibernate.element
	 *  type="int"
	 *  column="size"
	 */
	private Map img;

Img.java
Java代码 复制代码
  1.     /**  
  2.      * @hibernate.property  
  3.      *  column="imgname"  
  4.      */  
  5. //键   
  6.     private String imgname;   
  7.     /**  
  8.      * @hibernate.property  
  9.      * column="size"  
  10.      */  
  11. //值   
  12.     private int size;  
	/**
	 * @hibernate.property
	 * 	column="imgname"
	 */
//键
	private String imgname;
	/**
	 * @hibernate.property
	 * column="size"
	 */
//值
	private int size;

测试:
Java代码 复制代码
  1. public void testAddCustomer() {   
  2.     Customer c=new Customer();   
  3.     c.setName("李白");   
  4.     c.setAddress("五一九路");   
  5.     c.setData(new Date());   
  6.     Map img=new HashMap();   
  7.     img.put("img4",32);   
  8.     img.put("img5",123);   
  9.     img.put("img4",97);   
  10.     c.setImg(img);   
  11.     m.addCustomer(c);   
  12. }  
	public void testAddCustomer() {
		Customer c=new Customer();
		c.setName("李白");
		c.setAddress("五一九路");
		c.setData(new Date());
		Map img=new HashMap();
		img.put("img4",32);
		img.put("img5",123);
		img.put("img4",97);
		c.setImg(img);
		m.addCustomer(c);
	}

数据库同样只添加了img4、img5,去除了重复项。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics