Reputation: 133
I have two Classes Error and MainError (* - * association with MainError is the owner of the association)
I want to persist the data in my database and I cannot use Persist Cascade because I have many duplicate objects and I want to recognize the duplicate objects and associate them with the persisted ones (The name of Error and MainError is unique)
Error error1 = new Error ("ERR1");
Error error2 = new Error ("ERR2");
Error error3 = new Error ("ERR3");
Error error4 = new Error ("ERR4");
Error error5 = new Error ("ERR5");
Error error6 = new Error ("ERR1");
MainError mainError1 = new MainError("MAIN1");
MainError mainError2 = new MainError("MAIN2");
MainError mainError3 = new MainError("MAIN2");
mainError1.addError(error1);
mainError1.addError(error2);
mainError1.addError(error3);
mainError1.addError(error6);
mainError2.addError(error1);
mainError2.addError(error4);
mainError3.addError(error5);
//persisting Error and MainError
for example if I already persisted Error error1 = new Error ("ERR1") in my database and then I want to persist Error error6 = new Error ("ERR1"); I want that my application recognize that this is already persisted and associate "ERR1" to the corresponding MainError. I guess I will need to create a method findByName to know if the name of Error/MainError is already persisted and if so, returning this object, working with it and merge it ?
I hope that my question is not confusing Thank you very much
Upvotes: 1
Views: 940
Reputation: 2899
As you mentioned in your question, you can manually check for data exist in DB or not? For that you can also set that column as a uniq constraint.
Alternative solution :
In your case, the database design should be something like this :
error :
id varchar (PK)
mainerror :
id varchar (PK)
error_id varchar (FK)
and the entity classes should be something like this :
Error.java
@Entity
public class Error {
@Id
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 2147483647)
@Column(nullable = false, length = 2147483647)
private String id;
@OneToMany(mappedBy = "errorId", fetch = FetchType.LAZY)
private Collection<MainError> mainErrorCollection;
public Error() {
}
public Error(String id) {
this.id = id;
}
//getter and setter methods
}
MainError.java
@Entity
@Table(name = "main_error")
public class MainError {
@Id
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 2147483647)
@Column(nullable = false, length = 2147483647)
private String id;
@JoinColumn(name = "error_id", referencedColumnName = "id")
@ManyToOne(fetch = FetchType.LAZY)
private Error errorId;
public MainError() {
}
public MainError(String id) {
this.id = id;
}
//getter and setter methods
}
You should prevent adding duplicate record by making joint PK of id and error_id for main_error table.
Upvotes: 1