本文介绍了@ManyToOne(updatable = false)-应该如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我想在一个实体中具有只读功能。我知道在JPA 2.0中我们本身没有这样的功能。我以为我们可以使用 updateable = false,insertable = false 来实现它,但我不认为这是如何工作的。I want to have a read-only functionality in one of my entities. I know that in JPA 2.0 we don't have such functionality per se. I thought we can achieve it using updateable=false, insertable=false but I don't think I get how it works.假设我有两个实体: OrderedItem 和 Customer :Assume that I have two entities: OrderedItem and Customer:@Entitypublic class OrderedItem { @Id @GeneratedValue private int id; private String name; @ManyToOne @JoinColumn(updatable = false) private Customer owner; // bunch of simple getters and setters}@Entitypublic class Customer { @Id @GeneratedValue private int id; private String name; @OneToMany(mappedBy="owner") private Set<OrderedItem> orderedItems; // bunch of simple getters and setters}现在考虑以下代码:Customer john = new Customer();john.setName("John");OrderedItem milk = new OrderedItem();milk.setName("Milk");milk.setOwner(john);Set<OrderedItem> items = new HashSet<OrderedItem>();items.add(milk);john.setOrderedItems(items);// This starts the EM transactionstartTx();em.persist(john);em.persist(milk);stopTx();startTx();OrderedItem milkFromPC = em.find(OrderedItem.class, milk.getId());System.out.println(milkFromPC.getName() + " ordered by customer: " + milkFromPC.getOwner().getName());// Changing the state of Owner entity through the OrderedItemmilkFromPC.getOwner().setName("Terrence");stopTx();现在,没有 @JoinColumn(updatable = false)在 OrderedItem 实体中, OrderedItem 将从PC上获取,我可以访问它的所有者- Customer -并将成功修改其名称。这并不奇怪,因为 Customer 也处于托管状态,因此必须将其反映在数据库中。Now, without @JoinColumn(updatable = false) in OrderedItem entity, the OrderedItem would be fetched from the PC, I'd access it's owner - a Customer - and would successfully modified its name. It wouldn't be a surprise because the Customer was also in managed state, so it had to be reflected in the database. 但是,我假设 @JoinColumn 中的 updateable = false 设置为关系的一侧将阻止UPDATE SQL语句的发生。不幸的是,最后我可以在数据库中看到名称更改(它是 Terrence而不是 John)。我还可以看到执行的SQL UPDATE查询:However, I assumed that updateable=false in @JoinColumn set on the One side of the relationship would prevent the UPDATE SQL statement from occurring. Unfortunately in the end I can see the name changed in the database (it's "Terrence" instead of "John"). I can also see the executed SQL UPDATE query:所以-这是什么 updateable =错误真的吗?我为什么需要它?它仅保护我的外键不被更改吗?就像您不能更改实体,但可以更改实体的状态吗?So - what does this updateable=false really do? Why do I need it? Does it protect only my foreign key from being changed? Is it like 'you can't change the entity but you can change the state of the entity'?推荐答案从文档就像您说的那样,它仅保护我的外键不被更改So like you said, "it protects only my foreign key from being changed" 这篇关于@ManyToOne(updatable = false)-应该如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-31 08:16