How to make an Entity read-only?

后端 未结 9 1150
情歌与酒
情歌与酒 2020-12-03 00:43

What is the proper way to make an Entity read-only with JPA ? I wish my database table to never be modified at all programmatically.

I think I understand that I sho

相关标签:
9条回答
  • 2020-12-03 01:04

    IIRC you could set every field to insertable = false and updatable = false in your @Column annotations, but I'm sure there must be a better method... :)

    I don't suppose this helps?

    0 讨论(0)
  • 2020-12-03 01:04

    This is probably going to catch me a downvote because I always get downvoted for suggesting it, but you could use AspectJ in several ways to enforce this:

    Either automate Mac's solution (make AspectJ inject the @Column annotation):

    declare @field : (@Entity *) *.* : @Column(insertable=false);
    

    Or declare a compiler error for all access to set methods:

    declare error : execution((@Entity *) *.set*(*) );
    

    Downside: you need to add AspectJ compilation to your build, but that's easy if you use ant or maven

    0 讨论(0)
  • 2020-12-03 01:08

    I think what you are looking for is your entity to be Immutable. Hibernate supports this; JPA(at least JPA 1.0) does not. I suppose you can only control this by providing only getters and make sure that the getters return only immutable values.

    0 讨论(0)
提交回复
热议问题