JPA/Hibernate的@MappedSuperclass和@Inheritance(strategy = Inhe



我有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;
 }

最后一个是Student,它扩展了Person:

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

因此,我在Person和Student表中都有字段"active"。我想当我通过PersonRepository更新字段"active"时,它也会更新学生表中的适当行。目前它只更新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表中的"active"字段而不是Student(我使用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。最终,学生的"活动"字段将不会被使用,但我不能摆脱它,因为@MappedSuperclass.

最新更新