【问题标题】:Foreign key join using hibernate使用休眠的外键连接
【发布时间】:2017-02-24 22:52:37
【问题描述】:

大家好,我在使用休眠连接时遇到了一些错误 我使用 postgresql 9.5。

我的数据库表:cart (cart_id - primary key, cart.product_id references product.product_id - foreign key)product (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 注释 @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 时。

更新。它之前工作正常,但在转储/恢复数据库后出现此错误。

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

【问题讨论】:

  • 您两次放置产品实体的购物车实体的共享代码。
  • @IssamELATIF Ready=)

标签: java postgresql hibernate


【解决方案1】:

首先,惰性获取不适用于@OneToOne。观看this


你在 Cart 表上有外键,所以你应该像这样映射它:

购物车实体:

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

对于产品实体:

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

如果我帮助了你,请投票作为答案)

【讨论】:

  • 非常感谢,它现在可以工作了)但是我添加了 @JoinColumn 这样的 @JoinColumn(name = "product_id", insertable = false, updatable = false) cuz hibernate sweared cuz of @JoinColumn(name = "product_id")
猜你喜欢
  • 1970-01-01
  • 2015-12-04
  • 1970-01-01
  • 2018-05-29
  • 1970-01-01
  • 2016-05-17
  • 1970-01-01
  • 2017-07-30
  • 2012-12-22
相关资源
最近更新 更多