Hibernate ORM – Quick Start

Saving information to database is an extremely important task which almost every more advanced applications need to do. There are many solutions that allow us to achieve this, however still most common is used relational databases with SQL language. One of most popular solutions for web applications written in Java is Hibernate framework.


 
Hibernate ORM is a framework that allows mapping Java objects to relational tables in the database. Hibernate works on the basis of the JDBC API. With it we don’t have to make multiple repetitions of the same code. It helps with all operations related to database management which makes programming easier and faster.
 
In the following tutorial will be shown how to configure hibernate with our project. How to create one to one, one to many and many to many relationship . Will be present basics HQL queries. All examples will be made by use of annotations
 
To create our application we will need a few things. Those are the appropriate librarys which we can download using Maven, hibernate configuration file. Corresponding tables created in the database, POJO class which will map objects stored in the database and source code. So let’s get to work.
 
At the beginning let’s create Maven project and download necessary libraries:
 

<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.binaryalchemist</groupId>
	<artifactId>killer_robot</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>killer_robot Maven Webapp</name>
	<url>https://maven.apache.org</url>
	<dependencies>

			<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<scope>provided</scope>
			<version>3.1.0</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
			<version>2.3.1</version>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>javax.servlet.jsp.jstl</groupId>
			<artifactId>javax.servlet.jsp.jstl-api</artifactId>
			<version>1.2.1</version>
			<scope>compile</scope>
		</dependency>

		<dependency>
			<groupId>org.glassfish.web</groupId>
			<artifactId>javax.servlet.jsp.jstl</artifactId>
			<version>1.2.2</version>
			<scope>compile</scope>
			<exclusions>
				<exclusion>
					<groupId>javax.servlet</groupId>
					<artifactId>servlet-api</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.servlet.jsp</groupId>
					<artifactId>jsp-api</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.servlet.jsp.jstl</groupId>
					<artifactId>jstl-api</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>javax.el</groupId>
			<artifactId>javax.el-api</artifactId>
			<version>3.0.0</version>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>org.eclipse.persistence</groupId>
			<artifactId>javax.persistence</artifactId>
			<version>2.1.0</version>
			<scope>compile</scope>
		</dependency>

		<dependency>
			<groupId>javax.transaction</groupId>
			<artifactId>javax.transaction-api</artifactId>
			<version>1.2</version>
			<scope>compile</scope>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>4.3.1.Final</version>
			<scope>runtime</scope>
			<exclusions>
				<exclusion>
					<groupId>org.hibernate.javax.persistence</groupId>
					<artifactId>hibernate-jpa-2.1-api</artifactId>
				</exclusion>
				<exclusion>
					<groupId>org.jboss.spec.javax.transaction</groupId>
					<artifactId>jboss-transaction-api_1.2_spec</artifactId>
				</exclusion>
				<exclusion>
					<groupId>xml-apis</groupId>
					<artifactId>xml-apis</artifactId>
				</exclusion>
				<exclusion>
					<groupId>org.jboss.logging</groupId>
					<artifactId>jboss-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

		<dependency>
			<groupId>org.jboss.logging</groupId>
			<artifactId>jboss-logging</artifactId>
			<version>3.1.4.GA</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.6</version>
		</dependency>

		
	</dependencies>
	<build>
		<finalName>killer_robot</finalName>
		<plugins>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<configuration>
					<webXml>src\main\webapp\WEB-INF\web.xml</webXml>
				</configuration>

			</plugin>

		</plugins>

	</build>
</project>

Libraries associated with Hibernate starts from org.eclipse.persistence earlier libraries can be useful to us if we create web-based application.
 
To connect our application to database, it is necessary to create a configuration hibernate.cfg.xml file in the folder src/main/ resources. Configuration file may look like this:
 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"	"https://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/robot</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>

<property name="show_sql">true</property>
<property name="format_sql">true</property>

<mapping class="com.binaryalchemist.killer_robot.KillerRobot"/>

</session-factory>

</hibernate-configuration>

 

First parameters are responsible for the configuration and connection to the database. We give here information about which database we use (in my case MySQL) address of our database (localhost:3306/robot) username and password. Another parameters allow us to show the results o hibernate actions on console. At the end there is important line “” which is used to map our class to relational table. Thanks to this maping hibernate knows how to turn class into an object in the database. Here we have mapped class KillerRobot which will be created in next steps.
 

So let us create table representing our terminator type robot:
 

create table robot
(
robot_id int NOT NULL AUTO_INCREMENT,
name varchar(255),
serial varchar(255),
time datetime,
constraint primary key(robot_id)
)

 
If you know SQL there should be nothing extraordinary in above code. Another thing we need to do is create a Java class that reflects the same object. So let us create the following class KillerRobot.
 

@Entity
@Table(name="robot")
public class KillerRobot{

	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	@Column(name = "robot_id", unique = true, nullable = false)
	private long id;
	
	@Column(name = "name", unique = false, nullable = true)
	private String name;
	
	@Column(name = "serial", unique = false, nullable = true)
	private String serial;
	
	@Column(name = "time", unique = false, nullable = true)
	private Date productionTime;
	
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSerial() {
		return serial;
	}
	public void setSerial(String serial) {
		this.serial = serial;
	}
	public Date getProductionTime() {
		return productionTime;
	}
	public void setProductionTime(Date productionTime) {
		this.productionTime = productionTime;
	}

}

@Entity annotation tells us that this is object that we want to map to the database table. @Table, along with the parameter name informs on what tables we project our object. In our case it is a newly created table robot. Each robot has its own identification number. We wish, however, that the number was generated automatically so we use the annotation @GeneratedValue(strategy = GenerationType.IDENTITY)
GenericGenerator is responsible for strategy in which our number is generated. Each of the columns can be individually configured, so hibernate will know which variable corresponds to the values in the table. But this is not necessary if our variables have the same name as variables in the table.
 
Let’s create class DbConnection which will be responsible for loading Hibernate configuration file and managing session:
 

public class DBConnection {

	private static SessionFactory factory;

	static {
		Configuration cfg = new Configuration();
		cfg.configure("Hibernate.cfg.xml");

		ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties())
				.build();

		factory = cfg.buildSessionFactory(serviceRegistry);
	}

	public static Session getSession() {
		return factory.openSession();
	}

	public void doWork() {}

	public static void close() {
		factory.close();
	}

}

At the end of the introduction What remains is to finally use everything to save our robot in to database:
 

@WebServlet(
name="robotservlet",
urlPatterns={"/robot","/" })
public class KillerRobotServlet extends HttpServlet {
	
	public KillerRobotServlet() {
		super();
	}
	
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		KillerRobot robi = new KillerRobot();
		robi.setName("Bob");
		robi.setProductionTime(new Date());
		robi.setSerial("AX7N41S");
		
		Session session = DBConnection.getSession();
		session.beginTransaction();
		session.save(robi);
		session.getTransaction().commit();
		DBConnection.close();
		
		request.getRequestDispatcher("/index.jsp").forward(request, response);
	}
	
}

Code here is relatively simple. We create our robot and save it in the session. Default hibernate operations are carried out using transactions. That’s why we can’t ignore session.beginTransaction function(); which begins transactions and session.getTransaction().commit(); which approves the transaction. Since we already know the basics we can move on to one to one relationship.
 

One to one relationship Hibernate:

Each robot must be created by someone. So let’s assume that we want to store informations about the manufacturer of robot in one to one relationship.
 
At the begining, let’s create table company:
 

create table company
(
robot_id int NOT NULL,
name varchar(255),
adress text,
webpage text,
founded datetime,
constraint primary key(robot_id),
CONSTRAINT company_user_fk FOREIGN KEY(robot_id) REFERENCES robot(robot_id)
)

 
 
Same way as before we create a Company class:
 

@Entity
@Table(name="company")
public class Company{

	@Id
	@Column(name="robot_id", unique=true, nullable=false)
	@GeneratedValue(generator="generator")
	@GenericGenerator(name="generator", strategy="foreign", parameters = @Parameter(name = "property", value = "robot"))
    private long robot_id;
	private String name;
	private String adress;
	private String webpage;
	private Date founded;
	
	@OneToOne(mappedBy="company", cascade=CascadeType.ALL, fetch = FetchType.LAZY)
	private KillerRobot robot;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAdress() {
		return adress;
	}
	public void setAdress(String adress) {
		this.adress = adress;
	}
	public String getWebpage() {
		return webpage;
	}
	public void setWebpage(String webpage) {
		this.webpage = webpage;
	}
	public Date getFounded() {
		return founded;
	}
	public void setFounded(Date founded) {
		this.founded = founded;
	}
	public KillerRobot getRobot() {
		return robot;
	}
	public void setRobot(KillerRobot robot) {
		this.robot = robot;
	}
	public long getRobot_id() {
		return robot_id;
	}
	public void setRobot_id(long robot_id) {
		this.robot_id = robot_id;
	}	
}

You can notice here two differences. The first is annotation for generating identification number. As the ID number will be taken from robot table and will not be generated automatically. Therefore, we use foreign strategy and as a parameter we indicate robot table. @GeneratedValue (generator = “generator”)
@GenericGenerator (Name = “generator”, strategy = “foreign”, parameters = @Parameter (name = “property” value = “robot”))
 

The second important part is annotation @OneToOne (mappedBy = “company”, cascade = CascadeType.ALL, fetch = FetchType.LAZY)
Annotation @OneToOne tells us that classes are in one-to-one relationship and must be preceded before the object to which it refers. In this case it’s class KillerRobot. MappedBy parameter value is the same as the variable name stored in class KillerRobot. cascade = CascadeType.ALL tells us that in the case of updating or removing data we also update this object. Fetch tells us how to download data from the database. It may have value LAZY then data stored in object are retrieved when they are needed or EAGER then data is retrieved immediately.
 
Annotation @OneToOne must also be written in the KillerRobot class so we update this class as follows:
 

@Entity
@Table(name="robot")
public class KillerRobot{

	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	@Column(name = "robot_id", unique = true, nullable = false)
	private long id;
	
	@Column(name = "name", unique = false, nullable = true)
	private String name;
	
	@Column(name = "serial", unique = false, nullable = true)
	private String serial;
	
	@Column(name = "time", unique = false, nullable = true)
	private Date productionTime;
	
	@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
	@JoinColumn(name="robot_id")
	private Company company;
	
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSerial() {
		return serial;
	}
	public void setSerial(String serial) {
		this.serial = serial;
	}
	public Date getProductionTime() {
		return productionTime;
	}
	public void setProductionTime(Date productionTime) {
		this.productionTime = productionTime;
	}
	public Company getCompany() {
		return company;
	}
	public void setCompany(Company company) {
		this.company = company;
	}
}

 
It is very important that we don’t forget to add mapping of the newly created class in the hibernate.cfg.xml configuration file.
 

<mapping class="com.binaryalchemist.killer_robot.Company"/>

At this stage, our application looks as follows:
 

@WebServlet(
name="robotservlet",
urlPatterns={"/robot","/" })
public class KillerRobotServlet extends HttpServlet {
	
	public KillerRobotServlet() {
		super();
	}
	
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		KillerRobot robi = new KillerRobot();
		robi.setName("Bob");
		robi.setProductionTime(new Date());
		robi.setSerial("AX7N41S");
		
		Company company = new Company();
		company.setName("Skynet");
		company.setAdress("USA");
		company.setWebpage("www.skynet.com");
		company.setFounded(new Date());
		robi.setCompany(company);
		company.setRobot(robi);
		
		Session session = DBConnection.getSession();
		session.beginTransaction();
		session.save(robi);
		session.getTransaction().commit();
		DBConnection.close();
		
		request.getRequestDispatcher("/index.jsp").forward(request, response);
	}
}

The code did not became much harder. Remember, however, that both objects must be assigned to each other: robi.setCompany(company); company.setRobot(robi); Next we will take care of one to many relationship.
 

One to many relationship Hibernate:

Assume that each of our killer robots can have from one to more weapons. So let’s make again following tables and class:
 

create table weapon
(
weapon_id int NOT NULL AUTO_INCREMENT,
robot_id int NOT NULL,
name text,
firepower int,
type text,
weight float,
constraint primary key(weapon_id),
CONSTRAINT weapon_robot_fk FOREIGN KEY(robot_id) REFERENCES robot(robot_id)
)

 
[/cc]

@Entity
@Table(name="weapon")
public class Weapon {

	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	@Column(name = "weapon_id", unique = true, nullable = false)
	private long weapon_id;
    private String name;
	private int firepower;
    private String type;
    private float weight;
    
    
    @ManyToOne
    @JoinColumn(name = "robot_id")
    private KillerRobot robot;
    
	public long getWeapon_id() {
		return weapon_id;
	}
	public void setWeapon_id(long weapon_id) {
		this.weapon_id = weapon_id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getFirepower() {
		return firepower;
	}
	public void setFirepower(int firepower) {
		this.firepower = firepower;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public float getWeight() {
		return weight;
	}
	public void setWeight(float weight) {
		this.weight = weight;
	}
	public KillerRobot getRobot() {
		return robot;
	}
	public void setRobot(KillerRobot robot) {
		this.robot = robot;
	}
}

 
We have here only one new annotation @ManyToOne in which we indicate by which parameter table should be combined.
 
Then we update KillerRobot class with new relationship:
 

@Entity
@Table(name="robot")
public class KillerRobot{

	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	@Column(name = "robot_id", unique = true, nullable = false)
	private long id;
	
	@Column(name = "name", unique = false, nullable = true)
	private String name;
	
	@Column(name = "serial", unique = false, nullable = true)
	private String serial;
	
	@Column(name = "time", unique = false, nullable = true)
	private Date productionTime;
	
	@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
	@JoinColumn(name="robot_id")
	private Company company;
	
	@OneToMany(mappedBy="robot")
	private Set<Weapon> weapons;
	
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSerial() {
		return serial;
	}
	public void setSerial(String serial) {
		this.serial = serial;
	}
	public Date getProductionTime() {
		return productionTime;
	}
	public void setProductionTime(Date productionTime) {
		this.productionTime = productionTime;
	}
	public Company getCompany() {
		return company;
	}
	public void setCompany(Company company) {
		this.company = company;
	}
	public Set<Weapon> getWeapons() {
		return weapons;
	}
	public void setWeapons(Set<Weapon> weapons) {
		this.weapons = weapons;
	}
}

It is worth noting that since the robot can have many weapons annotation must indicate collections. Let’s add a mapping in the Hibernate configuration file:
 

<mapping class="com.binaryalchemist.killer_robot.Weapon" />

Source code upgraded with new functionality is as follows:
 

 
@WebServlet(
name="robotservlet",
urlPatterns={"/robot","/" })
public class KillerRobotServlet extends HttpServlet {
	
	public KillerRobotServlet() {
		super();
	}
	
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		KillerRobot robi = new KillerRobot();
		robi.setName("Bob");
		robi.setProductionTime(new Date());
		robi.setSerial("AX7N41S");
		
		Company company = new Company();
		company.setName("Skynet");
		company.setAdress("USA");
		company.setWebpage("www.skynet.com");
		company.setFounded(new Date());
		robi.setCompany(company);
		company.setRobot(robi);
		
		Set<Weapon> weapons = new HashSet<Weapon>(); 
		
		Weapon weapon1 = new Weapon();
		weapon1.setName("Laser");
		weapon1.setType("Energy");
		weapon1.setFirepower(36);
		weapon1.setWeight(56.6f);
		weapon1.setRobot(robi);
		Weapon weapon2 = new Weapon();
		weapon2.setName("Gattling Gun");
		weapon2.setType("Projectile");
		weapon1.setFirepower(58);
		weapon2.setWeight(172.6f);
		weapon2.setRobot(robi);
		weapons.add(weapon1);
		weapons.add(weapon2);
		
		robi.setWeapons(weapons);
		
		Session session = DBConnection.getSession();
		session.beginTransaction();
		session.save(robi);
		session.save(weapon1);
		session.save(weapon2);
		session.getTransaction().commit();
		DBConnection.close();
		
		request.getRequestDispatcher("/index.jsp").forward(request, response);
	}
}

We will now take care of last relationship many to many:
 

Many to many relationship Hibernate:

Each robot has various sensors as well as any type of sensor can be installed in various robots so let’s try to reflect this in hibernate:
 
Creating tables and class:
 

create table sensor
(
sensor_id int NOT NULL AUTO_INCREMENT,
name varchar(255),
type text,
description text,
constraint primary key(sensor_id)
)

 

create table robot_sensor
(
robot_id int NOT NULL,
sensor_id int NOT NULL,
CONSTRAINT PRIMARY KEY(robot_id,sensor_id),
CONSTRAINT FOREIGN KEY(robot_id) REFERENCES robot(robot_id) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT FOREIGN KEY(sensor_id) REFERENCES sensor(sensor_id) ON UPDATE CASCADE ON DELETE CASCADE
)

 

@Entity
@Table(name="sensor")
public class Sensor {

	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	@Column(name = "sensor_id", unique = true, nullable = false)
	private long sensor_id;
    private String name;
	private String type;
    private String description;
    
	@ManyToMany(mappedBy = "sensors")
	private Set<KillerRobot> robots;

	public long getSensor_id() {
		return sensor_id;
	}

	public void setSensor_id(long sensor_id) {
		this.sensor_id = sensor_id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public Set<KillerRobot> getRobots() {
		return robots;
	}

	public void setRobots(Set<KillerRobot> robots) {
		this.robots = robots;
	}
}

We are adding annotation @ManyToMany and point to the variable in class KillerRobot. We update our KillerRobot
 

@Entity
@Table(name="robot")
public class KillerRobot{

	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	@Column(name = "robot_id", unique = true, nullable = false)
	private long id;
	
	@Column(name = "name", unique = false, nullable = true)
	private String name;
	
	@Column(name = "serial", unique = false, nullable = true)
	private String serial;
	
	@Column(name = "time", unique = false, nullable = true)
	private Date productionTime;
	
	@OneToOne(cascade = CascadeType.ALL)
	@JoinColumn(name="robot_id")
	private Company company;
	
	@OneToMany(mappedBy="robot")
	private Set<Weapon> weapons;
	
	@ManyToMany(cascade = CascadeType.ALL)
	@JoinTable(name = "robot_sensor",  joinColumns = { 
			@JoinColumn(name = "robot_id") }, 
			inverseJoinColumns = { @JoinColumn(name = "sensor_id"
					) })
	private Set<Sensor> sensors;
	
	
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSerial() {
		return serial;
	}
	public void setSerial(String serial) {
		this.serial = serial;
	}
	public Date getProductionTime() {
		return productionTime;
	}
	public void setProductionTime(Date productionTime) {
		this.productionTime = productionTime;
	}
	public Company getCompany() {
		return company;
	}
	public void setCompany(Company company) {
		this.company = company;
	}
	public Set<Weapon> getWeapons() {
		return weapons;
	}
	public void setWeapons(Set<Weapon> weapons) {
		this.weapons = weapons;
	}
	public Set<Sensor> getSensors() {
		return sensors;
	}
	public void setSensors(Set<Sensor> sensors) {
		this.sensors = sensors;
	}
}

Here also most important is annotation @ManyToMany and @JoinTable in which we indicate the keys by which we connect our tables. Add the mapping of the new class to hibernate configuration file.
 

<mapping class="com.binaryalchemist.killer_robot.Sensor" />

All code is as follows:
 

@WebServlet(
name="robotservlet",
urlPatterns={"/robot","/" })
public class KillerRobotServlet extends HttpServlet {
	
	public KillerRobotServlet() {
		super();
	}
	
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		KillerRobot robi = new KillerRobot();
		robi.setName("Bob");
		robi.setProductionTime(new Date());
		robi.setSerial("AX7N41S");
		
		Company company = new Company();
		company.setName("Skynet");
		company.setAdress("USA");
		company.setWebpage("www.skynet.com");
		company.setFounded(new Date());
		robi.setCompany(company);
		company.setRobot(robi);
		
		Set<Weapon> weapons = new HashSet<Weapon>(); 
		
		Weapon weapon1 = new Weapon();
		weapon1.setName("Laser");
		weapon1.setType("Energy");
		weapon1.setFirepower(36);
		weapon1.setWeight(56.6f);
		weapon1.setRobot(robi);
		Weapon weapon2 = new Weapon();
		weapon2.setName("Gattling Gun");
		weapon2.setType("Projectile");
		weapon1.setFirepower(58);
		weapon2.setWeight(172.6f);
		weapon2.setRobot(robi);
		weapons.add(weapon1);
		weapons.add(weapon2);
		
		robi.setWeapons(weapons);
		
		KillerRobot robi2 = new KillerRobot();
		robi2.setName("Jack");
		robi2.setProductionTime(new Date());
		robi2.setSerial("Z9J6HSA");
		
		Sensor sensor = new Sensor();
		sensor.setName("Optical sensor");
		sensor.setType("Image Sensor");
		sensor.setDescription("Sensor for finding objects by robot");
		Sensor sensor2 = new Sensor();
		sensor2.setName("Ultrasonic Range Finder");
		sensor2.setType("Sound Sensor");
		sensor2.setDescription("Sensor for detecting ultrasonic waves");
		
		Set<Sensor> sensors = new HashSet<Sensor>();
		sensors.add(sensor);
		sensors.add(sensor2);
		
		robi.setSensors(sensors);
		robi2.setSensors(sensors);
		
		
		Session session = DBConnection.getSession();
		session.beginTransaction();
		session.save(robi);
		session.save(robi2);
		session.save(weapon1);
		session.save(weapon2);
		

		session.getTransaction().commit();
		DBConnection.close();
		
		
		request.getRequestDispatcher("/index.jsp").forward(request, response);
	}
}

At the end of this tutorial will be shown how to search, update and delete data using Hibernate HQL language.
 

HQL in Hibernnate:

In Hibernate we can use ordinary SQL queries as well as HQL (Hibernate Query Language) which is very similar to SQL, but the query is performed on objects rather than tables as in the case of SQL.
 
Below are basic example to read, update and delete data using HQL. Operations are performed based on the data that we created earlier in this tutorial.
 

		Session session = DBConnection.getSession();
		session.beginTransaction();

		//Finding all robots from database
		Query query = session.createQuery("from KillerRobot");
		List<KillerRobot> robotList = query.list();
		for(KillerRobot robot : robotList){
			System.out.println("Robot Data: ID "+robot.getId()+", Name "+robot.getName()+", Serial "+robot.getSerial());
		}
		
		//Update robot data
		query = session.createQuery("update KillerRobot set name= :name where robot_id= :robot_id");
		query.setParameter("name", "T-1000");
		query.setLong("robot_id", 1);
		query.executeUpdate();

		//Delete robot from DB
		query = session.createQuery("delete from KillerRobot where robot_id= :robot_id");
		query.setLong("robot_id", 2);
		query.executeUpdate();
		
		session.getTransaction().commit();
		DBConnection.close();

The entire source code created in Eclipse is possible to download below.
Source Code

Leave a Comment

WordPress Video Lightbox Plugin