Reputation: 2872
I've a class called Node that can have many Grades. And one grade can be associated with many Node objects. So many to many. my annotations are like the following:
@Entity
@Table(name="tbl_nodes")
public class Node {
//getters setters, constructors.
private Set<Grade> grades = new HashSet<Grade>();
@ManyToMany(mappedBy = "nodes")
public Set<Grade> getGrades() {
return grades;
}
}
// and here is grade class
@Entity
@Table(name="grades")
public class Grade {
private Set<Node> nodes;
// getters, setters, constructors
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(
name = "node_grade",
joinColumns = @JoinColumn(name = "grade_id"),
inverseJoinColumns = @JoinColumn(name = "node_id")
)
public Set<Node> getNodes() {
return nodes;
}
}
both classes have @Id annotated ofcourse. For eg. for grade entity it would be:
@Id
@GeneratedValue
@Column(name="grade_id")
public int getId() {
return id;
}
My grade table has 5 rows and a subset of the rows will be referenced when the relationship is made with a node object. I'm using the following query to create a relation between node and grade.
// loads configuration and mappings
Configuration configuration = new Configuration().configure();
ServiceRegistryBuilder registry = new ServiceRegistryBuilder();
registry.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = registry.buildServiceRegistry();
// builds a session factory from the service registry
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
// obtains the session
Session session = sessionFactory.openSession();
session.beginTransaction();
// List all grade
Query queryAllGrades = session.createQuery("FROM Grade");
List<Grade> allGrades = queryAllGrades.list();
for(Grade grade: allGrades) {
System.out.println("Grade::" + grade.getName());
}
// Create a new Node
Node node = new Node();
node.addGrade(allGrades.get(0));
session.save(node);
session.getTransaction().commit();
session.close();
But this only saves the Node object but this doesn't write to my table "node_grade" What am I missing?
even if I try to save the grade object it doesn't save the relationship in node_grade.
session.save(allGrades.get(0)); //doesn't save either the node or the node_grade
session.saveOrUpdate(allGrades.get(0)); //doesn't save either the node or the node_grade
What could be the issue?
Upvotes: 0
Views: 848
Reputation: 691625
You're modifying the inverse side of the association. Hibernate only cares about the owner side.
Node node = new Node();
session.save(node);
allGrades.get(0).addNode(node);
Upvotes: 1