gpt4 book ai didi

java - JPA/Hibernate @MappedSuperclass 和@Inheritance(strategy = InheritanceType.JOINED) 关系

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:18:01 25 4
gpt4 key购买 nike

我有 3 个由 JPA 模型表示的表。第一个:

@MappedSuperclass
public abstract class BaseEntity {
@Id
private Long id;
private Boolean active;
}

下一类扩展 BaseEntity:

 @Entity
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Person extends BaseEntity{
private String name;
}

最后一个是扩展 Person 的 Student:

@Entity
public abstract class Student extends Person{
private Integer grade;
}

所以,我在 Person 和 Student 表中都有字段“active”。我希望当我通过 PersonRepository 更新字段“Activity ”时,它也会更新 Student 表中的相应行。现在它只更新 Person 表。可能吗?

最佳答案

我找到了注释@Formula 的解决方案:

@Entity
public abstract class Student extends Person{

@Formula("(SELECT p.active FROM person p WHERE p.id = id)")
private Boolean active;
private Integer grade;
}

并实现了更新 Person 表而不是 Student 中的“Activity ”字段的方法(我使用 Spring Data):

public interface StudentRepository extends JpaRepository<Student, Long>{

@Override
@Query("update Person p set p.active = false where p.id = ?1")
@Modifying
@Transactional
void deactivate(Long id);
}

@Formula 将获取 Person 的“active”值并插入到具有相同 ID 的 Student 中。最终,Student 的“active”字段根本不会被使用,但由于@MappedSuperclass,我无法摆脱它。

关于java - JPA/Hibernate @MappedSuperclass 和@Inheritance(strategy = InheritanceType.JOINED) 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32453718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com