简体   繁体   English

实体存在或更新时如何自动更新实体

[英]How to automatically update an entity when an entity is persisted or updated

I have an entity that has a reference to another one like these: 我有一个实体引用了另一个像这样的实体:

class School {
   private boolean used = false;
}

class Student {
   @ManyToOne
   private School school;
}

The attribute used indicates that the School entity is whether used, referenced or not. 属性used表示该School实体是否使用,引用或不是。 So when created, a School entity should have used false, but once a Student makes a reference to it, the used must be turned to true. 创建所以,当一个School的实体应该used假的,但一旦一个Student ,使对它的引用,在used一定要变成真实的。 Is there any automatically way to do this like triggers in database? 有没有自动的方法可以做到这一点,例如数据库中的触发器?

I try to use @PrePersist and @PostPersist on Student entity like this but it doesn't work: 我尝试像这样在Student实体上使用@PrePersist@PostPersist ,但它不起作用:

@PrePersist
public void prePersist(){
    school.setUsed(true);
}

Thanks, 谢谢,

My thought is that School should also have a reverse list of students. 我的想法是学校也应该有一个相反的学生名单。 ie

class School {
   private List<Student> students;
}

So when the school is loaded, you can easily access the list of students. 因此,当学校加载完毕后,您可以轻松访问学生列表。 Then finding out if a school is being used becomes very simple. 然后找出是否正在使用学校变得非常简单。 You will not longer need a boolean flag, just this: 您将不再需要布尔标志,只需要这样:

public boolean hasStudents() {
    return students.size() > 0;
}

One way is to write a trigger on the insert, update of Student table, which will check if someone is holding the foreign key reference to school and you will have to check for all schools here. 一种方法是在“学生”表的插入,更新上编写一个触发器,该触发器将检查是否有人持有对学校的外键引用,并且您必须在此处检查所有学校。 Also map your used variable to a column in School table. 还将您使用的变量映射到School表中的列。 If any student is holding a reference, than make the column true and call a refresh from your application layer. 如果有任何学生持有参考文献,则将该列设为true,然后从您的应用程序层调用刷新。

On the second thought, check if this is possible. 再三考虑,检查是否可行。 When ever you need the logic for used variable, see that if you can write an HQL and using that HQL check if that particular school is currently getting used by any of the Student. 每当您需要使用的变量的逻辑时,请查看是否可以编写HQL并使用该HQL检查该学生是否正在使用该特定学校。 This I think is a cleaner approach, but finally it's a call based on requirements :) 我认为这是一种更清洁的方法,但最终它是基于需求的电话:)

Additionally you need to define the CascadeType . 另外,您需要定义CascadeType See the example below: 请参阅以下示例:

class Team {
  @OneToMany(mappedBy="team", cascade = CascadeType.ALL)
  Set players;
} 
class Player {
  @ManyToOne
  Team team;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM