简体   繁体   English

Spring Data JPA存储库返回父类的实体

[英]Spring data JPA repository returns entity of parent class

I have strange problem with spring data and inheritance, i have two classes: 我对spring数据和继承有奇怪的问题,我有两个类:

@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 和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: 我也有两个简单的接口,像这样扩展JpaRepo:

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: 然后在@Transactional中的代码中,我像这样使用它:

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. 还有一个问题B在这里为NULL,但是在表b的DB中它以100%确定相同的ID存在。 IF in debug i write 如果在调试中我写

BRepository.getOne(a.getId());

it returns instance of A, same instance A as above from ARepository. 它从ARepository返回实例A,与上面的实例A相同。

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. 我还尝试更改此示例中的等于和哈希码http://docs.jboss.org/hibernate/orm/5.3/userguide/html_single/Hibernate_User_Guide.html#identifiers-composite-associations,但是没有运气,问题仍然存在。

Hibernate version is: 5.0.12.Final Spring boot dependencies: 1.5.6.RELEASE Hibernate版本是:5.0.12.Final Spring启动依赖项: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. JOOK用于创建递归sql请求,并休眠以将该请求映射到实体。 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. 由于实体具有映射的继承关系,因此我必须在硬编码为0的请求中添加“ clazz_”字段,此请求之后,所有实体都会以某种方式缓存在第一个lvl休眠缓存中,然后无法从DB重新请求。 I add to my JOOK 我添加到我的JOOK

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

And now all working as expected 现在一切都按预期工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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