我在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;
最佳答案
当需要加入时,您应该始终知道要在关联上进行加入。 DemoOrder和DemoUser之间的关联由字段demoUser映射(因为您已将DemoUser当作根用户),因此应执行以下操作:
Join<DemoUser, DemoOrder> join = root.join("demoUser", JoinType.INNER);