Home > Blockchain >  JPA unmodifiable database row
JPA unmodifiable database row

Time:09-17

The Problem

I'm currently working on a Spring-Application as part of a university-project and we have run into the following problem:

I have a JPA-Entity that models a table of States and I would like to have a hardcoded End-State that always exists in the Database and cannot be deleted or modified. In the best case, it should have a special id (eg. 0), so it can be easily referenced from the application.

I also cannot model the States as Enums, because they have to be configurable at runtime.

Code

The Entity looks something like this (abbreviated):

@Entity
public class BillingItemState {

    @Autowired
    private BillingItemStateRepository billingItemStateRepository;

    @Id
    private String id;

    @NotEmpty
    private String name;

    @ManyToMany
    private List<BillingItemState> parentStates = new ArrayList<>();

    @ManyToMany(mappedBy = "parentStates", cascade = CascadeType.PERSIST)
    private List<BillingItemState> nextStates;
}

What I've tried so far

I have tried to enforce the rule by using @PrePersist, @PreUpdate and @PreDelete, but that doesn't seem like a very good solution, because that gives me no way to insert the End-State when the database is created. I've also thought of rather unelegant solutions, like having an own Table just for the unmodifiable Final-State, but that also raises some problems.

Is there a more suitable patterns for achieving this task? I feel like I'm on the completely wrong path here.

(Also, this is my first question. If you have any improvements to my question, please comment them :)

CodePudding user response:

I think what you need is @Immutable.

This annotation allows you to make your row immutable (you won’t be able to make any updates).

But insert action still will be possible as well as delete.

To get rid of delete possibility you can try @PreRemove with throwing some exception or any different logic.

To initialise database state data.sql file should be good.

You can consider also Flyway or Liquibase.

Additional resources

  1. Article about @Immutable
  2. Immutable user guide
  3. @PreRemove
  4. Spring docs about data.sql and database initialisation

CodePudding user response:

I would say that if you can, try to model the Final state as some kind of attribute i.e. a boolean isEnd. This way you have no problem with deletion or setup of static data.

  • Related