Hie guys, Iam developing a java web application which uses mysql as its database engine. Now I would like to use the hibernate and spring frameworks together. The problem I nam facing is in configuring the various beans and establishing a clear relationship btwn the two frame works. If any one has ever done a project with the two frameworks integrated pliz help me. All I need is a small working example that will definitel take me thru.
Help guys Iam stuck.
Thanks.

Recommended Answers

All 5 Replies

you should go to the springframework.org forum you'd get more help there you can also check the spring reference book its very lucid

check your struts-config.xml file and hibernate-cfg.xml file for correct enteries. If you have some other problem, please be more descriptive.

he is using springframework and not struts; you don't get any struts-config.xml file. What you get is a spring bean definition file. for more information on spring development visit http://www.springsource.org/documentation.

don't know if you would understand but I'll give it to you anyway. in the next post you will find two classes User and Address their hibernate config files and their spring bean difinition.

This is the address class with its hibernate config

public class User {
	private Long id;
	private String username;
	private String password;
	private String email;
	private Set<String> userRoles;
	private Date dob;
	private Address address;
	private boolean enabled;
	private String gender;
	private Orientation orientation;
	
	public User(){
		
	}

	public Long getId() {
		return id;
	}

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

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		if(username == null || username.equals(""))
			throw new IllegalArgumentException("username is a required field");
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		if(password == null || password.equals(""))
			throw new IllegalArgumentException("password is a required field");
		this.password = password;
	}


	public Set<String> getUserRoles() {
		return userRoles;
	}

	public void setUserRoles(Set<String> userRoles) {
		this.userRoles = userRoles;
	}

	public Date getDob() {
		return dob;
	}

	public void setDob(Date dob) {
		if(dob == null){
			throw new IllegalArgumentException("Date of Birth is a requried field");
		}
		this.dob = dob;
	}

	public Address getAddress() {
		return address;
	}

	public void setAddress(Address address) {
		this.address = address;
	}
	
	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	
	public boolean isEnabled() {
		return enabled;
	}

	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public Orientation getOrientation() {
		return orientation;
	}

	public void setOrientation(Orientation orientatoin) {
		this.orientation = orientatoin;
	}

	public boolean isNullUser(){
		boolean isNullUser = false;
		
		isNullUser = (username == null || username.equals("")) || (password == null || password.equals(""))
						|| (email == null || email.equals("")) || userRoles == null && address == null
						|| dob == null;
		
		return isNullUser;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((email == null) ? 0 : email.hashCode());
		result = prime * result
				+ ((username == null) ? 0 : username.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		User other = (User) obj;
		if (email == null) {
			if (other.email != null)
				return false;
		} else if (!email.equals(other.email))
			return false;
		if (username == null) {
			if (other.username != null)
				return false;
		} else if (!username.equals(other.username))
			return false;
		return true;
	}
	
	public String toString(){
		return id + " " + username + " " + email + " " + userRoles + " " + gender + " " + orientation;
	}
	
	
	

}
<?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="uk.co.datingalley.domain">
  <class name="User">
  	<id name="id" column="USER_ID">
  		<generator class="native"/>
  	</id>
  	
  	<property name="username"  not-null="true"/>
  	
  	<property name="password" not-null="true"/>
  	
  	<property name="email" not-null="true"/>
  	
  	<property name="dob" type="date" not-null="true" />
  	
  	<set name="userRoles" lazy="true" table="USER_ROLES">
  		<key column="USER_ID"/>
  		<element type="string" column="USER_ROLE" not-null="true" />
  	</set>
  	
  	<property name="gender" not-null="true"/>
  	
  	<property name="enabled" not-null="true" />
  	
  	<component name="orientation">
  		<property name="lookingFor" />
  		<property name="minAge" />
  		<property name="maxAge" />
  	</component>
  	
  	<many-to-one name="address" class="Address" column="ADDRESS_ID" cascade="all" />
  	
  </class>
</hibernate-mapping>

next the Address class

public class Address {
	public Long id;
	public String street;
	public String town;
	public String county;
	public String postcode;
	public String country;
	
	public Address(){
		
	}

	public String getStreet() {
		return street;
	}

	public void setStreet(String street) {
		this.street = street;
	}

	public String getTown() {
		return town;
	}

	public void setTown(String town) {
		this.town = town;
	}

	public String getCounty() {
		return county;
	}

	public void setCounty(String county) {
		this.county = county;
	}

	public String getPostcode() {
		return postcode;
	}

	public void setPostcode(String postcode) {
		if(postcode == null || postcode.equals(""))
			throw new IllegalArgumentException("postcode is a required field");
		this.postcode = postcode;
	}

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}

	public Long getId() {
		return id;
	}

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

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((postcode == null) ? 0 : postcode.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Address other = (Address) obj;
		if (postcode == null) {
			if (other.postcode != null)
				return false;
		} else if (!postcode.equals(other.postcode))
			return false;
		return true;
	}
	

}

its hibernate config

<?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="uk.co.datingalley.domain">
  <class name="Address">
  	
  	<id name="id" column="ADDRESS_ID">
  		<generator class="native"/>
  	</id>
  	
  	<property name="street"/>
  	
  	<property name="town"/>
  	
  	<property name="county"/>
  	
  	<property name="postcode"/>
  	
  	<property name="country" /> 	
  </class>
</hibernate-mapping>

To configure Hibernate with spring you have to create a DAO object to retrieve User and address from the database. below is the Hibernate DAO code for the above classes

public class HibernateUserDAO extends HibernateDaoSupport implements UserDAO {

	public void createUser(User user) throws DAOException {
		if(user == null){
			throw new NullUserException();
		}
		if(user.isNullUser()){
			throw new NullUserException();
		}
		checkForDuplicateInfo(user);	// check for exiting username and email address
		
		getHibernateTemplate().saveOrUpdate(user);
	}

	public User getUser(String username, String password) {
		List result = getHibernateTemplate().find("from User where username = ? and password = ?", 
				new Object[]{username, password});
		return result.size() > 0 ? (User) result.get(0) : null;
	}

	public List<User> getUsers() {
		return getHibernateTemplate().find("from Users");
	}

	public void removeUser(User user) throws DAOException {
		getHibernateTemplate().delete(user);

	}
	
	public void checkForDuplicateInfo(User user){
		// check for existing username
		List result = getHibernateTemplate().find("from User where username = ?",user.getUsername());
		if(result.size() > 0){
			throw new UsernameExistException();
		}
		
		// check for existing email address
		result = getHibernateTemplate().find("from User where email = ?", user.getEmail());
		
		if(result.size() > 0){
			throw new EmailExistException();
		}
	}
	
	public void checkForDuplicateUsername(String username){
		// check for existing username
		List result = getHibernateTemplate().find("from User where username = ?",username);
		if(result.size() > 0){
			throw new UsernameExistException();
		}
	}
	
	public void checkForDuplicateEmail(String email){
		List result = getHibernateTemplate().find("from User where email = ?", email);
		
		if(result.size() > 0){
			throw new EmailExistException();
		}
	}

}

next configure hibernate in spring with the following description

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">	
		<!--  external configuration properties -->
		<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
			<!--property name="location" value="C:\Documents and Settings\Josiah\workspace\datingalley\WebContent\WEB-INF\hibernate.properties"/-->
			<property name="location" value="/WEB-INF/hibernate.properties"/>
		</bean>

		<!-- Configure JDBC Data source -->
		<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
			<property name="driverClassName" value="${hibernate.connection.driver_class}"/>
			<property name="url" value="${hibernate.connection.url}" />
			<property name="username" value="${hibernate.connection.username}"/>
			<property name="password" value="${hibernate.connection.password}" />
		</bean>
		
		<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
			<property name="sessionFactory" ref="sessionFactory" />
		</bean>
		
		<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
			<property name="dataSource" ref="dataSource" />
			<property name="mappingLocations">
			 	<list>
			 		<value>\WEB-INF\classes\uk\co\datingalley\domain\Address.hbm.xml</value>
			 		<value>\WEB-INF\classes\uk\co\datingalley\domain\User.hbm.xml</value>
			 	</list>
			</property>
			<property name="hibernateProperties">
				<props>
					<prop key="hibernate.dialect">${hibernate.dialect}</prop>
					<prop key="hibernate.query.substitutions">${hibernate.query.substitutions}</prop>
					<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
					<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
					<!--prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop-->
				</props>
			</property>
		</bean>
		
		<bean id="userDAO" class="uk.co.datingalley.dao.HibernateUserDAO">
			<property name="hibernateTemplate" ref="hibernateTemplate"/>
		</bean>
</beans>

Easy right :D

commented: Nice example +4
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.