简体   繁体   中英

Spring data JPA repository returns entity of parent class

I have strange problem with spring data and inheritance, i have two classes:

@Getter
@Setter
@Entity
@Table(name = "a")
@Inheritance(strategy = InheritanceType.JOINED)
public class A {

  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "a_id_gen")
  @SequenceGenerator(name = "a_id_gen", sequenceName = "a_id_seq", allocationSize = 50)
  @Column(name = "id")
  private Long id;
}

And class B

@Getter
@Setter
@Entity
@Table(name = "b")
public class B extends A {

@ManyToOne
@JoinColumn(name = "subject")
private Subject subject;
}

Also i have two simple interfaces which extends JpaRepo like this:

public interface ARepository extends JpaRepository<A, Long>
public interface BRepository extends JpaRepository<B, Long>

And then in code in @Transactional i use it like this:

A a = ARepository.findOne(someId);
if (some checks here) {
    B b = BRepository.findOne(a.getId());
}

And a problem that B here is NULL, however in DB in table b it exists with same ID 100% sure. IF in debug i write

BRepository.getOne(a.getId());

it returns instance of A, same instance A as above from ARepository.

How i could make this work as i need? I think that problem in some hibernate managed cache or something. I also tried to change equals and hashcode like in this example http://docs.jboss.org/hibernate/orm/5.3/userguide/html_single/Hibernate_User_Guide.html#identifiers-composite-associations but no luck, problem still there.

Hibernate version is: 5.0.12.Final Spring boot dependencies: 1.5.6.RELEASE

Ok i found out problem cause. It was query earlier in transaction. JOOK was used to create recursive sql request, and hibernate to map this request to entity. Because of entity have inheritance for mapping i have to add "clazz_" field in request with hard coded 0, after this request all entity was cached in first lvl hibernate cache somehow and cant be then reRequested from DB. I add to my JOOK

.select(when(B.ID.isNotNull(), 1).otherwise(0).as("clazz_"))

And now all working as expected

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM