[英]Foreign key join using hibernate
大家好,在使用休眠连接时我遇到了一些错误,我使用的是PostgreSQL 9.5。
我的数据库表: cart (cart_id - primary key, cart.product_id references product.product_id - foreign key)
购物车 (cart_id - primary key, cart.product_id references product.product_id - foreign key)
和产品 (product_id - primary key)
Java类Cart
和Product
@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,但是遇到了错误或休眠状态的查询(主要是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
首先,@ OneToOne无法使用懒惰获取。 看这个
您在Cart表上具有外键,因此应按以下方式映射它:
购物车实体:
@OneToOne(cascade = CascadeType.All)
@JoinColumn(name = "product_id")
private Product product;
对于产品实体:
@OneToOne(mappedBy = "product")
private Cart cart;
如果我有帮助,请投票作为答案)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.