Many To One Hibernate Relations

I have modified the previous standalone Hibernate application to indicate how a one to many relation between objects is handled in Hibernate. http://cuppajavamattiz.com/2008/06/14/migrating-to-a-standalone-spring-hibernate-application/ I am using the jars under the folllwing folders in spring-framework-2.5.4-with-dependencies.zip:

spring-framework-2.5.4/lib/c3p0
spring-framework-2.5.4/lib/cglib
spring-framework-2.5.4/lib/jakarta-commons
spring-framework-2.5.4/lib/dom4j
spring-framework-2.5.4/lib/hibernate
spring-framework-2.5.4/dist
spring-framework-2.5.4/lib/log4j
spring-framework-2.5.4/lib/antlr

Of course I also separately downloaded and used jta.jar and the mysql driver.

The book has a one to many relationship with the author object with one book being written by serveral authors.

You need to run the following scripts for database intialization: I have used the same database named “authors” for this purpose.

CREATE TABLE TB_AUTHOR (UID int NOT NULL default 0, FIRST_NAME varchar(15) default NULL, LAST_NAME varchar(15) default NULL, BOOK_ID varchar(10) default NULL, PRIMARY KEY (UID)) ;

CREATE TABLE TB_BOOK (ISBN_CODE varchar(10) NOT NULL default '0', TITLE varchar(25) default NULL,PRIMARY KEY (ISBN_CODE)) ;

I am only including source code for the DAO class and the domain classes and the hbm.xml files for simplicity. The client code can be rewritten using code in the previous code as a base.

The DAO class:

package com.mattiz.persistence.data;
 
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
 
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateTemplate;
 
import com.mattiz.persistence.beans.Author;
import com.mattiz.persistence.beans.Book;
 
public class AuthorLookupBean {
 
    private HibernateTemplate hibernateTemplate;
 
    public void insertBook() throws DataAccessException {
        Book book = new Book();
        book.setIsbnCode("124");
        book.setTitle("The Dodo");
        book.setAuthors(new HashSet());
        book.getAuthors().add(new Author("Roy", "John"));
        book.getAuthors().add(new Author("James", "Joyce"));
        book.getAuthors().add(new Author("Jill", "Joyce"));
        book.getAuthors().add(new Author("Amy", "Watt"));
        book.getAuthors().add(new Author("Matt", "Tizz"));
        HibernateTemplate template = getHibernateTemplate();
        template.save(book);
    }
 
    public void getAuthorsFromBook() throws DataAccessException {
        String isbn = "124";
        Book book = (Book) getHibernateTemplate().load(Book.class, isbn);
        Set authors = book.getAuthors();
        Iterator iterator = authors.iterator();
        while (iterator.hasNext()) {
            Author author = (Author) iterator.next();
            System.out.println("FIRST NAME " + author.getFirstName());
            System.out.println("SECOND NAME " + author.getLastName());
        }
    }
 
    public HibernateTemplate getHibernateTemplate() {
        return hibernateTemplate;
    }
 
    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        this.hibernateTemplate = hibernateTemplate;
    }
}

The Author Domain class:

package com.mattiz.persistence.beans;

public class Author {
	public Author() {
	}

	public Author(String first, String last) {
		this.firstName = first;
		this.lastName = last;
	}

	private String firstName;
	private String lastName;
	private long id;

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}
}

The Book Domain class:

package com.mattiz.persistence.beans;

import java.util.Set;

public class Book {
	private String isbnCode;
	private String title;
	private Set authors;

	public String getIsbnCode() {
		return isbnCode;
	}

	public void setIsbnCode(String isbnCode) {
		this.isbnCode = isbnCode;
	}

	public Set getAuthors() {
		return authors;
	}

	public void setAuthors(Set authors) {
		this.authors = authors;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}
}

The Author hbm.xml

<?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="com.mattiz.persistence.beans.Author" table="TB_AUTHOR"
        lazy="false">
        <id name="id" column="UID" type="long">
            <generator class="increment" />
        </id>
        <property name="firstName" type="java.lang.String" column="FIRST_NAME"
            length="25" />
        <property name="lastName" type="java.lang.String" column="LAST_NAME"
            length="25" />
    </class>
</hibernate-mapping>

Note on id generator classes in hibernate:
assigned: lets the application to assign an identifier to the object before save() is called. This is the default strategy if no generator element is specified.
increment: It generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. It should not the used in the clustered environment.
sequence: The sequence generator uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int
identity: It supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int.
hilo: The hilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database. Do not use this generator with connections enlisted with JTA or with a user-supplied connection.
seqhilo: The seqhilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a named database sequence.
uuid: The uuid generator uses a 128-bit UUID algorithm to generate identifiers of type string, unique within a network (the IP address is used). The UUID is encoded as a string of hexadecimal digits of length 32.
guid: It uses a database-generated GUID string on MS SQL Server and MySQL.
native: It picks identity, sequence or hilo depending upon the capabilities of the underlying database.

select: retrieves a primary key assigned by a database trigger by selecting the row by some unique key and retrieving the primary key value.
foreign: uses the identifier of another associated object. Usually used in conjunction with a primary key association.

The Book hbml.xml

<?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="com.mattiz.persistence.beans.Book" table="TB_BOOK"
        lazy="false">
        <id name="isbnCode" column="ISBN_CODE" type="string">
            <generator class="assigned" />
        </id>
        <set name="authors" cascade="save-update" lazy="false">
            <key column="BOOK_ID" />
            <one-to-many class="com.mattiz.persistence.beans.Author" />
        </set>
        <property name="title" type="java.lang.String" column="TITLE"
            length="50" />
    </class>
</hibernate-mapping>

Output looks something like this:


mysql> select * from tb_author;
+-----+------------+-----------+---------+
| UID | FIRST_NAME | LAST_NAME | BOOK_ID |
+-----+------------+-----------+---------+
|   1 | James      | Joyce     | 124     |
|   2 | Amy        | Watt      | 124     |
|   3 | Jill       | Joyce     | 124     |
|   4 | Roy        | John      | 124     |
|   5 | Matt       | Tizz      | 124     |
+-----+------------+-----------+---------+
5 rows in set (0.00 sec)

mysql> select * from tb_book;
+-----------+----------+
| ISBN_CODE | TITLE    |
+-----------+----------+
| 124       | The Dodo |
+-----------+----------+

You would have to clean the data in the database after each run to avoid constraint violations, or better still modify the code above to handle that!

By the way, I would like to add something: I get a classic Lazy Initialization Exception if I don’t declare the set in Book.hbm.xml as lazy=”false”, that is I let it load non-lazy. This is a workaround and should be avoided as it could raise performance issues in critical situations.
NoteLazy loading and can be achieved in hibernate using the lazy attribute. Lazy setting decides whether to load child objects while loading the Parent Object. You need to specify parent class.Lazy = true in hibernate mapping file. By default the lazy loading of the child objects is true. This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent. In this case hibernate issues a fresh database call to load the child when getChild() is actully called on the Parent object. But in some cases you do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database. Examples: Address child of User class can be made lazy if it is not required frequently. But you may need to load the Author object for Book parent whenever you deal with the book for online bookshop.

Access source code here

About cuppajavamattiz
Matty Jacob - Avid technical blogger with interests in J2EE, Web Application Servers, Web frameworks, Open source libraries, Relational Databases, Web Services, Source control repositories, ETL, IDE Tools and related technologies.

Comments are closed.

%d bloggers like this: