I have a simple question about unit declaration in JPA. I have a unit with 2 foreign keys, which are not zero and make a unique combination. At first I was thinking about an overall key, made with two foreign keys, but I have heard that it is a heritage design, and not the recommended method of designing new tables.
So I'm interested if Hibernate / JPA can automatically generate ID based on two foreign keys. Let's say I have the following unit:
@Entity Public Square Fu {@ManyToOne private times; Private IT; } (I did not leave empty and exclusive contagious tags to make the code more readable)
I know that I can only generate an ID field , With the value generated, and my DB generates my keyboard (MySQL Auto_Increate with automatic example), but it seems disabling for me because it involves querying the database, and generating a unique ID value The new saying.
ID, which is not composite on the basis of the value of the "bar" class and the value of the integer "i" (i.e. type or long type), because these two values already make a unique obstacle?
You may wish to check chapter 7 of "".
You can model the entire key as a Embeddable :
Import javax.preistence. *; Import Java.io.Serializable; @Entity Public Class Fu {@Embedizable Public Static Class ID implementation serializable {@ column (name = "bar_id_ col") private long time id I @ Column (name = "i_col") private int i; Public ID () {} Public ID (Long time ID, IIFI) {this.barId = barId; This.i = i; } @ Override Public Boolean equivalent (last object o) {if (this == o) {return true; } If (! (IISIF for example)) {return false; } Last id id = (id) o; If (I! = IDI) {return false; } If (bar iid! = Null?! Bar id. Idle (id. Bard): id. Bar! = Null) {return false; } Back true; } @ Override Public Ent Hashod () {Fine Results = Bar ID = Zero? BarId.hashCode (): 0; Results = 31 * results + i; Return result; }} @ Embedded ID Private ID ID = New ID (); @ManyToOne @JoinColumn (name = "bar_id_col", insertable = false, updatable = false) Private times and times; Private IT; Public Fu () {} Public Fu (repeatedly, int i) {// set field it.bar = bar; I =; // set identifier value this.id.bar.bd = bar.getId (); This.id.i = i; }} Here I see the bar:
import javax.preistence.Entity; Import javax.preistence.Id; @Entity Public Class Bar {@Id Long ID; Public long iid () {return id; } Public Zero Set ID (Last Long Id) {this.id = id; }} Note that this map has twice the bar_id_en ; this is the second reason insertable = false, updatable = false is.
It is difficult, but if you really want to do this, then it is possible.
Good luck, J.
Comments
Post a Comment