Search code examples
javahibernatemany-to-many

Hibernate many to many - junction table is empty


I want to model many-to-many relationship in Java Hibernate.
I want graphics to have many categories and categories to be assigned to more than one graphic.
Parts of my java classes code:

@Entity
@Table(name = "graphic")
public class Graphic {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int graphicId;
    @ManyToMany
    private Set<Category> categories = new HashSet<Category>(0);
    // ...
}

@Entity
@Table(name = "category")
public class category {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int categoryId;
    // ...
}

Steps I have done:
1. Created Category instance.
2. Added category to database.
3. Created Graphic instance.
4. Added category to graphics set.
5. Added graphic to database.

Result: Records in category and graphic instance are OK. Table graphic_category is created, but it is empty. As result join hql queries are not returning any rows.
I will appreciate any help how to resolve this issue.

EDIT: Steps as code:

//In DBUtil
/**
 * Gets category. If none exists creates new.
 */
public Category getCategory(String name) {
    String hql = "From Category K where K.name = '" + name + "'";
    Query query = session.createQuery(hql);
    if (query.list().isEmpty()) {
        return saveCategory(name);
    } else {
        return (Category)query.list().get(0);
    }
}

public Category saveCategory(String name) {
    Category kat = new Category(name);
    session.save(kat);
    return kat;
}

public Graphic saveGraphic(Graphic g) {
    session.save(g);
    return g;
}


//In unit test
Category kat1 = dbUtil.getCategory("kat1-g");
Graphic g1 = new Graphic();
g1.getCategories().add(kat1);
dbUtil.saveGraphic(g1);

I have set autocommit to true.


Solution

  • OK, I found a reason.
    In my Hibernate config file I had:

    <property name="connection.autocommit">true</property>
    

    Even with that setting I have to make session.flush() after inserting objects to database to make persistent change.