使用hibernate的外键连接

时间:2016-10-15 16:02:48

标签: java postgresql hibernate

大家好我在使用hibernate加入时遇到了一些错误 我使用postgresql 9.5。

我的数据库表: 购物车 (cart_id - primary key, cart.product_id references product.product_id - foreign key) 产品 (product_id - primary key)

Java类CartProduct

@Entity
@Table(name = "product")
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;

    @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;

如何对我的类进行注释以便查询SELECT * FROM cart AS c INNER JOIN product p ON c.product_id = p.product_id

我尝试使用名称/ referencedColumnName注释annotane @PrimaryKeyJoinColumn和@JoinColumn,但是出现了错误或 hibernate使查询(大部分)像SELECT * FROM cart AS c INNER JOIN product p ON c.cart_id = p.product_id所以它“连接cart_id和product_id,当我在购物车和产品表中需要product_id和product_id时。

UPD。之前它工作正常,但在转储/恢复数据库之后出现了这个错误。

我的HQL查询是SELECT c FROM Cart c JOIN c.product

1 个答案:

答案 0 :(得分:1)

首先,懒惰的获取不会对@OneToOne起作用。观看this

您在Cart表上有外键,因此您应该像这样映射:

购物车实体:

@OneToOne(cascade = CascadeType.All)
@JoinColumn(name = "product_id")
    private Product product;

对于产品实体:

@OneToOne(mappedBy = "product")
    private Cart cart;

如果我帮助你,请将其作为答案)