Hibernate中联合主键映射时有一个也是外键的一种解决方法

一个联合主键的问题,困扰了我很久,最后发现《Hibernate in Action》里有讲到,因为在实际环境中老是报错,也不知配置的对不对,然后回家写了一个DEMO,发现可以保存。
表结构大致如下:
ITEM(ID,NAME)其中id是PK
CATEGORY(ID,NAME),其中ID是PK
CATEGORY_ITEM(ITEM_ID,CATEGORY_ID,THIRD_ID,ADDED_DATE),其中ITEM_ID,CATEGORY_ID分别是ITEM和CATEGORY的外键,而他们与THIRD_ID一起组成CATETORY_ITEM表的联合主键。
下面给出具体实现:
一、Item.java
Java代码 复制代码 收藏代码
  1. /**
  2. * @author Terrence
  3. *
  4. */ 
  5. public class Item implements Serializable { 
  6.  
  7.     /**
  8.      *
  9.      */ 
  10.     private static final long serialVersionUID = 1L; 
  11.     private Integer id; 
  12.     private String name; 
  13.     private Set<CategorizedItem> categorizedItems = new HashSet<CategorizedItem>(); 
  14.     /**
  15.      *
  16.      */ 
  17.     public Item() { 
  18.         super(); 
  19.     } 
  20.     /**
  21.      * @return the id
  22.      */ 
  23.     public Integer getId() { 
  24.         return id; 
  25.     } 
  26.     /**
  27.      * @param id the id to set
  28.      */ 
  29.     public void setId(Integer id) { 
  30.         this.id = id; 
  31.     } 
  32.     /**
  33.      * @return the name
  34.      */ 
  35.     public String getName() { 
  36.         return name; 
  37.     } 
  38.     /**
  39.      * @param name the name to set
  40.      */ 
  41.     public void setName(String name) { 
  42.         this.name = name; 
  43.     } 
  44.     /**
  45.      * @return the categorizedItems
  46.      */ 
  47.     public Set<CategorizedItem> getCategorizedItems() { 
  48.         return categorizedItems; 
  49.     } 
  50.     /**
  51.      * @param categorizedItems the categorizedItems to set
  52.      */ 
  53.     public void setCategorizedItems(Set<CategorizedItem> categorizedItems) { 
  54.         this.categorizedItems = categorizedItems; 
  55.     } 
  56.      
  57.      
/**
 * @author Terrence
 *
 */
public class Item implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Integer id;
	private String name;
	private Set<CategorizedItem> categorizedItems = new HashSet<CategorizedItem>();
	/**
	 * 
	 */
	public Item() {
		super();
	}
	/**
	 * @return the id
	 */
	public Integer getId() {
		return id;
	}
	/**
	 * @param id the id to set
	 */
	public void setId(Integer id) {
		this.id = id;
	}
	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}
	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}
	/**
	 * @return the categorizedItems
	 */
	public Set<CategorizedItem> getCategorizedItems() {
		return categorizedItems;
	}
	/**
	 * @param categorizedItems the categorizedItems to set
	 */
	public void setCategorizedItems(Set<CategorizedItem> categorizedItems) {
		this.categorizedItems = categorizedItems;
	}
	
	
}

二、Category.java
Java代码 复制代码 收藏代码
  1. /**
  2. * @author Terrence
  3. *
  4. */ 
  5. public class Category implements Serializable { 
  6.  
  7.     /**
  8.      *
  9.      */ 
  10.     private static final long serialVersionUID = 1L; 
  11.     private Integer id; 
  12.     private String name; 
  13.     private Set<CategorizedItem> categorizedItems = new HashSet<CategorizedItem>(); 
  14.      
  15.     public Category() { 
  16.         super(); 
  17.     } 
  18.     /**
  19.      * @return the id
  20.      */ 
  21.     public Integer getId() { 
  22.         return id; 
  23.     } 
  24.     /**
  25.      * @param id the id to set
  26.      */ 
  27.     public void setId(Integer id) { 
  28.         this.id = id; 
  29.     } 
  30.     /**
  31.      * @return the name
  32.      */ 
  33.     public String getName() { 
  34.         return name; 
  35.     } 
  36.     /**
  37.      * @param name the name to set
  38.      */ 
  39.     public void setName(String name) { 
  40.         this.name = name; 
  41.     } 
  42.     /**
  43.      * @return the categorizedItems
  44.      */ 
  45.     public Set<CategorizedItem> getCategorizedItems() { 
  46.         return categorizedItems; 
  47.     } 
  48.     /**
  49.      * @param categorizedItems the categorizedItems to set
  50.      */ 
  51.     public void setCategorizedItems(Set<CategorizedItem> categorizedItems) { 
  52.         this.categorizedItems = categorizedItems; 
  53.     } 
  54.      
  55.      
/**
 * @author Terrence
 *
 */
public class Category implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Integer id;
	private String name;
	private Set<CategorizedItem> categorizedItems = new HashSet<CategorizedItem>();
	
	public Category() {
		super();
	}
	/**
	 * @return the id
	 */
	public Integer getId() {
		return id;
	}
	/**
	 * @param id the id to set
	 */
	public void setId(Integer id) {
		this.id = id;
	}
	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}
	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}
	/**
	 * @return the categorizedItems
	 */
	public Set<CategorizedItem> getCategorizedItems() {
		return categorizedItems;
	}
	/**
	 * @param categorizedItems the categorizedItems to set
	 */
	public void setCategorizedItems(Set<CategorizedItem> categorizedItems) {
		this.categorizedItems = categorizedItems;
	}
	
	
}

三、CategorizedItem.java
Java代码 复制代码 收藏代码
  1. /**
  2. * @author Terrence
  3. *
  4. */ 
  5. public class CategorizedItem implements Serializable { 
  6.      
  7.     /**
  8.      *
  9.      */ 
  10.     private static final long serialVersionUID = 1L; 
  11.     public static class Id implements Serializable { 
  12.  
  13.         /**
  14.          *
  15.          */ 
  16.         private static final long serialVersionUID = 1L; 
  17.         private Integer thirdId; 
  18.         private Integer categoryId; 
  19.         private Integer itemId; 
  20.         /**
  21.          *
  22.          */ 
  23.         public Id() { 
  24.             super(); 
  25.         } 
  26.          
  27.         /**
  28.          * @return the thirdId
  29.          */ 
  30.         public Integer getThirdId() { 
  31.             return thirdId; 
  32.         } 
  33.  
  34.         /**
  35.          * @param thirdId the thirdId to set
  36.          */ 
  37.         public void setThirdId(Integer thirdId) { 
  38.             this.thirdId = thirdId; 
  39.         } 
  40.  
  41.         /**
  42.          * @return the categoryId
  43.          */ 
  44.         public Integer getCategoryId() { 
  45.             return categoryId; 
  46.         } 
  47.         /**
  48.          * @param categoryId the categoryId to set
  49.          */ 
  50.         public void setCategoryId(Integer categoryId) { 
  51.             this.categoryId = categoryId; 
  52.         } 
  53.         /**
  54.          * @return the itemId
  55.          */ 
  56.         public Integer getItemId() { 
  57.             return itemId; 
  58.         } 
  59.         /**
  60.          * @param itemId the itemId to set
  61.          */ 
  62.         public void setItemId(Integer itemId) { 
  63.             this.itemId = itemId; 
  64.         } 
  65.         /* (non-Javadoc)
  66.          * @see java.lang.Object#hashCode()
  67.          */ 
  68.         @Override 
  69.         public int hashCode() { 
  70.             return this.categoryId.hashCode()+this.itemId.hashCode(); 
  71.         } 
  72.         /* (non-Javadoc)
  73.          * @see java.lang.Object#equals(java.lang.Object)
  74.          */ 
  75.         @Override 
  76.         public boolean equals(Object obj) { 
  77.             if(obj!=null&&obj instanceof Id){ 
  78.                 Id that = (Id)obj; 
  79.                 return this.categoryId.equals(that.categoryId)&&this.itemId.equals(that.itemId); 
  80.             }else
  81.                 return false
  82.             } 
  83.         } 
  84.          
  85.     } 
  86.      
  87.     private Id id = new Id(); 
  88.     private Date dateAdded; 
  89.     private Item item; 
  90.     private Category category; 
  91.     /**
  92.      *
  93.      */ 
  94.     public CategorizedItem() { 
  95.         super(); 
  96.     } 
  97.     /**
  98.      * @return the id
  99.      */ 
  100.     public Id getId() { 
  101.         return id; 
  102.     } 
  103.     /**
  104.      * @param id the id to set
  105.      */ 
  106.     public void setId(Id id) { 
  107.         this.id = id; 
  108.     } 
  109.     /**
  110.      * @return the dateAdded
  111.      */ 
  112.     public Date getDateAdded() { 
  113.         return dateAdded; 
  114.     } 
  115.     /**
  116.      * @param dateAdded the dateAdded to set
  117.      */ 
  118.     public void setDateAdded(Date dateAdded) { 
  119.         this.dateAdded = dateAdded; 
  120.     } 
  121.     /**
  122.      * @return the item
  123.      */ 
  124.     public Item getItem() { 
  125.         return item; 
  126.     } 
  127.     /**
  128.      * @param item the item to set
  129.      */ 
  130.     public void setItem(Item item) { 
  131.         this.item = item; 
  132.         this.id.itemId = item.getId(); 
  133.         item.getCategorizedItems().add(this); 
  134.     } 
  135.     /**
  136.      * @return the category
  137.      */ 
  138.     public Category getCategory() { 
  139.         return category; 
  140.     } 
  141.     /**
  142.      * @param category the category to set
  143.      */ 
  144.     public void setCategory(Category category) { 
  145.         this.category = category; 
  146.         this.id.categoryId = category.getId(); 
  147.         category.getCategorizedItems().add(this); 
  148.     } 
  149.     /**
  150.      * @return the thirdId
  151.      */ 
  152.     public Integer getThirdId() { 
  153.         return this.id.getThirdId(); 
  154.     } 
  155.  
  156.     /**
  157.      * @param thirdId the thirdId to set
  158.      */ 
  159.     public void setThirdId(Integer thirdId) { 
  160.         this.id.thirdId = thirdId; 
  161.     } 
  162.      
/**
 * @author Terrence
 *
 */
public class CategorizedItem implements Serializable {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public static class Id implements Serializable {

		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		private Integer thirdId;
		private Integer categoryId;
		private Integer itemId;
		/**
		 * 
		 */
		public Id() {
			super();
		}
		
		/**
		 * @return the thirdId
		 */
		public Integer getThirdId() {
			return thirdId;
		}

		/**
		 * @param thirdId the thirdId to set
		 */
		public void setThirdId(Integer thirdId) {
			this.thirdId = thirdId;
		}

		/**
		 * @return the categoryId
		 */
		public Integer getCategoryId() {
			return categoryId;
		}
		/**
		 * @param categoryId the categoryId to set
		 */
		public void setCategoryId(Integer categoryId) {
			this.categoryId = categoryId;
		}
		/**
		 * @return the itemId
		 */
		public Integer getItemId() {
			return itemId;
		}
		/**
		 * @param itemId the itemId to set
		 */
		public void setItemId(Integer itemId) {
			this.itemId = itemId;
		}
		/* (non-Javadoc)
		 * @see java.lang.Object#hashCode()
		 */
		@Override
		public int hashCode() {
			return this.categoryId.hashCode()+this.itemId.hashCode();
		}
		/* (non-Javadoc)
		 * @see java.lang.Object#equals(java.lang.Object)
		 */
		@Override
		public boolean equals(Object obj) {
			if(obj!=null&&obj instanceof Id){
				Id that = (Id)obj;
				return this.categoryId.equals(that.categoryId)&&this.itemId.equals(that.itemId);
			}else{
				return false;
			}
		}
		
	}
	
	private Id id = new Id();
	private Date dateAdded;
	private Item item;
	private Category category;
	/**
	 * 
	 */
	public CategorizedItem() {
		super();
	}
	/**
	 * @return the id
	 */
	public Id getId() {
		return id;
	}
	/**
	 * @param id the id to set
	 */
	public void setId(Id id) {
		this.id = id;
	}
	/**
	 * @return the dateAdded
	 */
	public Date getDateAdded() {
		return dateAdded;
	}
	/**
	 * @param dateAdded the dateAdded to set
	 */
	public void setDateAdded(Date dateAdded) {
		this.dateAdded = dateAdded;
	}
	/**
	 * @return the item
	 */
	public Item getItem() {
		return item;
	}
	/**
	 * @param item the item to set
	 */
	public void setItem(Item item) {
		this.item = item;
		this.id.itemId = item.getId();
		item.getCategorizedItems().add(this);
	}
	/**
	 * @return the category
	 */
	public Category getCategory() {
		return category;
	}
	/**
	 * @param category the category to set
	 */
	public void setCategory(Category category) {
		this.category = category;
		this.id.categoryId = category.getId();
		category.getCategorizedItems().add(this);
	}
	/**
	 * @return the thirdId
	 */
	public Integer getThirdId() {
		return this.id.getThirdId();
	}

	/**
	 * @param thirdId the thirdId to set
	 */
	public void setThirdId(Integer thirdId) {
		this.id.thirdId = thirdId;
	}
	
}

四、*.hbm.xml,这里节省时间空间写在了一起
Java代码 复制代码 收藏代码
  1. <hibernate-mapping package="org.terrence.hrsystem.model"
  2.     <class name="Item" table="ITEM"
  3.       <id name="id" type="integer" column="ITEM_ID"
  4.          <generator class="identity" /> 
  5.       </id> 
  6.       <property name="name" type="string" not-null="true" 
  7.          update="false" column="ITEM_NAME" /> 
  8.       <set name="categorizedItems" cascade="all, delete-orphan" 
  9.          inverse="true" lazy="false"
  10.          <key column="ITEM_ID" not-null="true" /> 
  11.          <one-to-many class="CategorizedItem" /> 
  12.       </set> 
  13.    </class
  14.  
  15. <class name="Category" table="CATEGORY"
  16.       <id name="id" type="integer" column="CATEGORY_ID"
  17.          <generator class="identity" /> 
  18.       </id> 
  19.       <property name="name" type="string" column="CATEGORY_NAME" not-null="true"/> 
  20.       <set name="categorizedItems" cascade="all, delete-orphan" 
  21.          inverse="true" lazy="false"
  22.          <key column="CATEGORY_ID" not-null="true" /> 
  23.          <one-to-many class="CategorizedItem" /> 
  24.       </set> 
  25.    </class
  26.  
  27. <class name="Category" table="CATEGORY"
  28.       <id name="id" type="integer" column="CATEGORY_ID"
  29.          <generator class="identity" /> 
  30.       </id> 
  31.       <class name="CategorizedItem" table="CATEGORIZED_ITEM" mutable="false"
  32.     <composite-id name="id" class="CategorizedItem$Id"
  33.     <key-property name="thirdId" column="THIRD_ID" type="integer"/> 
  34.     <key-property name="categoryId" column="CATEGORY_ID" 
  35.                 type="integer" /> 
  36.     <key-property name="itemId" column="ITEM_ID" type="integer" /> 
  37.     </composite-id> 
  38.     <property name="dateAdded" column="ADDED_ON" type="timestamp" 
  39.             not-null="true" /> 
  40.  
  41.     <many-to-one name="item" class="Item" column="ITEM_ID" 
  42.             not-null="true" insert="false" update="false" /> 
  43.     <many-to-one name="category" class="Category" column="CATEGORY_ID" 
  44.             not-null="true" insert="false" update="false" /> 
  45.     </class
  46. </hibernate-mapping> 
<hibernate-mapping package="org.terrence.hrsystem.model">
	<class name="Item" table="ITEM">
      <id name="id" type="integer" column="ITEM_ID">
         <generator class="identity" />
      </id>
      <property name="name" type="string" not-null="true"
         update="false" column="ITEM_NAME" />
      <set name="categorizedItems" cascade="all, delete-orphan"
         inverse="true" lazy="false">
         <key column="ITEM_ID" not-null="true" />
         <one-to-many class="CategorizedItem" />
      </set>
   </class>

<class name="Category" table="CATEGORY">
      <id name="id" type="integer" column="CATEGORY_ID">
         <generator class="identity" />
      </id>
      <property name="name" type="string" column="CATEGORY_NAME" not-null="true"/>
      <set name="categorizedItems" cascade="all, delete-orphan"
         inverse="true" lazy="false">
         <key column="CATEGORY_ID" not-null="true" />
         <one-to-many class="CategorizedItem" />
      </set>
   </class>

<class name="Category" table="CATEGORY">
      <id name="id" type="integer" column="CATEGORY_ID">
         <generator class="identity" />
      </id>
      <class name="CategorizedItem" table="CATEGORIZED_ITEM" mutable="false">
	<composite-id name="id" class="CategorizedItem$Id">
	<key-property name="thirdId" column="THIRD_ID" type="integer"/>
	<key-property name="categoryId" column="CATEGORY_ID"
				type="integer" />
	<key-property name="itemId" column="ITEM_ID" type="integer" />
	</composite-id>
	<property name="dateAdded" column="ADDED_ON" type="timestamp"
			not-null="true" />

	<many-to-one name="item" class="Item" column="ITEM_ID"
			not-null="true" insert="false" update="false" />
	<many-to-one name="category" class="Category" column="CATEGORY_ID"
			not-null="true" insert="false" update="false" />
	</class>
</hibernate-mapping>


五、测试代码
Java代码 复制代码 收藏代码
  1. /**  
  2. * @Title: TestDao.java
  3. * @Package test
  4. * @Description: TODO(用一句话描述该文件做什么)
  5. * @author Terrence.zhung chguxing@163.com  
  6. * @date 2011-3-29 上午02:45:05
  7. * @version V1.0  
  8. */  
  9.  
  10. package test; 
  11.  
  12. import org.springframework.context.ApplicationContext; 
  13. import org.springframework.context.support.ClassPathXmlApplicationContext; 
  14. import org.terrence.hrsystem.dao.CategorizedItemDao; 
  15. import org.terrence.hrsystem.dao.CategoryDao; 
  16. import org.terrence.hrsystem.dao.ItemDao; 
  17. import org.terrence.hrsystem.model.CategorizedItem; 
  18. import org.terrence.hrsystem.model.Category; 
  19. import org.terrence.hrsystem.model.Item; 
  20.  
  21. /**
  22. * @author Terrence
  23. *
  24. */ 
  25. public class TestDao { 
  26.  
  27.     /**
  28.      * @param args
  29.      */ 
  30.     private static ItemDao itemDao; 
  31.     private static CategoryDao categoryDao; 
  32.     private static CategorizedItemDao  categorizedItemDao; 
  33.     private static ApplicationContext ctx; 
  34.      
  35.     public static void init(){ 
  36.         if(ctx==null){ 
  37.             ctx = new ClassPathXmlApplicationContext(new String[]{"classpath:applicationContext.xml","classpath:daoContext.xml"}); 
  38.         } 
  39.         itemDao = (ItemDao)ctx.getBean("itemDao"); 
  40.         categoryDao = (CategoryDao)ctx.getBean("categoryDao"); 
  41.         categorizedItemDao = (CategorizedItemDao)ctx.getBean("categorizedItemDao"); 
  42.     } 
  43.     public static void main(String[] args) throws Exception { 
  44.         init(); 
  45.         saveItem(); 
  46.         saveCategory(); 
  47.         saveCategoryItem(); 
  48.     } 
  49.      
  50.     public static void saveItem() throws Exception{ 
  51.         Item item = new Item(); 
  52.         item.setName("item2"); 
  53.         itemDao.save(item); 
  54.     } 
  55.      
  56.     public static void saveCategory() throws Exception{ 
  57.         Category category = new Category(); 
  58.         category.setName("category2"); 
  59.         categoryDao.save(category); 
  60.     } 
  61.      
  62.     public static void saveCategoryItem() throws Exception{ 
  63.         Item item = itemDao.get(1); 
  64.         Category category = categoryDao.get(1); 
  65.         CategorizedItem categorizedItem = new CategorizedItem(); 
  66.         categorizedItem.setItem(item); 
  67.         categorizedItem.setCategory(category); 
  68.         categorizedItem.setDateAdded(new java.util.Date()); 
  69.         categorizedItem.setThirdId(5); 
  70.         categorizedItemDao.save(categorizedItem); 
  71.     } 
  72.  
/**   
* @Title: TestDao.java 
* @Package test 
* @Description: TODO(用一句话描述该文件做什么) 
* @author Terrence.zhung chguxing@163.com   
* @date 2011-3-29 上午02:45:05 
* @version V1.0   
*/ 

package test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.terrence.hrsystem.dao.CategorizedItemDao;
import org.terrence.hrsystem.dao.CategoryDao;
import org.terrence.hrsystem.dao.ItemDao;
import org.terrence.hrsystem.model.CategorizedItem;
import org.terrence.hrsystem.model.Category;
import org.terrence.hrsystem.model.Item;

/**
 * @author Terrence
 *
 */
public class TestDao {

	/**
	 * @param args
	 */
	private static ItemDao itemDao;
	private static CategoryDao categoryDao;
	private static CategorizedItemDao  categorizedItemDao;
	private static ApplicationContext ctx;
	
	public static void init(){
		if(ctx==null){
			ctx = new ClassPathXmlApplicationContext(new String[]{"classpath:applicationContext.xml","classpath:daoContext.xml"});
		}
		itemDao = (ItemDao)ctx.getBean("itemDao");
		categoryDao = (CategoryDao)ctx.getBean("categoryDao");
		categorizedItemDao = (CategorizedItemDao)ctx.getBean("categorizedItemDao");
	}
	public static void main(String[] args) throws Exception {
		init();
		saveItem();
		saveCategory();
		saveCategoryItem();
	}
	
	public static void saveItem() throws Exception{
		Item item = new Item();
		item.setName("item2");
		itemDao.save(item);
	}
	
	public static void saveCategory() throws Exception{
		Category category = new Category();
		category.setName("category2");
		categoryDao.save(category);
	}
	
	public static void saveCategoryItem() throws Exception{
		Item item = itemDao.get(1);
		Category category = categoryDao.get(1);
		CategorizedItem categorizedItem = new CategorizedItem();
		categorizedItem.setItem(item);
		categorizedItem.setCategory(category);
		categorizedItem.setDateAdded(new java.util.Date());
		categorizedItem.setThirdId(5);
		categorizedItemDao.save(categorizedItem);
	}

}



六、说明
    因为用了spring,在配置文件配好环境,表可以用hibernate直接生成,不用写SQL语句。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值