Illya Slobozhanin Illya Slobozhanin - 1 year ago 93
Java Question

Foreign key join using hibernate

Hi all i've got some errors using join with hibernate
I use postgresql 9.5.

My db tables: cart

(cart_id - primary key, cart.product_id references product.product_id - foreign key)
and product
(product_id - primary key)

Java classes

@Table(name = "product")
public class Product{
@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)
private Cart cart;


@Table(name = "cart")
public class Cart {
@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;

How should i annotate my classes in order to have query
SELECT * FROM cart AS c INNER JOIN product p ON c.product_id = p.product_id

I tried annotane @PrimaryKeyJoinColumn and @JoinColumn with names/referencedColumnName, but got errors or
hibernate made query (mostly) like
SELECT * FROM cart AS c INNER JOIN product p ON c.cart_id = p.product_id
So it "connects cart_id and product_id, when I need product_id and product_id in cart and product tables.

Upd. It worked fine before, but after dumping/restoring db this errors appeared.

My HQL query is
SELECT c FROM Cart c JOIN c.product

Answer Source

Firstly, lazy fetch won't work on @OneToOne. Watch this

You have foreign key on Cart table, so you should map it like this:

Cart entity:

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

And for Product entity:

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

Vote it as an answer if i helped you)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download