3

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?

Yuriy Gorbylov
  • 104
  • 1
  • 5
  • Why do you want to duplicate "active" across two tables ? Do you have a concrete class that extend student ? – M4ver1k Sep 08 '15 at 09:16
  • 2
    Column `active` in `Student` table shouldn't exists. Did you create this yourself, or it was generated by Hibernate? – Predrag Maric Sep 08 '15 at 09:18
  • @Predrag Maric Actually it exists because of MappedSuperclass. – Yuriy Gorbylov Sep 09 '15 at 09:27
  • @M4ver1k I want to have ability to filter Persons and Students by "active" field. But when I update "active" in Person table, Student is not updated. That's why I have discrepancy between these tables. – Yuriy Gorbylov Sep 09 '15 at 10:30
  • @YuriyGorbylov Ok got it, I would not keep Person and Student as separate tables in DB, but again it would depend on your requirements. – M4ver1k Sep 09 '15 at 11:13

1 Answers1

2

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.

Yuriy Gorbylov
  • 104
  • 1
  • 5