3

I have a problem with writting a generic class for composite keys that I use in my db. All tables that are using composite key have relation ManyToOne and use 2 FK. I have written following class:

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) {
           /* */
}

}

And example class with 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 */


    }

Now the questions:
1. Is this approach correct? Or its better to write separate composite key for each entity?
2. If this approach is correct, then how can I move annonation @ManyToOne from CompositeKey class to TestClass ?
3. Is it possible to use cascade in this case? I would like to save Entities that are in composite keys when entity with composite key is saved.

Thanks in advance for Your replies!

jmac
  • 688
  • 3
  • 15

0 Answers0