One to many relationship example using Hibernate – Step by Step Instruction

One to many relationship example using Hibernate

One to many relationship using Hibernate can be super useful for any practical purposes. Here are step by step instructions on how to do the same:
In this example There is a one to many relationship between User and User Purchase.
1. Create User Table

	CREATE DATABASE IF NOT EXISTS training; 
	CREATE TABLE IF NOT EXISTS
	training.User ( id INT NOT NULL AUTO_INCREMENT , 
	username VARCHAR(250) NOT NULL , 
	password VARCHAR(250) NOT NULL , 
	email_address VARCHAR(250) NULL ,
	PRIMARY KEY (id) , UNIQUE INDEX
	username_UNIQUE (username ASC) );

2. Create User Purchase Table

	CREATE TABLE `training`.`user_purchase` (
		  `iduser_purchase` INT NOT NULL,
		  `user_id` INT NULL,
		  `item` VARCHAR(45) NULL,
		  `price` FLOAT NULL,
		  PRIMARY KEY (`iduser_purchase`),
		  INDEX `user_id_idx` (`user_id` ASC),
		  CONSTRAINT `user_id`
		    FOREIGN KEY (`user_id`)
		    REFERENCES `training`.`User` (`id`)
		    ON DELETE CASCADE
		    ON UPDATE CASCADE);

3. Create UserPurchase Class

package com.st.model;


public class UserPurchase {
	private Integer purchaseId;
	private User user;
	private float price;
	private String item;

	public Integer getPurchaseId() {
		return purchaseId;
	}

	public void setPurchaseId(Integer purchaseId) {
		this.purchaseId = purchaseId;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public float getPrice() {
		return price;
	}

	public void setPrice(float price) {
		this.price = price;
	}

	public String getItem() {
		return item;
	}

	public void setItem(String item) {
		this.item = item;
	}
}

4. Create User Class

package com.st.model;

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

/**
@author asinha
 *
 */
public class User {
	private int id;

	private String emailAddress;
	private String username;
	private String password;
	
	//Create a new variable to indicate collection of UserPurchase
	//This shows one to many relationship between User and UserPurchase
	private Set userPurchases = new HashSet();
	
	

	public int getId() {
		return id;
	}

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

	public String getEmailAddress() {
		return emailAddress;
	}

	public void setEmailAddress(String emailAddress) {
		this.emailAddress = emailAddress;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Set getUserPurchases() {
		return userPurchases;
	}

	public void setUserPurchases(Set userPurchases) {
		this.userPurchases = userPurchases;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", emailAddress=" + emailAddress + ", username=" + username + ", password=" + password
				+ "]";
	}

}

4. Create user-purchase.hbm.xml

<!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.st.model.UserPurchase" table="user_purchase">
		<id name="purchaseId" column="iduser_purchase">
			<generator class="increment" />
		</id>

		<property name="price" type="float" column="price"></property>
		<property name="item" type="string" column="item"></property>
		
		<many-to-one name="user" class="com.st.model.User"
			fetch="select">
			<column name="user_id" not-null="true" />
		</many-to-one>

	</class>
</hibernate-mapping>

4. Create user.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!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.st.model.User" table="User">
		<id name="id">
			<generator class="increment" />
		</id>

		<property name="username" type="string" column="username"></property>
		<property name="password" type="string" column="password"></property>
		<property name="emailAddress" type="string" column="email_address"></property>
		
		<set name="userPurchases" table="user_purchase" inverse="true"
			lazy="true" fetch="select">
			<key>
				<column name="id" not-null="true" />
			</key>
			<one-to-many class="com.st.model.UserPurchase" />
		</set>
		
	
	</class>
</hibernate-mapping>

4. Update hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration
    PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<!--<property name="connection.url">jdbc:mysql://localhost:3306/sansa_ads</property> -->
		<property name="connection.url">jdbc:mysql://localhost:3306/training</property>
		<property name="connection.username">root</property>
		<property name="connection.password">password</property>
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
		<!-- thread is the short name for org.hibernate.context.ThreadLocalSessionContext 
			and let Hibernate bind the session automatically to the thread -->
		<property name="current_session_context_class">thread</property>

		<!-- this will show us all sql statements -->
		<property name="hibernate.show_sql">true</property>

		<!-- mapping files -->


		<mapping resource="user.hbm.xml" />
		<mapping resource="user-purchase.hbm.xml" />



	</session-factory>
</hibernate-configuration>

4. Create a method in UserDAO Class

package com.st.dao;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.st.model.SocialClub;
import com.st.model.User;
import com.st.model.UserPurchase;

public class UserDAO {

	static Session session;

	static void createSession() {
		SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
		session = sessionFactory.openSession();
	}


	public static boolean testCreateOneToMany() {
		boolean status = false;
		createSession();
		
		Transaction tx = session.beginTransaction();
		
		User user = new User();

		user.setEmailAddress("a@apple.com2");
		user.setUsername("a_user2");
		user.setPassword("a_pass2");
		session.save(user);
		
		UserPurchase userPurchase = new UserPurchase();
		userPurchase.setItem("Iphone");
		userPurchase.setPrice(695.00f);
		
		userPurchase.setUser(user);
		user.getUserPurchases().add(userPurchase);
		session.save(userPurchase);
		
		
		tx.commit();
		status = true;

		return status;

	}
	
	public static void main(String[] args) {


		testCreateOneToMany();

	}

}

10. That’s it. You should see an output like below to show that data has been inserted in the tables

Hibernate: select max(id) from User2
Hibernate: select max(iduser_purchase) from user_purchase
Hibernate: insert into User2 (username, password, email_address, id) values (?, ?, ?, ?)
Hibernate: insert into user_purchase (price, item, user_id, iduser_purchase) values (?, ?, ?, ?)

Also, Verify this in the database using a tool such as MySQL Workbench:

SELECT * FROM training.user_purchase;
'1','6','Iphone','695'

Advertisements

About sansatechnology

Sansa Technology is an IT staffing, Consulting and Training company located in the heart of Silicon Valley. If you are a consultant looking for your new gig, send us your resume to us. If you are looking for training in the field of White Box Testing, Java, Java EE, Selenium, DevOps, Android and others, connect with us as well. Visit us at www.sansatechnology.com or email contact@sansatechnology.com
This entry was posted in Coding Challenges, Computers and Internet, Interview Preparation, IT Jobs and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s