Search code examples
javamysqldatabasehibernatepojo

How work with foreign keys in Hibernate?


I'm new to Hibernate. This is my problem. I can do this:

package = session.createQuery("from Package").list();
session.getTransaction().commit();

But what I really want is this in SQL:

select * from package,product where product.nome='television' and package.idProduct = product.id

How do I do that?

These are my POJOs:

public class Package implements java.io.Serializable {

  private PackageId id;
  private User user;
  private Product product;
  private int quant;
  private char mode;
  private String unit;
  private String description;

public class PackageId implements java.io.Serializable {

  private int id;
  private int idProduct;

public class Product  implements java.io.Serializable {

  private int id;
  private String name;
  private Set packages = new HashSet(0);

These POJOs were generated by Netbeans.

Is this configuration right?

http://pastebin.com/gBUdKke0


Solution

  • You're already working with HQL. With HQL you can select multiple objects not just one or just a set of object fields.

    select product, package 
    from Product product
    join product.packages package
    where product.name = 'television' 
    

    See HQL reference for select for examples.