1

I have an JPA entity with contains a ManyToOne reference to another table, a simplified version of that entity is shown below:

@Entity
@Table(name = "ENTITIES")
public class Entity implements Serializable {
    @Id @NotNull
    private String id;

    @JoinColumn(name = "REFERENCE", referencedColumnName = "ID")
    @ManyToOne(optional = false)
    private ReferencedEntity referencedEntity;
}

@Entity
@Table(name = "REFERENCES")
public class ReferencedEntity implements Serializable {
    @Id @NotNull @Column(name = "ID")
    private String id;

    @Size(max = 50) @Column(name = "DSC")
    private String description;
}

Finding entities works fine. Peristing entities also works fine, a bit too good in my particular setup, I need some extra validation.

Problem
My requirement is that the rows in table REFERENCES are static and should not be modified or new rows added.
Currently when I create a new Entity instance with a non-existing (yet) ReferencedEntity and persist that instance, a new row is added to REFERENCES.

Right now I've implemented this check in my own validate() method before calling the persist(), but I'd rather do it more elegantly.
Using an enum instead of a real entity is not an option, I want to add rows myself without a rebuild/redeployment several times in the future.

My question
What is the best way to implement a check like this?
Is there some BV annotation/constraint that helps me restrict this? Maybe a third party library?

Bossk
  • 707
  • 8
  • 24

2 Answers2

1

It sounds like you need to first do a DB query to check if the value exists and then insert the record. This must be done in a transaction in order to ensure that the result of the query is still true at the time of insertion. I had a similar problem half a year back which might provide you with some leads on how to set up locking. Please see this SO question.

Community
  • 1
  • 1
Janus Varmarken
  • 2,306
  • 3
  • 20
  • 42
  • Yes, this seems to be the only solution for me. I'm wondering if I can put this in a custom validator though.. – Bossk Mar 03 '17 at 06:58
0

You should add this => insertable=false, updatable=false

And remove => optional=false , and maybe try nullable=true