JPA CriteryQuery内部联接-IllegalStateException

时间:2018-09-04 20:40:49

标签: java jpa jpa-criteria

我在JPA中有以下qriteria查询:

      CriteriaBuilder cb2 = entityMager.getCriteriaBuilder();
      CriteriaQuery<DemoUser> cqInnerJoin = cb2.createQuery(DemoUser.class);
      Root<DemoUser> root = cqInnerJoin.from(DemoUser.class);
      Join<DemoUser, DemoOrder> join = root.join("userId", JoinType.INNER);

但是会引发异常:

Exception in thread "main" java.lang.IllegalStateException: CAN_NOT_JOIN_TO_BASIC (There is no English translation for this message.)
    at org.eclipse.persistence.internal.jpa.querydef.FromImpl.join(FromImpl.java:354)
    at org.eclipse.persistence.internal.jpa.querydef.FromImpl.join(FromImpl.java:513)
    at jpaTest.jpaTest.main(jpaTest.java:144)

我从Oracle数据库表中生成了这些类。我的代码有问题吗?

我在TypedQuery中尝试过此操作,但它显示了相同的错误消息。

生成的类:

DemoUser.class

 @Entity
    @Table(name="DEMO_USERS")
    public class DemoUser implements Serializable {
        private static final long serialVersionUID = 1L;

        @Id
        @GeneratedValue(strategy=GenerationType.IDENTITY)
        @Column(name="USER_ID")
        private long userId;

        //bi-directional many-to-one association to DemoOrder
        @OneToMany(mappedBy="demoUser")
        //@JoinColumn(name = "USER_ID")
        private List<DemoOrder> demoOrders;

DemoOrder类

@Entity
@Table(name="DEMO_ORDERS")
public class DemoOrder implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="ORDER_ID")
    private long orderId;

    @Temporal(TemporalType.DATE)
    @Column(name="ORDER_TIMESTAMP")
    private Date orderTimestamp;

    @Column(name="ORDER_TOTAL")
    private BigDecimal orderTotal;

    //bi-directional many-to-one association to DemoCustomer
    @ManyToOne
    @JoinColumn(name="CUSTOMER_ID")
    private DemoCustomer demoCustomer;

    //bi-directional many-to-one association to DemoUser
    @ManyToOne
    @JoinColumn(name="USER_ID")
    private DemoUser demoUser;

    //bi-directional many-to-one association to DemoOrderItem
    @OneToMany(mappedBy="demoOrder")
    private List<DemoOrderItem> demoOrderItems;

2 个答案:

答案 0 :(得分:1)

当需要加入时,您应该始终知道要在关联上进行加入。 DemoOrder和DemoUser之间的关联由字段demoUser映射(因为您已将DemoUser设为 root ),因此,您应该执行以下操作:

Join<DemoUser, DemoOrder> join = root.join("demoUser", JoinType.INNER);

答案 1 :(得分:0)

您不能加入基本类型(长)的属性“ userId”。对于单个属性,可以加入Entity或Embeddable类型。