Hibernate在join上返回false值

时间:2016-10-13 11:21:02

标签: postgresql hibernate

我使用hibernate时出错了。 我的课程:

@Entity
@Table(name = "cart")
public class Cart {
    @Id
    @Column(name = "cart_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int cartId;

    @Column(name = "user_id")
    private int userId;

    @Column(name = "product_id")
    private int productId;

    @Column(name = "quantity")
    private int quantity;

    @OneToOne(fetch = FetchType.LAZY, mappedBy = "cart", cascade = CascadeType.ALL)
    private Product product;

我的第二堂课:

@Entity
@Table(name = "products")
public class Product{
    @Id
    @Column(name = "product_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int productId;

    @Column(name = "article")
    private String article;

    @Column(name = "name")
    private String name;

    @Column(name = "price")
    private BigDecimal price;

    @Column(name = "description")
    private String description;

    @Column(name = "manufacturer")
    private String manufacturer;

    @Column(name = "category")
    private String category;

    @Column(name = "unitsinstock")
    private long unitsInStock;

    @OneToOne(fetch = FetchType.LAZY)
    @PrimaryKeyJoinColumn
    private Cart cart;

执行此代码时:

String hql = "SELECT c FROM Cart c JOIN c.product ORDER BY c.cartId ASC";
List<Cart> cart = session.createQuery(hql).list();

返回错误的值,其中product_id等于cart_id

我将数据库转移到新电脑后发现了这一点(使用pg_dump postgres 9.5)。

我认为恢复后存在一些错误,但表结构是正确的。

购物车外键:"cart_pkey" FOREIGN KEY (product_id) REFERENCES products(product_id) ON DELETE CASCADE

产品索引:"products_pkey" PRIMARY KEY, btree (product_id)

产品主键:TABLE "cart" CONSTRAINT "cart_pkey" FOREIGN KEY (product_id) REFERENCES products(product_id) ON DELETE CASCADE

1 个答案:

答案 0 :(得分:0)

你的hql对我来说不清楚,你想要返回什么,如果购物车为什么你甚至需要加入?

正确的hql将是

     String hql = "SELECT c.product FROM Cart c ORDER BY c.cartId ASC";
     List<product> cart = session.createQuery(hql).list();

通过这种方式,您可以获得已经引用产品的购物车对象,无需其他任何东西