Hibernate通用复合键和级联保存

时间:2013-11-25 14:13:13

标签: hibernate composite-key hibernate-cascade

我在为数据库中使用的复合键编写泛型类时遇到问题。 使用复合键的所有表都具有ManyToOne关系并使用2 FK。我写过以下课程:

import java.io.Serializable;

import javax.persistence.Embeddable;
import javax.persistence.ManyToOne;

@Embeddable
public class CompositeKey<K, T> implements Serializable {
@ManyToOne
K firstKey;
@ManyToOne
T secondKey;

public CompositeKey() {
}

public CompositeKey(K firstKey, T secondKey) {
    this.firstKey = firstKey;
    this.secondKey = secondKey;
}

public K getFirstKey() {
    return firstKey;
}

public void setFirstKey(K firstKey) {
    this.firstKey = firstKey;
}

public T getSecondKey() {
    return secondKey;
}

public void setSecondKey(T secondKey) {
    this.secondKey = secondKey;
}

@Override
public String toString() {
    return "CompositeKey [firstKey=" + firstKey + ", secondKey="
            + secondKey + "]";
}

@Override
public int hashCode() {
    /* HashCode implementation */
}

@Override
public boolean equals(Object obj) {
           /* */
}

}

使用CompositeKey的示例类:

import javax.persistence.AssociationOverride;
import javax.persistence.AssociationOverrides;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;



@Entity
public class TestClass {

@EmbeddedId
@AssociationOverrides({
        @AssociationOverride(name = "firstKey", joinColumns = @JoinColumn(name = "FirstTable")),
        @AssociationOverride(name = "secondKey", joinColumns = @JoinColumn(name = "SecondTable")) })
private CompositeKey<A, B> compositeKey;

@Lob
private String description;

    /* Getters and Setters */


    }

现在问题:
这种方法是否正确?或者更好地为每个实体编写单独的复合密钥?
2.如果这种方法是正确的,那么我如何将复合@ManyToOne从CompositeKey类移到TestClass?
3.在这种情况下是否可以使用级联?我希望在保存具有复合键的实体时保存复合键中的实体。

提前感谢您的回复!

0 个答案:

没有答案