Java Criteria API - 使用嵌入式ID加入

时间:2015-03-18 10:15:12

标签: java hibernate jpa criteria-api

我已经使用Java Criteria API创建了一个应用程序来实现一个惰性数据模型并且它可以工作,但我正在尝试通过进行连接查询来减少JDBC语句。问题是其中一个实体具有嵌入式ID。您可以在下面看到实体定义:

消息权限:

@Entity
@NamedQuery(name = "Message.findAll", query = "SELECT m FROM Message m")
public class Message implements Serializable {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name = "\"Id_Msg\"")
  private long id_Msg;


  // bi-directional many-to-one association to Recipients
  @OneToMany(cascade = CascadeType.ALL, mappedBy = "message")
  private List<Recipients> recipients;

收件人实体:

 @Entity 
    @Table(name="RECIPIENTS")
    @NamedQuery(name="Recipients.findAll", query="SELECT m FROM Recipients m")
    public class Recipients implements Serializable {
        @EmbeddedId
        private RecipientsPK id;

        //bi-directional many-to-one association to Message
        @ManyToOne(cascade = CascadeType.PERSIST)
        @MapsId(value = "id_Msg")
        @JoinColumns({
            @JoinColumn(name = "`Id_Msg`", referencedColumnName = "`Id_Msg`", insertable=false, updatable=false),
            })
        private Message message;

收件人PK类:

    @Embeddable
public class RecipientsPK implements Serializable {

    @Column(name="\"Id_Msg\"", insertable=false, updatable=false)
    private long id_Msg;

    @Column(name="\"Receiver\"")
    private String receiver;

这是我尝试加入Message与收件人实体的距离,但我因为嵌入的id而陷入困境:

   CriteriaQuery<Message> q = cb.createQuery(Message.class);


  Metamodel m = entityManager.getMetamodel();
  EntityType<Message> Message_ = m.entity(Message.class);
  Root<Message> message = q.from(Message.class);

  Join<Message, Recipients> mess = (Join<Message, Recipients>) message.join(Message_.getSingularAttribute("id_Msg"));
  q.select(message);

上面的代码生成:org.hibernate.jpa.criteria.BasicPathUsageException:无法连接到基本类型的属性(在连接线上)

0 个答案:

没有答案