java - JPA2向表添加引用约束使带有延迟获取的条件查询变得复杂,需要建议

标签 java jpa jpa-2.0

以下是针对我认为非常简单的问题的大量写作。问题的根源是我的无知,不是在寻找代码而是在寻找建议。

表:Ininvhst(库存架构库存历史记录)列 ihtran(库存历史记录转移代码)使用我拥有的旧实体映射:

@Basic(optional = false)
@Column(name = "IHTRAN")
private String ihtran;

ihtran 实际上是表 Intrnmst(“库存转移主数据”,其中包含“转移代码”列表)的外键。这没有在数据库中表达,因此对重新生成生成的 JPA2 实体类的 Ininvhst 施加了引用约束:

@JoinColumn(name = "IHTRAN", referencedColumnName = "TMCODE", nullable = false)
@ManyToOne(optional = false)
private Intrnmst intrnmst;

现在,之前我使用 JPA2 从 Ininvhst 表中选择记录/(Ininvhst 实体),其中“ihtran”是一组值之一。我使用 in.value() 来执行此操作...这是一个片段:

        cq = cb.createQuery(Ininvhst.class);
        ...
        In<String> in = cb.in(transactionType); //Get in expression for transacton types
        for (String s : transactionTypes) { //has a value
            in = in.value(s);//check if the strings we are looking for exist in the transfer master
        }
        predicateList.add(in);

我的问题是 Ininvhst 过去包含一个名为 ihtran 的字符串,但现在它包含 Ininvhst...所以我现在需要一个路径表达式:

    this.predicateList = new ArrayList<Predicate>();
    if (transactionTypes != null && transactionTypes.size() > 0) { //list of strings has some values
        Path<Intrnmst> intrnmst = root.get(Ininvhst_.intrnmst); //get transfermaster from Ininvhst
        Path<String> transactionType = intrnmst.get(Intrnmst_.tmcode); //get transaction types from transfer master
        In<String> in = cb.in(transactionType); //Get in expression for transacton types
        for (String s : transactionTypes) { //has a value
            in = in.value(s);//check if the strings we are looking for exist in the transfer master
        }
        predicateList.add(in);
    }

我可以将 ihtran 添加回实体以及两个引用“IHTRAN”的连接列吗?或者我应该使用投影以某种方式返回 Ininvhst 以及 ihtran 字符串,该字符串现在是 Intrnmst 实体的一部分。或者我应该使用投影来返回 Ininvhst 并以某种方式限制 Intrnmst 只是 ihtran 字符串。

更多信息:我在 Web 应用程序中使用所选 Ininvhst 对象的结果列表,包含 Ininvhst 对象列表的类将转换为 json 对象。可能有相当多的序列化方法可以导航对象图,问题是我当前的获取策略是惰性的,因此它会命中连接实体(Intrnmst intrnmst),并且此时没有可用的实体管理器。此时,我已阻止对象序列化连接列,但现在我丢失了一条关键数据。

我觉得我说得太多了,但了解的还不够,我不知道你们JPA专家需要什么。我想要的是我的原始对象既具有字符串对象,又能够连接到同一列(ihtran),但如果这是不可能或不明智的,我想听听我应该做什么以及为什么。

伪代码/英语就更好了。

最佳答案

Can I add ihtran back into the entity along with a join column that is both references "IHTRAN"?

是的。只需将其中之一设置为只读(insertable/updateable=false)

如果您使用 EclipseLink,您还可以为外键添加 QueryKey。

如果您在序列化之前访问关系,那么它将可用。否则将其设置为 EAGER,或者在查询中加入 fetch。

关于java - JPA2向表添加引用约束使带有延迟获取的条件查询变得复杂,需要建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4719766/

相关文章:

java - 从 jruby 和 warbled jar 运行之间有什么区别 "under the hood"?

java - 这个接口(interface)声明在java中是什么意思?

java - 如何查找不在数组列表中的数字?

postgresql - 如何将 Postgres any 子句与 JPA/Hibernate native 查询(数组参数)一起使用

java - "user lacks privilege"是什么意思?

java - JPA中按组获取记录

java - 如何在 Apache poi 中按名称获取单元格样式

mysql - JPA/Hibernate 查询执行时间太长

java - ManyToMany with CascadeType.ALL 导致 Detached entity passed to persist

jakarta-ee - 在 JPQL 中可以选择 EXISTS() 吗?