Hibernate version: 3.0
Name and version of the database you are using: MySQL 5.0
I can't seem to add an entry onto my association table.
Here's the setup:
"Supplier" can have many "Book"
"Book" can have many "Supplier"
I have a join table called BookSupplier that takes both the PK's of Book and Supplier; and sets it as its own PK
here is my Supplier.hbm
Code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Supplier" table="suppliers">
<id name="supplierId" column="supplierId" type="int">
<generator class="native"/>
</id>
<property name="name"/>
<property name="address"/>
<set name="books" table="BookSupplier" inverse="true">
<key column="supplierId" />
<many-to-many column="bookId" class="Book"/>
</set>
</class>
</hibernate-mapping>
Book.hbm
Code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Book" table="Book">
<id name="bookId" column="bookId" type="int">
<generator class="native"/>
</id>
<property name="bookTypeId" type="int"/>
<property name="title"/>
<property name="author"/>
<property name="publisher"/>
<property name="language"/>
<property name="pageCount" type="int"/>
<property name="quantity" type="int"/>
<property name="margin" type="int"/>
<property name="status"/>
<set name="bookSuppliers" table="BookSupplier">
<key column="bookId" />
<many-to-many column="supplierId" class="SupplierBean"/>
</set>
</class>
</hibernate-mapping>
I already have Book.java and Supplier.java that have the necessary setters and getters.
excerpt from Supplier.java (to show the code for adding sets)
Code:
protected Set getBooks() {
return books;
}
protected void setBooks(Set newbook) {
books = newbook;
}
public void addBooks(Book book) {
this.getBooks().add(book);
book.getBookSuppliers().add(this);
}
public void removeBooks(Book book) {
this.getBooks().remove(book);
book.getBookSuppliers().remove(this);
}
this is the code that hopefully saves the object
Code:
public boolean addBookSupplier(Book b, Supplier s)
{
boolean check = false;
try
{
Book tempB;
Supplier tempS;
tempB = (Book)((session.createQuery("from Book as book where book.title = ?")).setString(0,b.getTitle())).list().get(0);
tempS = (Supplier)((session.createQuery("from Supplier as s where s.name = ?")).setString(0,s.getName())).list().get(0);
tempS.addBooks(tempB);
session.save(tempS);
tx.commit();
check = true;
}catch(HibernateException e) {
System.out.println(e.getMessage());
}
return check;
}
After I execute the code above, there would be no errors. However, the object was not saved onto the database. Any ideas?