我目前陷入更新父实体字段并将更新级联到其所有子实体字段的问题。
这是我想要实现的目标的示例:
用户.java
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(nullable = false, columnDefinition = "TINYINT(1) default false")
private Boolean archived = Boolean.FALSE;
@OneToMany(mappedBy = "user")
private Set<Invoice> invoices = new HashSet<Invoice>();
// Setters & Getters
}
发票.java
@Entity
public class Invoice{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(nullable = false, columnDefinition = "TINYINT(1) default false")
private Boolean archived = Boolean.FALSE;
@ManyToOne(mappedBy = "invoices")
@JoinColumn(nullable = false)
private User user;
// Setters & Getters
}
当我将存档值更新为true
时。我希望所有发票也更新为 true
。
IE
public Boolean archiveUserById(Integer id) {
User user= entity_manager.find(User.class, id);
Boolean result = false;
if(auction != null) {
// This should cascade to all the invoices as well and update their archived fields to true as well
user.setArchived(true);
try {
entity_manager.getTransaction().begin();
entity_manager.merge(auction);
entity_manager.getTransaction().commit();
result = true;
} catch(Exception e) {
e.printStackTrace();
}
}
return result;
}
我已尝试将 cascade = CascadeType.PERSIST
和 @JoinTable(....)
与所有引用的列一起使用,但它们仍然无法更新字段正确。
澄清一下,是否有一种方法可以通过父级的更新来更新子级的字段,并具有级联效果?
谢谢您的帮助。
编辑
为了澄清我的问题,我试图在更新父实体上的字段以反射(reflect)子实体的相同字段时添加约束级联效果。我试图避免实体本身的任何逻辑。有没有办法仅通过注释来做到这一点?
与此效果相同的东西:
ALTER TABLE `child` ADD CONSTRAINT `childs-archived-mirrors-parent`
FOREIGN KEY (`archived`, `parentId`)
REFERENCES `parent`(`archived`, `id`)
ON DELETE RESTRICT ON UPDATE CASCADE;
最佳答案
尝试在父级上添加@PreUpdate
方法,您可以在其中手动更改列表中的子级。
关于java - JPA 实体 - 如何根据其父字段更新子实体字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59727102/