I have 3 tables represented by JPA model. The first one:
@MappedSuperclass
public abstract class BaseEntity {
@Id
private Long id;
private Boolean active;
}
Next class extends BaseEntity:
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Person extends BaseEntity{
private String name;
}
The last one is Student which extends Person:
@Entity
public abstract class Student extends Person{
private Integer grade;
}
So, I have field "active" both in Person and Student tables. I want that when I update field "active" through PersonRepository it also updates appropriate row in Student table. For now it updates only Person table. Is it possible?
I found the solution with annotation @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;
}
And implemented method which updates "active" field in Person table instead of Student (I use 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 will take the "active" value of Person and insert into Student with the same id. Eventually, "active" field of Student won't be used at all, but I can't get rid of it because of @MappedSuperclass.