如何使用EntyManager createQuery函数将postgresql select查询转换为jpa?

时间:2014-08-31 07:11:57

标签: sql postgresql jpa

有人可以帮我翻译下面的postgresql查询到EntyManager.createQuery吗?

SELECT distinct id.itemid,  id.itemdetailid, id.property,  id.propertyval
FROM item_detail1 id 
join (SELECT distinct  i.itemid
      FROM item_detail1 id 
      join item i
        on i.itemid = id.itemid
      where 
        id.itemdetailid in (9,22,24,27)) myItems
  on myItems.itemid = id.itemid
join category_item ci
  on ci.itemid = id.itemid
where id.itemdetailid not in (9,22,24,27) and 
    ci.categoryid = 1005 and id.propertyval is not null
order by id.property asc, id.itemdetailid asc

以下是缺少的必需实体。我在内连接中遇到子查询的问题最多。我有以下jpa查询但缺少子查询连接。

SELECT distinct id.itemid,  id.itemdetailid, id.property,  id.propertyval  
FROM item_detail1 id 
join id.itemid i
join i.categoryCollection c
where id.itemdetailid not in (9,22,24,27) and 
  c.categoryid = 1005 and id.propertyval is not null
order by id.property asc, id.itemdetailid asc





@Entity
@Table(name = "item_detail1")
@XmlRootElement
public class ItemDetail1 implements Serializable
{

   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   @Basic(optional = false)
   @Column(name = "itemdetailid")
    private Integer itemdetailid;

   @JoinColumn(name = "itemid", referencedColumnName = "itemid")
   @ManyToOne
    private Item itemid;

 ..getters and setters
}                                       


@Entity
@Table(name = "item")
@XmlRootElement
public class Item implements Serializable
{
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Basic(optional = false)
  @Column(name = "itemid")
       private Integer itemid;

  @ManyToMany(mappedBy = "itemCollection")
    private Collection<Category> categoryCollection;

  @OneToMany(mappedBy = "itemid")
    private Collection<ItemDetail1> itemDetail1Collection;

 ..getters and setters
}


@Entity
@Table(name = "category")
@XmlRootElement
public class Category implements Serializable
{
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   @Basic(optional = false)
   @Column(name = "categoryid")
    private Integer categoryid;


   @JoinTable(name = "category_item", joinColumns =
   {
      @JoinColumn(name = "categoryid", referencedColumnName = "categoryid")
   }, 
    inverseJoinColumns = {
      @JoinColumn(name = "itemid", referencedColumnName = "itemid")
   })
   @ManyToMany
    private Collection<Item> itemCollection;

 ..getters and setters
}

感谢。

1 个答案:

答案 0 :(得分:0)

SELECT DISTINCT id.itemdetailid,  id.property,  id.propertyval 
FROM ItemDetail1 id 
join id.itemid i 
join i.categoryCollection cc 
where id.itemdetailid not in :itemdetailid 
      and cc.categoryid = :categoryid 
      and id.propertyval is not null 
      and EXISTS(SELECT 1 
                 FROM ItemDetail1 id2 
                 where id2.itemdetailid in :itemdetailid  
                 and id.itemid = id2.itemid) 
order by id.property asc, id.itemdetailid asc