0

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 Cart and 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;

and

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

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

1 Answers1

1

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)

Community
  • 1
  • 1
ch3rn1k0v
  • 440
  • 3
  • 9
  • Thanks a lot, it works now) But i added `@JoinColumn` like this `@JoinColumn(name = "product_id", insertable = false, updatable = false)` cuz hibernate sweared cuz of `@JoinColumn(name = "product_id")` – Illya Slobozhanin Oct 15 '16 at 16:36