Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA/Hibernate @MappedSuperclass and @Inheritance(strategy = InheritanceType.JOINED) relation

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?

like image 959
Yuriy Gorbylov Avatar asked Dec 11 '25 20:12

Yuriy Gorbylov


1 Answers

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.

like image 161
Yuriy Gorbylov Avatar answered Dec 13 '25 10:12

Yuriy Gorbylov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!