Reputation: 23896
So, I have a model with three entities: Document, Template and Origin.
The main source of my problem is that I need the Document's number to be unique for the Template's Source, but as the origin is property of Template
(not of Document
), I can't create an unique constraint for it in a straight-forward manner.
Just to clarify, the model in code goes something like this:
Origin:
@Entity
public class Origin {
@Id private Long id;
// ... some other fields
}
Template:
@Entity
public class Template {
@Id private Long id;
@Column private Origin origin;
// ... some other fields
}
Document:
@Entity
public class Document {
@Id private Long id;
@Column Template template;
@Column Long number;
// ... some other fields
}
So, Origins have several Templates associated, and you can create Documents for an Origin using a Template.
As I said, the source of my problem is that a document's number must be unique for each source. The only way I could thought for that to work is to use an additional field for the originId, and try to keep it updated.
So, I was trying to do something like this:
@Entity
@Table("documents",
uniqueConstraints = @UniqueConstraint(columnNames = {"number", "originId"}))
public class Document {
@Id private Long id;
@Column Template template;
@Column Long number;
// ... some other fields
// added extra field to use in the constraint:
@Column Long originId;
@PrePersist
@PreUpdate
private void updateConstraintValue() {
this.originId = getTemplate().getId();
}
}
Note: getters, setters and other boilerplate ommited for brevity
but that won't always work with JPA, since the Template object isn't required to be a managed entity at the time of the persist/update event (it's only required to have an id set for the relationship to work).
Then I'm now thinking this may not be the best approach. So, my question is:
Upvotes: 0
Views: 96
Reputation: 910
I might be missing something, but can you get rid of the origin ID altogether and simply use a generated ID for the Document rather than creating one manually? You already have an ID column there. It looks like all you need to do is specify that the ID be generated.
@Entity
@Table("documents" )
public class Document {
@Id
@GeneratedValue( strategy = GenerationType.IDENTITY )
private Long id;
@Column Template template;
@Column Long number;
// ... some other fields
}
Note: I've added the GeneratedValue annotation and removed the origin ID
Upvotes: 1