Java 请参考 JPA @Column 注释解释 insertable=false 和 updatable=false
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3805584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Please explain about insertable=false and updatable=false in reference to the JPA @Column annotation
提问by Thang Pham
If a field is annotated insertable=false, updatable=false
, doesn't it mean that you cannot insert value nor change the existing value? Why would you want to do that?
如果一个字段被注释insertable=false, updatable=false
,是不是意味着你不能插入值也不能改变现有值?你为什么想这么做?
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToMany(mappedBy="person", cascade=CascadeType.ALL)
private List<Address> addresses;
}
@Entity
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
@JoinColumn(name="ADDRESS_FK")
@Column(insertable=false, updatable=false)
private Person person;
}
采纳答案by BalusC
You would do that when the responsibilityof creating/updating the related entity in question isn't in the currententity. E.g. you have a Person
and an Address
. You'd like to add insertable=false, updatable=false
to the @OneToMany
relationship with the Person
entity in the Address
entity, simply because it's not the responsibility of the Address
entity to create or update a Person
. It's the other way round.
当创建/更新相关实体的责任不在当前实体中时,您会这样做。例如,您有一个Person
和一个Address
。您想添加与实体中实体insertable=false, updatable=false
的@OneToMany
关系,仅仅是因为实体没有责任创建或更新. 这是反过来的。Person
Address
Address
Person
回答by Pascal Thivent
Defining insertable=false, updatable=false
is useful when you need to map a field more than once in an entity, typically:
insertable=false, updatable=false
当您需要在实体中多次映射字段时,定义很有用,通常:
- when using a composite key
- when using a shared primary key
- when using cascaded primary keys
This is IMO not a semantical thing, but definitely a technical one.
这是 IMO 不是语义上的事情,但绝对是技术上的事情。
回答by Magnilex
I would like to add to the answers of BalusCand Pascal Thiventanother common use of insertable=false, updatable=false
:
我想在BalusC和Pascal Thivent的答案中添加另一个常见用法insertable=false, updatable=false
:
Consider a column that is not an idbut some kind of sequence number. The responsibility for calculating the sequence number may not necessarily belong to the application.
考虑一个不是id而是某种序列号的列。计算序列号的责任不一定属于应用程序。
For example, sequence number starts with 1000 and should increment by one for each new entity. This is easily done, and very appropriately so, in the database, and in such cases these configurations makes sense.
例如,序列号从 1000 开始,并且应该为每个新实体递增 1。这在数据库中很容易完成,而且非常合适,在这种情况下,这些配置是有意义的。
回答by Johny19
An other example would be on the "created_on" column where you want to let the database handle the date creation
另一个示例是在“created_on”列上,您希望在该列中让数据库处理日期创建