【问题标题】:Spring Data JPA: Handling inherited property of other entitySpring Data JPA:处理其他实体的继承属性
【发布时间】:2017-09-28 08:54:19
【问题描述】:

情况: (类是实体)

  • class1 具有 属性 类型为 class2
  • subclass1(继承自 class1)将类型 subclass2(继承自 class2)用于 property
  • subclass2 有一个 property2,而 class2 没有

如何在 subclass1Repository 中实现这一点:

findByProperty_property2(xx)

显然我得到“找不到类型 class1 的属性“property2”,遍历路径:class2.property2。

显然 JPA 不知道 property 属于 subclass2 类型。

@Entity
open class Class1 constructor(
        @ManyToOne property: Class2
)

@Entity
open class Class 2 constructor() {

}

@Entity
open class subclass1 constructor(
        property: Subclass2
):Class1(property = property)


@Entity
open class subclass2 constructor(
        property2: Double
):Class2(..)


interface subclass1Repository: JpaRepository<Subclass1, Long>{
fun findByProperty_property2(prop2:Double): List<Subclass1>
}

【问题讨论】:

  • 不要描述你的代码。发表它。 Java 中没有覆盖属性这样的东西。只有方法可以被覆盖。
  • 你使用泛型类型而不是覆盖吗?
  • @JBNizet:已发布(虽然是 Kotlin)
  • @Al1:我没有,我不知道这里怎么做
  • 使用 JPA 规范 (download.oracle.com/otndocs/jcp/persistence-2_1-fr-eval-spec/…) 中描述的 TREAT JPQL 运算符。规格示例:SELECT b.name, b.ISBN FROM Order o JOIN TREAT(o.product AS Book) b

标签: java spring jpa kotlin


【解决方案1】:

您想映射subclass1 和subclass2?我对你的问题有点迷茫......但希望这对你有价值。

@Entity
public class Foo1 {
@Id
private int id; // primary key is great to have for map tables.
  @ManyToMany // or something 
  @JoinTables(...
  private List<Foo2> foo2;
}

@Entity
public class Foo2 {
  @Id
  private int id;
  @ManyToMany(mappedBy="foo2")
  private List<Foo1> foo1;

}

创建 getter 和 setter。


foo2 的存储库:

public interface Foo2Repository extends CrudRepository<Foo2, Long> {
    Foo2 findBySomeValue(Double doubleValue); 

您可以为方法创建@Service 类:

@Service
public class FooService {
  @Autowired
  private Foo2Repository foo2Repository;

public List<Foo1> ListMyFoo(Double doubleValue) {
  return this.yourInterface.findBySomeValue(doubleValue).getFoo1();

}

它返回一个基于列表的 Foo2 SomeValue 为真。

【讨论】:

  • 感谢您的回答,但我担心问题比这更复杂
猜你喜欢
  • 2015-02-17
  • 2019-04-06
  • 2020-09-22
  • 2019-04-17
  • 1970-01-01
  • 2014-05-08
  • 2015-08-24
  • 1970-01-01
  • 2012-09-09
相关资源
最近更新 更多