Hibernate中使用Annotation实现复合主键

定义复合主键类:Override Object的equals和hasCode方法;同时实现java.io.Serializable接口。如下:
/*
 * Created on 2007-02-05
 */
package com.snow.hib.pojos;
import java.io.Serializable;
import javax.persistence.Column;
/**
 * 定义一个复合主键
 * @author snowflower
 *
 */
public class ComplexIDObject implements Serializable {
 private static final long serialVersionUID = 1L;
    private String pkA;
    private String pkB;
 /**
  * @return Returns the pkA.
  */
    @Column(name="keyA")
 public String getPkA() {
  return pkA;
 }
 /**
  * @param pkA The pkA to set.
  */
 public void setPkA(String pkA) {
  this.pkA = pkA;
 }
 /**
  * @return Returns the pkB.
  */
 @Column(name="keyB")
 public String getPkB() {
  return pkB;
 }
 /**
  * @param pkB The pkB to set.
  */
 public void setPkB(String pkB) {
  this.pkB = pkB;
 }
 
 public int hashCode() {
  int result;
  result = pkA.hashCode();
  result = 29 * result + pkB.hashCode();
  return result;
 }
 public boolean equals(Object obj) {
  if(this == obj)return true;
  if ( !( obj instanceof ComplexIDObject ) ) return false;
  
  final ComplexIDObject o = (ComplexIDObject) obj;
  if(!pkA.equals(o.getPkA()))return false;
  if(!pkB.equals(o.getPkB()))return false;
  return true;
 } 
}
下面是对上面符合主键类的使用,需要注意的和复合主键类似:
/*
 * Created on 2007-02-05
 */
package com.snow.hib.pojos;
import java.io.Serializable;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 *
 * @author snowflower
 *
 */
@Entity
@Table(name="complex_PK")
public class UseComplexIDObject implements Serializable {
 private static final long serialVersionUID = 1L;
 
    private ComplexIDObject comPk;
   
 /**
  * @return Returns the comPk.
  */
    @EmbeddedId
 public ComplexIDObject getComPk() {
  return comPk;
 }
 /**
  * @param comPk The comPk to set.
  */
 public void setComPk(ComplexIDObject comPk) {
  this.comPk = comPk;
 } 
 
 public boolean equals(Object o) {
  if ( this == o ) return true;
  if ( !( o instanceof UseComplexIDObject ) ) return false;
  final UseComplexIDObject parent = (UseComplexIDObject) o;
  if ( !comPk.equals( parent.comPk ) ) return false;
  return true;
 }
 public int hashCode() {
  return comPk.hashCode();
 }
}
下面是一段测试代码:
          UseComplexIDObject comp = new UseComplexIDObject();
          ComplexIDObject pk = new ComplexIDObject();
          pk.setPkA("0001A");
          pk.setPkB("0001B");
          comp.setComPk(pk);
          manager.saveComplexO(comp);
这样就OK了,至于Annotation已经在源文件中使用了,这里就不多说了。

你可能感兴趣的:(Hibernate)