Hi, i am a hibernate-beginner and have a problem when trying to join 2 tables with hibernate. What i am trying to do is get the list of products a certain store has depending on the store id, but what i am getting is the list of all available products in the database listed under every store.
Here's the code for Product.java
:
@Entity
@Table (name = "products")
public class Product implements Serializable{
/**
*
*/
private static final long serialVersionUID = -1001086120280322279L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column (name = "product_id")
private int product_id;
@Column(name = "product_name", unique=true)
private String product_name;
@JoinColumn(name = "store", referencedColumnName="store_id")
@ManyToOne(cascade=CascadeType.ALL)
private Store store;
etc..
and here's the code for Store.java
:
@Entity
@Table(name = "stores")
public class Store implements Serializable{
/**
*
*/
private static final long serialVersionUID = 4497252090404342019L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column (name = "store_id")
private int store_id;
@Column(name = "store_name", unique=true)
private String store_name;
@JoinColumn(name="store", referencedColumnName= "store_id")
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
private List<Product> productList;
etc..
Here's the output: (products A should be under Butik A and products B under Butik B)
Butik: Butik A
Produkt: Banana A
Produkt: Morot A
Produkt: Banana B
Produkt: Apple B
Butik: Butik B
Produkt: Banana A
Produkt: Morot A
Produkt: Banana B
Produkt: Spple B
I have 2 additional classes, ProductDAO and StoreDAO that take care of the query, the code is similar in both classes except the table-name/class-name.
public class ProductDAO {
public static List<Product> getStoreProductsList() {
Session hibernateSession = HibernateUtil.getSession();
hibernateSession.beginTransaction();
Query query = hibernateSession.createQuery("from Product");
hibernateSession.getTransaction().commit();
List<Product> storeProducts = query.list();
return storeProducts;
}
}
Is there any way of solving this with hibernate only?
Thanks