Verifying Many to One Bidirectional Hibernate Mapping using Domain Files created by hbm2java

Next we move onto how we use the generated classes in the post below to develop a hibernate application that demonstrates many to one bidirectional relationship. We have a little bit of spring but the highlight is to demonstrate hibernate capabilities.
Refer
http://cuppajavamattiz.com/2012/01/20/hibernate-mappings-with-hbm-xml-files/
and
http://cuppajavamattiz.com/2012/01/30/domain-java-files-from-hibernate-mapping-files/
First we would need to create a database with the following DDL for mySQL:

script

drop database hibemappings;
create database hibemappings;
use hibemappings;
create table Book (isbn_code bigint(3) not null auto_increment, book_title varchar(30), primary key(isbn_code));
create table Author (author_id bigint(3) not null auto_increment, isbn_code_in_author bigint(3), first_name varchar(30), last_name varchar(30), primary key(author_id), foreign Key (isbn_code_in_author) references Book(isbn_code));

The workspace for the project has the following structure on eclipse:

<project>
     <com.mattiz.persistence.beans>
          ...copy over the generated domain files from previous post
          BookWithMultipleAuthors.java
          ContributingAuthor.java
     <com.mattiz.persistnece.data>
          MappingDAO.java
          MappingDAOImpl.java
     <com.mattiz.service.spring>
          AppInvoker.java
     <resources>
         author.hbm.xml(same mapping file used to generate domain files as in previous post)
         book.hbm.xml(same mapping file used to generate domain files as in previous post)
         mattiz.xml(spring configuration file)

I have put most of the jars in http://cuppajavamattiz.com/2008/06/14/migrating-to-a-standalone-spring-hibernate-application/ example on the classpath with a minor change. In addition I have added \spring-framework-2.5.4-with-dependencies\spring-framework-2.5.4\lib\cglib\cglib-nodep-2.1_3.jar also on the classpath.

Copy over the domain classes generated by the hbm2 java and the hbml.xml files to the location shown above. (See previous post)

Note the lazy=false in both hibernate mapping files at two locations by which we enforce eager fetch.

mattiz.xml is the spring configuration file which provides the Spring’s hibernate support to our DAO:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
	<bean id="mattiz.hibernate.dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
		destroy-method="close">
		<property name="driverClass" value="com.mysql.jdbc.Driver" />
		<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/hibemappings" />
		<property name="user" value="root" />
		<property name="password" value="admin" />
	</bean>
	<bean id="mattiz.abstract.hibernate.sessionfactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
		abstract="true" lazy-init="true">
		<property name="dataSource">
			<ref local="mattiz.hibernate.dataSource" />
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">
					org.hibernate.dialect.MySQLDialect
				</prop>
				<prop key="hibernate.show_sql">false</prop>
			</props>
		</property>
	</bean>
	<bean id="mattiz.pageSize" class="java.lang.Integer">
		<constructor-arg value="5000"></constructor-arg>
	</bean>
	<bean id="mattiz.hibernate.sessionfactory" parent="mattiz.abstract.hibernate.sessionfactory">
		<property name="mappingResources">
			<list>
				<value>resources/author.hbm.xml</value>
				<value>resources/book.hbm.xml</value>
			</list>
		</property>
	</bean>
	<bean id="mattiz.transactionManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory">
			<ref bean="mattiz.hibernate.sessionfactory" />
		</property>
	</bean>
	<bean id="mattiz.hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
		<property name="sessionFactory">
			<ref bean="mattiz.hibernate.sessionfactory" />
		</property>
	</bean>
	<bean id="mattiz.mattizDAO" class="com.mattiz.persistence.data.MappingDAOImpl"
		singleton="true">
		<property name="hibernateTemplate">
			<ref bean="mattiz.hibernateTemplate" />
		</property>
	</bean>
</beans>

We write the following java classes to demonstrate the many to one bidirectional relationship:

MappingDAO.java

package com.mattiz.persistence.data;
 
import java.util.Set;
import com.mattiz.persistence.beans.BookWithMultipleAuthors;
import com.mattiz.persistence.beans.ContributingAuthor;
 
public interface MappingDAO {
     
    public Set<ContributingAuthor> getContributingAuthors(long isbnCode);
 
    public BookWithMultipleAuthors getBookForAuthor(long authorId);
 
    public void initializeDB();
}

MappingDAOImpl.java

package com.mattiz.persistence.data;
 
import java.util.Iterator;
import java.util.Random;
import java.util.Set;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.mattiz.persistence.beans.BookWithMultipleAuthors;
import com.mattiz.persistence.beans.ContributingAuthor;
 
public class MappingDAOImpl implements MappingDAO {
    private HibernateTemplate hibernateTemplate;
 
    public HibernateTemplate getHibernateTemplate() {
        return hibernateTemplate;
    }
 
    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        this.hibernateTemplate = hibernateTemplate;
    }
 
    public Set<ContributingAuthor> getContributingAuthors(long isbnCode) {
        BookWithMultipleAuthors bookWithMultipleAuthors = (BookWithMultipleAuthors) getHibernateTemplate()
                .load(BookWithMultipleAuthors.class, isbnCode);
        Set<ContributingAuthor> authors = bookWithMultipleAuthors
                .getContributingAuthors();
        Iterator<ContributingAuthor> i = authors.iterator();
        while (i.hasNext()) {
            System.out.println("Author "
                    + ((ContributingAuthor) i.next()).getFirstName());
        }
        return authors;
    }
 
    public BookWithMultipleAuthors getBookForAuthor(long authorId) {
        ContributingAuthor contributingAuthor = (ContributingAuthor) getHibernateTemplate()
                .load(ContributingAuthor.class, authorId);
        BookWithMultipleAuthors book = contributingAuthor
                .getBookContributedToByAuthor();
        System.out.println("BOOK " + book.getTitle());
        return book;
    }
 
    public void initializeDB() {// fill up db with random named AUTHORs and
                                // BOOKs
        HibernateTemplate template = getHibernateTemplate();
        BookWithMultipleAuthors bookEntity = new BookWithMultipleAuthors();
        Random random = new Random();
        int ran = generateRandomInteger(65, 74, random);// boiler plate code
        bookEntity.setTitle(new String(new char[] { (char) ran,
                (char) (ran + 3), (char) (ran + 10), (char) (ran + 15) }));
        template.saveOrUpdate(bookEntity);
        System.out.println("Inserted Book, ISBN, Title:  "
                + bookEntity.getIsbnCode() + " " + bookEntity.getTitle());
        for (int i = 0; i < 10; i++) {
            ran = generateRandomInteger(65, 85, random);
            ContributingAuthor contributingAuthor = newContributingAuthor(ran,
                    bookEntity);
            System.out.println("Inserted Author, First and last name:  "
                    + contributingAuthor.getFirstName() + " "
                    + contributingAuthor.getLastName());
        }
    }
 
    private ContributingAuthor newContributingAuthor(int i,
            BookWithMultipleAuthors bookEntity) {
        HibernateTemplate template = getHibernateTemplate();
        ContributingAuthor contributingAuthor = new ContributingAuthor();
        contributingAuthor.setBookId(i);
        contributingAuthor.setFirstName(new String(new char[] { (char) (i + 2),
                (char) (i + 1), (char) (i + 3) }));
        contributingAuthor.setLastName(new String(new char[] { (char) (i + 3),
                (char) (i + 2), (char) (i + 4) }));
        contributingAuthor.setBookContributedToByAuthor(bookEntity);
        template.save(contributingAuthor);
        return contributingAuthor;
    }
 
    private static int generateRandomInteger(int aStart, int aEnd,
            Random aRandom) {// boiler plate code to generate ascii code for A-Z
        if (aStart > aEnd) {
            throw new IllegalArgumentException("Start cannot exceed End.");
        }
        long range = (long) aEnd - (long) aStart + 1;
        long fraction = (long) (range * aRandom.nextDouble());
        int randomNumber = (int) (fraction + aStart);
        return randomNumber;
    } 
}

AppInvoker.java

package com.mattiz.service.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.mattiz.persistence.data.MappingDAO;
import com.mattiz.persistence.data.MappingDAOImpl;

public class AppInvoker {
	private ApplicationContext applicationContext;
	private MappingDAO mappingDAOImpl;

	public static void main(String[] args) {
		AppInvoker appInvoker = new AppInvoker();
		appInvoker.setApplicationContext(new ClassPathXmlApplicationContext(
				"resources/mattiz.xml"));
		appInvoker.getMappingDAO().initializeDB();
		appInvoker.getMappingDAO().getContributingAuthors(2L);// demonstrates one to many
		appInvoker.getMappingDAO().getBookForAuthor(11);// demonstrates many to one
	}

	public MappingDAO getMappingDAO() {
		mappingDAOImpl = (MappingDAOImpl) applicationContext
				.getBean("mattiz.mattizDAO");
		return mappingDAOImpl;
	}

	public void setMapppingDAO(MappingDAO mappingDAOImpl) {
		this.mappingDAOImpl = mappingDAOImpl;
	}

	public ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	public void setApplicationContext(ApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
	}
}

On running the main class in AppInvoker.java you may see an output similar to this on the console:

Inserted Book, ISBN, Title:  9 GJQV
Inserted Author, First and last name:  NMO ONP
Inserted Author, First and last name:  RQS SRT
Inserted Author, First and last name:  JIK KJL
Inserted Author, First and last name:  LKM MLN
Inserted Author, First and last name:  HGI IHJ
Inserted Author, First and last name:  CBD DCE
Inserted Author, First and last name:  RQS SRT
Inserted Author, First and last name:  UTV VUW
Inserted Author, First and last name:  LKM MLN
Inserted Author, First and last name:  GFH HGI
Author HGI
Author LKM
Author QPR
Author POQ
Author ONP
Author FEG
Author TSU
Author GFH
Author EDF
Author MLN
BOOK EHOT

The database might look something like this – verify the mapping->

mysql> select * from book;

+-----------+------------+
| isbn_code | book_title |
+-----------+------------+
|         1 | ILSX       |
|         2 | EHOT       |
|         3 | CFMR       |
|         4 | FIPU       |
|         5 | GJQV       |
|         6 | EHOT       |
|         7 | HKRW       |
|         8 | BELQ       |
|         9 | GJQV       |
+-----------+------------+
9 rows in set (0.00 sec)

mysql> select * from author;
+-----------+---------------------+------------+-----------+
| author_id | isbn_code_in_author | first_name | last_name |
+-----------+---------------------+------------+-----------+
|         1 |                   1 | CBD        | DCE       |
|         2 |                   1 | MLN        | NMO       |
|         3 |                   1 | MLN        | NMO       |
|         4 |                   1 | GFH        | HGI       |
|         5 |                   1 | FEG        | GFH       |
|         6 |                   1 | ONP        | POQ       |
|         7 |                   1 | VUW        | WVX       |
|         8 |                   1 | RQS        | SRT       |
|         9 |                   1 | GFH        | HGI       |
|        10 |                   1 | FEG        | GFH       |
|        11 |                   2 | FEG        | GFH       |
|        12 |                   2 | QPR        | RQS       |
|        13 |                   2 | HGI        | IHJ       |
|        14 |                   2 | LKM        | MLN       |
|        15 |                   2 | TSU        | UTV       |
|        16 |                   2 | MLN        | NMO       |
|        17 |                   2 | ONP        | POQ       |
|        18 |                   2 | GFH        | HGI       |
|        19 |                   2 | EDF        | FEG       |
|        20 |                   2 | POQ        | QPR       |
|        21 |                   3 | LKM        | MLN       |
|        22 |                   3 | VUW        | WVX       |
|        23 |                   3 | DCE        | EDF       |
|        24 |                   3 | ONP        | POQ       |
|        25 |                   3 | UTV        | VUW       |
|        26 |                   3 | DCE        | EDF       |
|        27 |                   3 | SRT        | TSU       |
|        28 |                   3 | IHJ        | JIK       |
|        29 |                   3 | NMO        | ONP       |
|        30 |                   3 | SRT        | TSU       |
|        31 |                   4 | RQS        | SRT       |
|        32 |                   4 | MLN        | NMO       |
|        33 |                   4 | RQS        | SRT       |
|        34 |                   4 | FEG        | GFH       |
|        35 |                   4 | HGI        | IHJ       |
|        36 |                   4 | EDF        | FEG       |
|        37 |                   4 | GFH        | HGI       |
|        38 |                   4 | VUW        | WVX       |
|        39 |                   4 | LKM        | MLN       |
|        40 |                   4 | SRT        | TSU       |

Folder structure here heirarchy

The source code can be downloaded here

Domain java files from hibernate mapping files

This post is related to the discussion on hibernate mappings below.
http://cuppajavamattiz.com/2012/01/20/hibernate-mappings-with-hbm-xml-files/
To take the discussion forward I have created two projects and I shall be dealing with each project in two separate posts.
This post is related to how the hbm2java task creates domain objects mapped to the database on the fly, from hbm.xml files.
The project structure on Eclipse looks like this:

<project>
     <generated/src>
          author.hbm.xml
          book.hbml.xml
          <com.mattiz.persistence.beans>
                 <classes generated by hbm2java.....>
                 BooksWithMultipleAuthors.java
                 ContributingAuthors.java
build.xml
hibernate.properties
log4j.properties
<classpath - jars>
      commons-collections.jar
      commons-logging.jar
      dom4j-1.6.1.jar
     freemarker.jar
     hibernate3.jar
     log4j-1.2.15.jar
     hibernate-annotation.jar
     xercesImpl.jar
     xml-apis.jar
     hibernate-tools.jar

build.xml

<?xml version="1.0" encoding="UTF-8"?>
<project default="codegen">
	<target name="codegen">
		<path id="classpath_id">
			<pathelement
				location="I:/>packages/spring-framework-2.5.4-with-dependencies/spring-framework-2.5.4/lib/jakarta-commons/commons-collections.jar" />
			<pathelement
				location="I:/>packages/spring-framework-2.5.4-with-dependencies/spring-framework-2.5.4/lib/jakarta-commons/commons-logging.jar" />
			<pathelement
				location="I:/>packages/spring-framework-2.5.4-with-dependencies/spring-framework-2.5.4/lib/dom4j/dom4j-1.6.1.jar" />
			<pathelement
				location="I:/>packages/spring-framework-2.5.4-with-dependencies/spring-framework-2.5.4/lib/freemarker/freemarker.jar" />
			<pathelement
				location="I:/>packages/spring-framework-2.5.4-with-dependencies/spring-framework-2.5.4/lib/hibernate/hibernate3.jar" />
			<pathelement
				location="I:/>packages/spring-framework-2.5.4-with-dependencies/spring-framework-2.5.4/lib/log4j/log4j-1.2.15.jar" />
			<pathelement
				location="I:/>packages/spring-framework-2.5.4-with-dependencies/spring-framework-2.5.4/lib/hibernate/hibernate-annotations.jar" />
			<pathelement location="I:/>packages/hibernate-tools.jar/hibernate-tools.jar" />
			<pathelement location="I:/>packages/hsqldb-1_8_0_10.jar" />
		</path>
		<echo>Zippzip</echo>
		<taskdef name="hibernatetool" classname="org.hibernate.tool.ant.HibernateToolTask">
			<classpath refid="classpath_id" />
		</taskdef>
		<hibernatetool destdir="generated/src">
			<configuration propertyfile="./hibernate.properties">
				<fileset dir=".">
					<include name="generated/src/*.hbm.xml" />
				</fileset>
			</configuration>
			<hbm2java />
		</hibernatetool>
	</target>
</project>

author.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 package="com.mattiz.persistence.beans">
	<class name="ContributingAuthor" table="Author" lazy="false">
		<id name="bookId" column="author_id" type="long">
			<generator class="native" />
		</id>
		<property name="firstName" type="string" length="20" column="first_name" />
		<property name="lastName" type="string" length="20" column="last_name" />
		<many-to-one name="bookContributedToByAuthor" column="isbn_code_in_author"
			class="BookWithMultipleAuthors" not-null="true" lazy="false" />
	</class>
</hibernate-mapping>

book.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 package="com.mattiz.persistence.beans">
	<class name="BookWithMultipleAuthors" table="Book" lazy="false">
		<id name="isbnCode" column="isbn_code" type="long">
			<generator class="native" />
		</id>
		<property name="title" type="string" length="20" column="book_title" />
		<set name="contributingAuthors" inverse="true" lazy="false">
			<key column="isbn_code_in_author" />
			<one-to-many class="ContributingAuthor" />
		</set>
	</class>
</hibernate-mapping>

hibernate.properties

hibernate.connection.driver_class=org.hsqldb.jdbcDriver
hibernate.connection.url=jdbc\:hsqldb\:hsql\://localhost
hibernate.connection.username=user
hibernate.connection.password=user
hibernate.connection.pool_size=2
hibernate.dialect=net.sf.hibernate.dialect.HSQLDialect

log4j.properties

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=warn, stdout
log4j.logger.net.sf.hibernate=info
### log just the SQL
log4j.logger.net.sf.hibernate.SQL=debug
### log JDBC bind parameters ###
log4j.logger.net.sf.hibernate.type=info
### log schema export/update ###
log4j.logger.net.sf.hibernate.tool.hbm2ddl=debug
### log cache activity ###
log4j.logger.net.sf.hibernate.cache=debug
### enable the following line if you want to track down connection ###
### leakages when using DriverManagerConnectionProvider ###
log4j.logger.net.sf.hibernate.connection.DriverManagerConnectionProvider=trace

When you run build.xml, the following two classes are generated by hbm2java utility

package com.mattiz.persistence.beans;

// Generated 31 Jan by Hibernate Tools 3.2.2.GA
import java.util.HashSet;
import java.util.Set;

/**
 * BookWithMultipleAuthors generated by hbm2java
 */
public class BookWithMultipleAuthors implements java.io.Serializable {
	private long isbnCode;
	private String title;
	private Set contributingAuthors = new HashSet(0);

	public BookWithMultipleAuthors() {
	}

	public BookWithMultipleAuthors(String title, Set contributingAuthors) {
		this.title = title;
		this.contributingAuthors = contributingAuthors;
	}

	public long getIsbnCode() {
		return this.isbnCode;
	}

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

	public String getTitle() {
		return this.title;
	}

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

	public Set getContributingAuthors() {
		return this.contributingAuthors;
	}

	public void setContributingAuthors(Set contributingAuthors) {
		this.contributingAuthors = contributingAuthors;
	}
}
package com.mattiz.persistence.beans;

// Generated 31 Jan by Hibernate Tools 3.2.2.GA
/**
 * ContributingAuthor generated by hbm2java
 */
public class ContributingAuthor implements java.io.Serializable {
	private long bookId;
	private String firstName;
	private String lastName;
	private BookWithMultipleAuthors bookContributedToByAuthor;

	public ContributingAuthor() {
	}

	public ContributingAuthor(BookWithMultipleAuthors bookContributedToByAuthor) {
		this.bookContributedToByAuthor = bookContributedToByAuthor;
	}

	public ContributingAuthor(String firstName, String lastName,
			BookWithMultipleAuthors bookContributedToByAuthor) {
		this.firstName = firstName;
		this.lastName = lastName;
		this.bookContributedToByAuthor = bookContributedToByAuthor;
	}

	public long getBookId() {
		return this.bookId;
	}

	public void setBookId(long bookId) {
		this.bookId = bookId;
	}

	public String getFirstName() {
		return this.firstName;
	}

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

	public String getLastName() {
		return this.lastName;
	}

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

	public BookWithMultipleAuthors getBookContributedToByAuthor() {
		return this.bookContributedToByAuthor;
	}

	public void setBookContributedToByAuthor(
			BookWithMultipleAuthors bookContributedToByAuthor) {
		this.bookContributedToByAuthor = bookContributedToByAuthor;
	}
}

Check this download for a similar app here

Or download source code here

Hibernate Mappings With hbm.xml Files

SCENARIO: Many authors contribute to one book

• Unidirectional associations – Many-to-one

create table Author ( author_id bigint not null primary key, book_id bigint not null, first_name varchar, last_name varchar )
create table Book ( book_id bigint not null primary key )

Author.book_id is foreign key from Book.

author.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 package="com.mattiz.persistence.beans">
	<class name="Author">
		<id name="authorid" column="author_Id" type="long">
			<generator class="native" />
		</id>
		<property name="firstName" type="string" length="20" column="first_name" />
		<property name="lastName" type="string" length="20" column="last_name" />
		<many-to-one name="book" column="book_Id" class="Book"
			not-null=”true” />
	</class>
</hibernate-mapping>

In the many-to-one tag the name is “book”, so that means that if you use a getter it would be author.getBook() or if you use HQL author.book.
The many to one tag implies that book_id is a foreign key for this relationship

book.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 package="com.mattiz.persistence.beans">
	<class name="Book">
		<id name="bookid" column="book_id" type="long">
			<generator class="native" />
		</id>
	</class>
</hibernate-mapping>
package com.mattiz.persistence.beans;

public class Author implements java.io.Serializable {
	private long authorid;
	private String firstName;
	private String lastName;
	private Book book;

	public Author() {
	}

	public Author(Book book) {
		this.book = book;
	}

	public Author(String firstName, String lastName, Book book) {
		this.firstName = firstName;
		this.lastName = lastName;
		this.book = book;
	}

	public long getAuthorid() {
		return this.authorid;
	}

	public void setAuthorid(long authorid) {
		this.authorid = authorid;
	}

	public String getFirstName() {
		return this.firstName;
	}

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

	public String getLastName() {
		return this.lastName;
	}

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

	public Book getBook() {
		return this.book;
	}

	public void setBook(Book book) {
		this.book = book;
	}
}
package com.mattiz.persistence.beans;

public class Book implements java.io.Serializable {
	private long bookid;

	public Book() {
	}

	public long getBookid() {
		return this.bookid;
	}

	public void setBookid(long bookid) {
		this.bookid = bookid;
	}
}


• Bidirectionality in Many to One

Bidirectional many-to-one

create table Author ( author_id bigint not null primary key, book_id  bigint not null, first_name varchar, last_name varchar )
create table Book ( book_id bigint not null primary key )

Author.book_id is foreign key from Book

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 package="com.mattiz.persistence.beans">
	<class name="Author">
		<id name="authorid" column="author_Id" type="long">
			<generator class="native" />
		</id>
		<property name="firstName" type="string" length="20" column="first_name" />
		<property name="lastName" type="string" length="20" column="last_name" />
		<many-to-one name="book" column="book_Id" class="Book"
			not-null="true" />
<!—book_id is FK in Author table from Book table->
	</class>
</hibernate-mapping>

book.hbml.xml

<hibernate-mapping package="com.mattiz.persistence.beans">
	<class name="Book">
		<id name="bookid" column="book_id" type="long">
			<generator class="native" />
		</id>
		<set name="authors" inverse="true"><!—book_id references column in Author table-->
			<key column="book_id" />
			<one-to-many class="Author" />
		</set>
	</class>
</hibernate-mapping>
package com.mattiz.persistence.beans;

public class Author implements java.io.Serializable {
	private long authorid;
	private String firstName;
	private String lastName;
	private Book book;

	public Author() {
	}

	public Author(Book book) {
		this.book = book;
	}

	public Author(String firstName, String lastName, Book book) {
		this.firstName = firstName;
		this.lastName = lastName;
		this.book = book;
	}

	public long getAuthorid() {
		return this.authorid;
	}

	public void setAuthorid(long authorid) {
		this.authorid = authorid;
	}

	public String getFirstName() {
		return this.firstName;
	}

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

	public String getLastName() {
		return this.lastName;
	}

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

	public Book getBook() {
		return this.book;
	}

	public void setBook(Book book) {
		this.book = book;
	}
}
package com.mattiz.persistence.beans;

import java.util.HashSet;
import java.util.Set;

public class Book implements java.io.Serializable {
	private long bookid;
	private Set authors = new HashSet(0);

	public Book() {
	}

	public Book(Set authors) {
		this.authors = authors;
	}

	public long getBookid() {
		return this.bookid;
	}

	public void setBookid(long bookid) {
		this.bookid = bookid;
	}

	public Set getAuthors() {
		return this.authors;
	}

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

If author in book is many-to-one, book to author is one- to-many and is a set.
The FK to author is the primary key in book.

From book.hbm.xml:

<set name="authors" inverse="true">
	<key column="book_id" />
	<one-to-many class="Author" />
</set>

Let’s consider

<key column=”book_id” />

in book.hbm.xml. Here the key book_id is in the other table, i.e. Author. So getAuthors() will use the book_id column (FK) in the Author table.
So Author has PK author_id and FK book_id while Book has PK book_id. This relationship gets the authors (looked up based on FK book_id) associated with that Book. So authors are looked up based on their FK which is book_id and you get multiple authors which is a set. Basically in a one to many the key has to be in the other table.
the fk in a many to one, the key is in this table
The underlying table structure has to match hibernate’s definition else it will give you a runtime exception.
When you see

<key> 

it means refer to the key in the table where it is an FK.

Here is a simplistic explanation of the references:

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 package="com.mattiz.persistence.beans">
	<class name="ContributingAuthor">
		<id name="id" column="id" type="long">
			<generator class="native" />
		</id>
		<property name="firstName" type="string" length="20" column="first_name" />
		<property name="lastName" type="string" length="20" column="last_name" />
		<many-to-one name="bookContributedToByAuthor" column="book_Id_in_Author"
			class="BookWithMultipleAuthors" not-null="true" />
	</class>
</hibernate-mapping>

book.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 package="com.mattiz.persistence.beans">
	<class name="BookWithMultipleAuthors">
		<id name="id" column="id" type="long">
			<generator class="native" />
		</id>
		<set name="contributingAuthors" inverse="true">
			<key column="book_Id_in_Author" />
			<one-to-many class="ContributingAuthor" />
		</set>
	</class>
</hibernate-mapping>

Generated classes:

package com.mattiz.persistence.beans;

import java.util.HashSet;
import java.util.Set;

public class BookWithMultipleAuthors implements java.io.Serializable {
	private long id;
	private Set contributingAuthors = new HashSet(0);

	public BookWithMultipleAuthors() {
	}

	public BookWithMultipleAuthors(Set contributingAuthors) {
		this.contributingAuthors = contributingAuthors;
	}

	public long getId() {
		return this.id;
	}

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

	public Set getContributingAuthors() {
		return this.contributingAuthors;
	}

	public void setContributingAuthors(Set contributingAuthors) {
		this.contributingAuthors = contributingAuthors;
	}
}
package com.mattiz.persistence.beans;

public class ContributingAuthor implements java.io.Serializable {
	private long id;
	private String firstName;
	private String lastName;
	private BookWithMultipleAuthors bookContributedToByAuthor;

	public ContributingAuthor() {
	}

	public ContributingAuthor(BookWithMultipleAuthors bookContributedToByAuthor) {
		this.bookContributedToByAuthor = bookContributedToByAuthor;
	}

	public ContributingAuthor(String firstName, String lastName,
			BookWithMultipleAuthors bookContributedToByAuthor) {
		this.firstName = firstName;
		this.lastName = lastName;
		this.bookContributedToByAuthor = bookContributedToByAuthor;
	}

	public long getId() {
		return this.id;
	}

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

	public String getFirstName() {
		return this.firstName;
	}

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

	public String getLastName() {
		return this.lastName;
	}

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

	public BookWithMultipleAuthors getBookContributedToByAuthor() {
		return this.bookContributedToByAuthor;
	}

	public void setBookContributedToByAuthor(
			BookWithMultipleAuthors bookContributedToByAuthor) {
		this.bookContributedToByAuthor = bookContributedToByAuthor;
	}
}

Executing a one-to-many book.getAuthors() is the equivalent of writing this sql
select * from t_author where book_id=? Where book_id is the FK in t_author
The book_id would have to be already present in book as a rule via referential integrity
Executing a many to one author.getBook() is the equivalent of writing this sql
select * from t_book where book_id = ? where the parameter in the last query would be from the author table; which would return one (obviously) since you are querying by PK.

• Unidirectional one to one

create table  Author( author_id  bigint not null primary key, book_id  bigint not null unique )
create table Book ( book_id bigint not null primary key )

A unidirectional one-to-one association on a foreign key is almost identical. The only difference is the column unique constraint.
Of course the underlying table structure has to match hibernate’s definition else it will give you a runtime exception.

create table Book ( isbn bigint not null primary key )
create table Author ( isbn bigint not null primary key )
<class name="Book">
<id name="id" column="isbn">
	<generator class="native" />
</id>
</class>
<class name="Author">
	<id name="id" column="isbn">
		<generator class="foreign">
			<param name="property">book</param>
		</generator>
	</id>
	<one-to-one name="book" constrained="true" />
</class>

There are two ways of doing a one-to-one, In the second option the two tables share the same id as the primary key which makes sense since it is a one to one. Both tables have isbn as primary key
One method is by sharing the primary key, the other method is by having a Primarykey and foreign key but enforcing uniqueness on the foreign key. Both isbn ids are generated so they must match, so you see only one has a native generator and the other has a ‘foreign’ generator meaning it relies on the first
If both generate separately they’d get out of synch. We only need to take away that there are two ways of defining a one-to-one
1. Sharing primary key – one table generates the primary key and the other one syncs with the first
2. The other option is to have a PK FK relationship but uniqueness enforced on the FK – so there will only be one.

One attribute that could be useful is the cascade attribute. In a one-to-many or many-to-one relation –
• cascade=”none” means that if saving or deleting first hibernate object has no affect on related objects.
• cascade=”save” means if first object is saved it automatically saves related objects.
• Similarly cascade = “delete” will delete related objects.
• cascade=”all” will save, delete, etc related objects even if they have FK constraints. Everything gets deleted, and hibernate takes care of that.

http://docs.jboss.org/hibernate/core/3.5/reference/en/html/associations.htmlhttp://ndpsoftware.com/HibernateMappingCheatSheet.html

Web Services and RESTFul Services

Q# Describe the structure of a SOAP request/ response

The soap request/ response consists of a SOAP envelope. The soap envelope contains the soap header and soap body. The SOAP header gives you an option of putting some stuff in that would be evaluated before the body is processed. The SOAP header may contain authentication information, namespace and method-name invoked, etc. Soap body may contain request and response content.
From
http://java.sun.com/developer/technicalArticles/xml/webservices/ #Message Format
SOAP performs operations in the context of a standardized message format. The primary part of this message has a MIME type of “text/xml” and contains the SOAP envelope. This envelope is an XML document. The envelope contains a header (optional) and a body (mandatory). The body part of the envelope is always intended for the final recipient of the message, while the header entries may target the nodes that perform intermediate processing, such as endpoint. Attachments, binary or otherwise, may be appended to the body.
..
Headers, for example, may be used to provide digital signatures for a request contained in the body. In this circumstance, an authentication or authorization server could process the header entry — independent of the body — stripping out information to validate the signature. Once validated, the rest of the envelope would be passed on to the SOAP server, which would process the body of the message.

Q# How do you authenticate a SOAP request?

I have used weblogic.xml.crypto.wss.provider.CredentialProvider to set the user credentials that will be added to the request header after encryption. This information is stripped from the soap header to authenticate the request. The authorization data is passed to the server through the request header each and every time a request is made. The authorization policy is defined in an xml file that is kept in the META-INF folder of the SOAP war/ ear file. The policy.xml says that user should always send username/ password token. The request should then always contain username/ password token.
We implemented “Standard Web Services Security” using username and password tokens passed in the soap header and a policy xml was deployed on the server which executed an EJB that did authentication.
The method itself was exposed as a webservice using annotations in the javax.jws package which is implemented in weblogic jar. Also jboss-ejb3.jar.

Describe how you have created various web services

In one of our previous project we used ejb3 annotations to expose ordinary pojo methods with annotations such as

@WebService(serviceName = "SomeService", portName = "SomeServicePort", targetNamespace = "http://mattiz.com/calculateInterest")

which seems to be in the import javax.jws.WebService; package of weblogic.jar.
The wsdl was automatically created and client stubs were generated using the ant clientgen task.
http://java.sun.com/developer/technicalArticles/J2SE/jax_ws_2/ is a rather a simplistic introduction, but similar to one described above.
In another project we created the wsdl manually and generated stubs using something like wsconsume ant task. The generated stubs are used both client side and server side.

Q# What is the difference between restful services and soap?

From here http://stackoverflow.com/questions/19884295/soap-vs-rest-differences
REST is an architecture. REST is not restricted to HTTP alone. It can use any protocol that follows the URI scheme. SOAP on the other hand uses HTTP alone. The consumer need not know a lot about the services exposed by the Rest service provider. In case of SOAP any undocumented change on either server or client side will break the communication. i.e. Web Service client and server are more tightly coupled than REST. The soap client requires detailed previous knowledge of the web service provider. However, once the entry point is known in REST, the resources are supposed to return links that the client can follow. Rest has a much simpler request and can use JSON as well as XML. It does not have the soap envelope and the headers and can be used for protocols that don’t support these.

From my brief reading, it looks like the main difference between SOAP and RESTful webservices is :
* SOAP exposes a function (or a method call) as an HTTP web service. The method can contain complex business logic etc.
* RESTful web service provides pieces of data as an HTTP web service. Think of RESTful web service as exposing a bunch of getter methods as webservice. The client can invoke the getter functions to retrieve pieces of data and then do what it pleases with the retrieved data. The restful web service provides data similar to how a database would provide data. Each invocation is very light since the web service provider doesn’t have any logic. It just retrieves and sends data.
I found this article useful http://137.254.16.27/enterprisetechtips/entry/implementing_restful_web_services_in
“Instead of providing just one endpoint for a particular web service and having that endpoint perform various operations, you provide access to resources.” So the soap web service client can be thin – service provider has lot of logic and data access and does lot of work while in RESTful web service, the provider is very thin – just provides resources (e.g. data). The client can do whatever it likes with the data – complex logic etc. So thin server/ thick client model is implemented and separate uri’s for each resource (or piece of data) are in place. RESTful services looks different from SOAP. SOAP has a method call which takes params and returns params while RESTful service just has separate uri’s for each resource (piece of data).
Here’s an example of how a RESTful service would look different from soap:
A soap service could expose a service that looks like this String doComplexStuff(param1, param2, param3, param4) while a RESTful service would look like this http://blah/resource/param1, http://blah/resource/param12 where it is just giving the values asked for and the RESTful service will return param1 and param12 without doing complex processing.
The difference is not whether “light” or “heavy”; the difference is whether you are executing a method call or getting access to resources.Typically RESTful services are supposed to be “light” without complex logic though that’s not to say that it can’t access the db or that it can’t use hibernate.
Restful service provider can use any technique to provide access to resources. The “resource” could be a value retrieved from db using hibernate, DTO, or anything else. For example the client may ask for all a list of DTOs and is returned list of DTOs; its just getting a resource or a list of resources. You can access db resources and return a dto or list of dtos and that would still be RESTful. The difference between SOAP and RESTful services is whether you are exposing a method or exposing your resources. Restful means simply access to resources. You can ignore how the RESTful service is implemented, just focus on the interface exposed to the client. Soap service looks like this – String doComplexStuff(param1, param2, param3, param4) while RESTful service looks like this
http://blah/resource/param1
http://blah/resource/param
It exposes multiple URI’s each URI exposing a single resource. For soap, each url would expose a method that performs some complex task and it’s not just exposing a resource. The difference is philosophical more of a design difference. We can use one technology on one end of a RESTful service and another at the consumer side, its just like a soap webservice – the mechanism is the same.

https://www.upwork.com/hiring/development/soap-vs-rest-comparing-two-apis/

Because SOAP is a protocol, and REST is an architectural style. SOAP is its own protocol, and is a bit more complex by defining more standards than REST—things like security and how messages are sent. For many of the reasons SOAP is a good choice rarely apply to web services scenarios, which make it more ideal for enterprise-type situations that require more comprehensive features in the way of security, transactions, and ACID (Atomicity, Consistency, Isolation, Durability) compliance.
SOAP is a protocol. REST is an architectural style. An API is designed to expose certain aspects of an application’s business logic on a server, and SOAP uses a service interface to do this while REST uses URIs.
REST APIs access a resource for data (a URI); SOAP APIs perform an operation. REST is an architecture that’s more data-driven; SOAP is a standardized protocol for transferring structured information that’s more function-driven.
REST permits many different data formats including plain text, HTML, XML, and JSON, which is a great fit for data and yields more browser compatibility; SOAP only uses XML.
Security is handled differently. SOAP supports WS-Security, which is great at the transport level and a bit more comprehensive than SSL, and more ideal for integration with enterprise-level security tools. Both support SSL for end-to-end security, and REST can use the secure version of the HTTP protocol, HTTPS.
SOAP requires more bandwidth; REST requires fewer resources (depending on the API). There’s a little more overhead with SOAP out of the gate, on account of the envelope-style of payload transport. Because REST is used primarily for web services, its being lightweight is an advantage in those scenarios.
REST calls can be cached, SOAP-based calls cannot be cached. Data can be marked as cacheable, which means it can be reused by the browser later without having to initiate another request back to the server. This saves time and resources.
An API is built to handle your app’s payload, and REST and SOAP do this differently. A payload is data sent over the internet, and when a payload is “heavy,” it requires more resources. REST tends to use HTTP and JSON, which lighten the payload; SOAP relies more on XML.
SOAP is tightly coupled with the server; REST is coupled to a lesser degree. In programming, the more layers of abstraction between two pieces of technology, the less control you have over their interaction, but there’s also less complexity and it’s easier to make updates to one or the other without blowing up the whole relationship. The same goes for APIs and how closely they interact with a server. This is a key difference between SOAP and REST to consider. SOAP is very closely coupled with the server, having a strict communication contract with it that makes it more difficult to make changes or updates. A client interacting with a REST API needs no knowledge of the API, but a client interacting with a SOAP API needs knowledge about everything it will be using before it can even initiate an interaction.

Q# What is the difference between JAX-WS, JAX-RS,JAX-RPC and what is JAX-B?

From http://www.ibm.com/developerworks/webservices/library/ws-tip-jaxwsrpc/index.html
Web services have been around a while now. First there was SOAP. JAX-rpc
The industry was not merely doing RPC web services, they were also doing message-oriented web services. So “RPC” was removed from the name and replaced with “WS” (for web Services). Thus the successor to JAX-RPC 1.1 is JAX-WS 2.0 – the Java API for XML-based web services.
What is different between JAX-rpc and JAX-ws?
JAX-RPC and JAX-WS support SOAP 1.1. JAX-WS also supports SOAP 1.2.
The WSDL 1.1 specification defined an HTTP binding, which is a means by which you can send XML messages over HTTP without SOAP. JAX-RPC ignored the HTTP binding. JAX-WS adds support for it.
JAX-RPC maps to Java 1.4. JAX-WS maps to Java 5.0. JAX-WS relies on many of the features new in Java 5.0.
Java EE 5, the successor to J2EE 1.4, adds support for JAX-WS, but it also retains support for JAX-RPC, which could be confusing to today’s web services novices.
JAX-RPC has its own data mapping model, which covers about 90 percent of all schema types. Those that it does not cover are mapped to javax.xml.soap.SOAPElement.
JAX-WS’s data mapping model is JAXB. JAXB promises mappings for all XML schemas.
JAX-WS’s dynamic client model is quite different from JAX-RPC’s. Many of the changes acknowledge industry needs:
It introduces message-oriented functionality.
It introduces dynamic asynchronous functionality.
JAX-WS also adds a dynamic server model, which JAX-RPC does not have.
JAX-RPC handlers rely on SAAJ 1.2. JAX-WS handlers rely on the new SAAJ 1.3 specification.

Differences: JAX-RS and JAX-WS; and why JAX-RS is preferrred in modern web applications

Soap is service based while REST is resource based and lighter with less overhead since it doesn’t include authentication, security, transaction, message types and ACID (Atomicity, Consistency, Isolation, Durability) by defining more standards. Soap is resource intensive on the client side(thin client) while REST isn’t which makes REST useful on devices such as mobile phones. Rest is the preferred web service.

REST is particularly useful for limited-profile devices, such as PDAs and mobile phones. It’s not that JSON is so significantly smaller than XML by itself. It’s mostly that JAX-WS specification includes lots overhead in how it communicates. On the point about WSDL and API definitions, REST will more frequently use the URI structure and HTTP commands to define the API rather than message types, as is done in the JAX-WS. This means that you don’t need to publish a WSDL document so that other users of your service can know how to talk to your service. With REST you will still need to provide some documentation to other users about how the REST service is organized and what data and HTTP commands need to be sent. JAX-RS refers to Rest services while JAX-WS is related to web services.

Q# What web services have you used?
Lately I have used Apache CXF with Spring for creating WebServices using annotations – bottom up. Prior to this I used the EJB3 web services using annotations – bottom up. Apache Axis for both bottom up and top down web service creation. Top-down means you start with a WSDL and then create all the necessary scaffolding in Java all the way down. Bottom-up means you start with a Java method, and generate the WSDL from it.