Hibernate Notes for Professionals

GoalKicker.com (CC BY-SA)
Page 1 sur 39Lecteur de document UniversityLib

Hibernate Notes for Professionals

Programming, Hibernate, Java · course

Browse all programmation documents

Hibernate

Notes for Professionals

Hibernate

Notes for Professionals

30+ pages

of professional hints and tricks

GoalKicker.com

Free Programming Books

Disclaimer

This is an unocial free book created for educational purposes and is

not aliated with ocial Hibernate group(s) or company(s).

All trademarks and registered trademarks are

the property of their respective owners

Contents

About

...................................................................................................................................................................................

1

Chapter 1: Getting started with Hibernate

......................................................................................................

2

Section 1.1: Using XML Configuration to set up Hibernate

Section 1.2: Simple Hibernate example using XML

Section 1.3: XML-less Hibernate configuration

.........................................................................................

2

.....................................................................................................

...........................................................................................................

Chapter 2: Fetching in Hibernate

..........................................................................................................................

8

Section 2.1: It is recommended to use FetchType.LAZY. Join fetch the columns when they are needed

..................................................................................................................................................................................

8

Chapter 3: Hibernate Entity Relationships using Annotations

............................................................

10

Section 3.1: Bi-Directional Many to Many using user managed join table object

Section 3.2: Bi-Directional Many to Many using Hibernate managed join table

Section 3.3: Bi-directional One to Many Relationship using foreign key mapping

Section 3.4: Bi-Directional One to One Relationship managed by Foo.class

Section 3.5: Uni-Directional One to Many Relationship using user managed join table

Section 3.6: Uni-directional One to One Relationship

................................................

..................................................

..............................................

.......................................................

..............................................................................................

14

.....................................

13

4

6

10

11

12

12

Chapter 4: HQL

............................................................................................................................................................

15

Section 4.1: Selecting a whole table

Section 4.2: Select specific columns

Section 4.3: Include a Where clause

Section 4.4: Join

...........................................................................................................................

15

..........................................................................................................................

15

..........................................................................................................................

15

...........................................................................................................................................................

15

Chapter 5: Native SQL Queries

............................................................................................................................

16

Section 5.1: Simple Query

Section 5.2: Example to get a unique result

...........................................................................................................................................

16

.............................................................................................................

16

Chapter 6: Mapping associations

.......................................................................................................................

17

Section 6.1: One to One Hibernate Mapping

.............................................................................................................

17

Chapter 7: Criterias and Projections

................................................................................................................

19

Section 7.1: Use Filters

Section 7.2: List using Restrictions

Section 7.3: Using Projections

.................................................................................................................................................

19

.............................................................................................................................

20

....................................................................................................................................

20

Chapter 8: Custom Naming Strategy

...............................................................................................................

21

Section 8.1: Creating and Using a Custom ImplicitNamingStrategy

Section 8.2: Custom Physical Naming Strategy

.......................................................................................................

21

......................................................................

21

Chapter 9: Caching

.....................................................................................................................................................

24

Section 9.1: Enabling Hibernate Caching in WildFly

.................................................................................................

24

Chapter 10: Association Mappings between Entities

................................................................................

25

...................................................................................................

25

.......................................................................................................................

27

.................................................................................................

28

............................................................................................................

.......................................................................................................................................................

Section 10.1: One to many association using XML

Section 10.2: OneToMany association

Chapter 11: Lazy Loading vs Eager Loading

Section 11.1: Lazy Loading vs Eager Loading

Section 11.2: Scope

Chapter 12: Enable/Disable SQL log

Section 12.1: Using a logging config file

Section 12.2: Using Hibernate properties

Section 12.3: Enable/Disable SQL log in debug

.................................................................................................................

....................................................................................................................

..................................................................................................................

........................................................................................................

31

28

29

31

31

31

Chapter 13: Hibernate and JPA

............................................................................................................................

33

Section 13.1: Relationship between Hibernate and JPA

...........................................................................................

33

Chapter 14: Performance tuning

........................................................................................................................

34

Section 14.1: Use composition instead of inheritance

..............................................................................................

34

Credits

Advertisement

..............................................................................................................................................................................

35

You may also like

........................................................................................................................................................

36

About

Please feel free to share this PDF with anyone for free,

latest version of this book can be downloaded from:

https://goalkicker.com/HibernateBook

This Hibernate Notes for Professionals book is compiled from Stack Overflow

Documentation, the content is written by the beautiful people at Stack Overflow.

Text content is released under Creative Commons BY-SA, see credits at the end

of this book whom contributed to the various chapters. Images may be copyright

of their respective owners unless otherwise specified

This is an unofficial free book created for educational purposes and is not

affiliated with official Hibernate group(s) or company(s) nor Stack Overflow. All

trademarks and registered trademarks are the property of their respective

company owners

The information presented in this book is not guaranteed to be correct nor

accurate, use at your own risk

Please send feedback and corrections to [email protected]

GoalKicker.com – Hibernate Notes for Professionals

1

Chapter 1: Getting started with Hibernate

Version

4.2.0

4.3.0

5.0.0

Documentation Link

Release Date

http://hibernate.org/orm/documentation/4.2/ 2013-03-01

http://hibernate.org/orm/documentation/4.3/ 2013-12-01

http://hibernate.org/orm/documentation/5.0/ 2015-09-01

Section 1.1: Using XML Configuration to set up Hibernate

I create a file called database-servlet.xml somewhere on the classpath.

Initially your config file will look like this:

<?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:jdbc="http://www.springframework.org/schema/jdbc"

xmlns:tx="http://www.springframework.org/schema/tx"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.2.xsd

http://www.springframework.org/schema/jdbc

http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">

</beans>

You'll notice I imported the tx and jdbc Spring namespaces. This is because we are going to use them quite heavily

in this config file.

First thing you want to do is enable annotation based transaction management (@Transactional). The main reason

that people use Hibernate in Spring is because Spring will manage all your transactions for you. Add the following

line to your configuration file:

<tx:annotation-driven />

We need to create a data source. The data source is basically the database that Hibernate is going to use to persist

your objects. Generally one transaction manager will have one data source. If you want Hibernate to talk to multiple

data sources then you have multiple transaction managers.

<bean id="dataSource"

class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<property name="driverClassName" value="" />

<property name="url" value="" />

<property name="username" value="" />

<property name="password" value="" />

</bean>

The class of this bean can be anything that implements javax.sql.DataSource so you could write your own. This

example class is provided by Spring, but doesn't have its own thread pool. A popular alternative is the Apache

Commons org.apache.commons.dbcp.BasicDataSource, but there are many others. I'll explain each of the

properties below:

driverClassName: The path to your JDBC driver. This is a database specific JAR that should be available on

GoalKicker.com – Hibernate Notes for Professionals

2

your classpath. Ensure that you have the most up to date version. If you are using an Oracle database, you'll

need a OracleDriver. If you have a MySQL database, you'll need a MySQLDriver. See if you can find the driver

you need here but a quick google should give you the correct driver.

url: The URL to your database. Usually this will be something like

jdbc\:oracle\:thin\:\path\to\your\database or jdbc:mysql://path/to/your/database. If you google

around for the default location of the database you are using, you should be able to find out what this should

be. If you are getting a HibernateException with the message org.hibernate.HibernateException:

Connection cannot be null when 'hibernate.dialect' not set and you are following this guide, there is

a 90% chance that your URL is wrong, a 5% chance that your database isn't started and a 5% chance that

your username/password is wrong.

username: The username to use when authenticating with the database.

password: The password to use when authenticating with the database.

The next thing, is to set up the SessionFactory. This is the thing that Hibernate uses to create and manage your

transactions, and actually talks to the database. It has quite a few configuration options that I will try to explain

below.

<bean id="sessionFactory"

class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

<property name="dataSource" ref="dataSource" />

<property name="packagesToScan" value="au.com.project />

<property name="hibernateProperties">

<props>

<prop key="hibernate.use_sql_comments">true</prop>

<prop key="hibernate.hbm2ddl.auto">validate</prop>

</props>

</property>

</bean>

dataSource: Your data source bean. If you changed the Id of the dataSource, set it here.

packagesToScan: The packages to scan to find your JPA annotated objects. These are the objects that the

session factory needs to manage, will generally be POJO's and annotated with @Entity. For more information

on how to set up object relationships in Hibernate see here.

annotatedClasses (not shown): You can also provide a list of classes for Hibernate to scan if they are not all in

the same package. You should use either packagesToScan or annotatedClasses but not both. The

declaration looks like this:

<property name="annotatedClasses">

<list>

<value>foo.bar.package.model.Person</value>

<value>foo.bar.package.model.Thing</value>

</list>

</property>

hibernateProperties: There are a myriad of these all lovingly documented here. The main ones you will be

using are as follows:

hibernate.hbm2ddl.auto: One of the hottest Hibernate questions details this property. See it for more info. I

generally use validate, and set up my database using either SQL scripts (for an in-memory), or create the

database beforehand (existing database).

hibernate.show_sql: Boolean flag, if true Hibernate will print all the SQL it generates to stdout. You can also

configure your logger to show you the values that are being bound to the queries by setting

GoalKicker.com – Hibernate Notes for Professionals

3

log4j.logger.org.hibernate.type=TRACE log4j.logger.org.hibernate.SQL=DEBUG in your log manager (I

use log4j).

hibernate.format_sql: Boolean flag, will cause Hibernate to pretty print your SQL to stdout.

hibernate.dialect (Not shown, for good reason): A lot of old tutorials out there show you how to set the

Hibernate dialect that it will use to communicate to your database. Hibernate can auto-detect which dialect

to use based on the JDBC driver that you are using. Since there are about 3 different Oracle dialects and 5

different MySQL dialects, I'd leave this decision up to Hibernate. For a full list of dialects Hibernate supports

see here.

The last 2 beans you need to declare are:

<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"

id="PersistenceExceptionTranslator" />

<bean id="transactionManager"

class="org.springframework.orm.hibernate4.HibernateTransactionManager">

<property name="sessionFactory" ref="sessionFactory" />

</bean>

The PersistenceExceptionTranslator translates database specific HibernateException or SQLExceptions into

Spring exceptions that can be understood by the application context.

The TransactionManager bean is what controls the transactions as well as roll-backs.

Note: You should be autowiring your SessionFactory bean into your DAO's.

Section 1.2: Simple Hibernate example using XML

To set up a simple hibernate project using XML for the configurations you need 3 files, hibernate.cfg.xml, a POJO for

each entity, and a EntityName.hbm.xml for each entity. Here is an example of each using MySQL:

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="hibernate.dialect">

org.hibernate.dialect.MySQLDialect

</property>

<property name="hibernate.connection.driver_class">

com.mysql.jdbc.Driver

</property>

<property name="hibernate.connection.url">

jdbc:mysql://localhost/DBSchemaName

Advertisement

</property>

<property name="hibernate.connection.username">

testUserName

</property>

<property name="hibernate.connection.password">

testPassword

</property>

<!-- List of XML mapping files -->

GoalKicker.com – Hibernate Notes for Professionals

4

<mapping resource="HibernatePractice/Employee.hbm.xml"/>

</session-factory>

</hibernate-configuration>

DBSchemaName, testUserName, and testPassword would all be replaced. Make sure to use the full resource name

if it is in a package.

Employee.java

package HibernatePractice;

public class Employee {

private int id;

private String firstName;

private String middleName;

private String lastName;

public Employee(){

}

public int getId(){

return id;

}

public void setId(int id){

this.id = id;

}

public String getFirstName(){

return firstName;

}

public void setFirstName(String firstName){

this.firstName = firstName;

}

public String getMiddleName(){

return middleName;

}

public void setMiddleName(String middleName){

this.middleName = middleName;

}

public String getLastName(){

return lastName;

}

public void setLastName(String lastName){

this.lastName = lastName;

}

}

Employee.hbm.xml

<hibernate-mapping>

<class name="HibernatePractice.Employee" table="employee">

<meta attribute="class-description">

This class contains employee information.

</meta>

<id name="id" type="int" column="empolyee_id">

<generator class="native"/>

</id>

<property name="firstName" column="first_name" type="string"/>

<property name="middleName" column="middle_name" type="string"/>

<property name="lastName" column="last_name" type="string"/>

GoalKicker.com – Hibernate Notes for Professionals

5

</class>

</hibernate-mapping>

Again, if the class is in a package use the full class name packageName.className.

After you have these three files you are ready to use hibernate in your project.

Section 1.3: XML-less Hibernate configuration

This example has been taken from here

package com.reborne.SmartHibernateConnector.utils;

import org.hibernate.HibernateException;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

public class LiveHibernateConnector implements IHibernateConnector {

private String DB_DRIVER_NAME = "";

private String DB_URL = "jdbc:h2:~/liveDB;MV_STORE=FALSE;MVCC=FALSE";

private String DB_USERNAME = "sa";

private String DB_PASSWORD = "";

private String DIALECT = "org.hibernate.dialect.H2Dialect";

private String HBM2DLL = "create";

private String SHOW_SQL = "true";

private static Configuration config;

private static SessionFactory sessionFactory;

private Session session;

private boolean CLOSE_AFTER_TRANSACTION = false;

public LiveHibernateConnector() {

config = new Configuration();

config.setProperty("hibernate.connector.driver_class", DB_DRIVER_NAME);

config.setProperty("hibernate.connection.url", DB_URL);

config.setProperty("hibernate.connection.username", DB_USERNAME);

config.setProperty("hibernate.connection.password", DB_PASSWORD);

config.setProperty("hibernate.dialect", DIALECT);

config.setProperty("hibernate.hbm2dll.auto", HBM2DLL);

config.setProperty("hibernate.show_sql", SHOW_SQL);

/*

  • Config connection pools

*/

config.setProperty("connection.provider_class",

"org.hibernate.connection.C3P0ConnectionProvider");

config.setProperty("hibernate.c3p0.min_size", "5");

config.setProperty("hibernate.c3p0.max_size", "20");

config.setProperty("hibernate.c3p0.timeout", "300");

config.setProperty("hibernate.c3p0.max_statements", "50");

config.setProperty("hibernate.c3p0.idle_test_period", "3000");

/**

  • Resource mapping

GoalKicker.com – Hibernate Notes for Professionals

6

*/

// config.addAnnotatedClass(User.class);

// config.addAnnotatedClass(User.class);

// config.addAnnotatedClass(User.class);

sessionFactory = config.buildSessionFactory();

}

public HibWrapper openSession() throws HibernateException {

return new HibWrapper(getOrCreateSession(), CLOSE_AFTER_TRANSACTION);

}

public Session getOrCreateSession() throws HibernateException {

if (session == null) {

session = sessionFactory.openSession();

}

return session;

}

public void reconnect() throws HibernateException {

this.sessionFactory = config.buildSessionFactory();

}

}

Please note, that with latest Hibernate this approach doesn't work well (Hibernate 5.2 release still allow this

configuration)

GoalKicker.com – Hibernate Notes for Professionals

7

Chapter 2: Fetching in Hibernate

Fetching is really important in JPA (Java Persistence API). In JPA, HQL (Hibernate Query Language) and JPQL (Java

Persistence Query Language) are used to fetch the entities based on their relationships. Although it is way better

than using so many joining queries and sub-queries to get what we want by using native SQL, the strategy how we

fetch the associated entities in JPA are still essentially effecting the performance of our application.

Section 2.1: It is recommended to use FetchType.LAZY. Join

fetch the columns when they are needed

Below is an Employer entity class which is mapped to the table employer. As you can see I used fetch =

FetchType.LAZY instead of fetch = FetchType.EAGER. The reason I am using LAZY is because Employer may have a

lot of properties later on and every time I may not need to know all the fields of an Employer, so loading all of them

will leading a bad performance then an employer is loaded.

@Entity

@Table(name = "employer")

public class Employer

{

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id;

@Column(name = "name")

private String Name;

@OneToMany(mappedBy = "employer", fetch = FetchType.LAZY,

cascade = { CascadeType.ALL }, orphanRemoval = true)

private List<Employee> employees;

public Long getId() {

Advertisement

return id;

}

public void setId(Long id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public List<Employee> getEmployees() {

return employees;

}

public void setEmployees(List<Employee> employees) {

this.employees = employees;

}

}

However, for LAZY fetched associations, uninitialized proxies are sometimes leads to LazyInitializationException. In

this case, we can simply use JOIN FETCH in the HQL/JPQL to avoid LazyInitializationException.

GoalKicker.com – Hibernate Notes for Professionals

8

SELECT Employer employer FROM Employer

LEFT JOIN FETCH employer.name

LEFT JOIN FETCH employer.employee employee

LEFT JOIN FETCH employee.name

LEFT JOIN FETCH employer.address

GoalKicker.com – Hibernate Notes for Professionals

9

Chapter 3: Hibernate Entity Relationships

using Annotations

Annotation

@OneToOne

Details

Specifies a one to one relationship with a corresponding object.

@OneToMany Specifies a single object that maps to many objects.

@ManyToOne Specifies a collection of objects that map to a single object.

@Entity

@Table

Specifies an object that maps to a database table.

Specifies which database table this object maps too.

@JoinColumn Specifies which column a foregin key is stored in.

@JoinTable Specifies an intermediate table that stores foreign keys.

Section 3.1: Bi-Directional Many to Many using user managed

join table object

@Entity

@Table(name="FOO")

public class Foo {

private UUID fooId;

@OneToMany(mappedBy = "bar")

private List<FooBar> bars;

}

@Entity

@Table(name="BAR")

public class Bar {

private UUID barId;

@OneToMany(mappedBy = "foo")

private List<FooBar> foos;

}

@Entity

@Table(name="FOO_BAR")

public class FooBar {

private UUID fooBarId;

@ManyToOne

@JoinColumn(name = "fooId")

private Foo foo;

@ManyToOne

@JoinColumn(name = "barId")

private Bar bar;

//You can store other objects/fields on this table here.

}

Specifies a two-way relationship between many Foo objects to many Bar objects using an intermediate join table

that the user manages.

The Foo objects are stored as rows in a table called FOO. The Bar objects are stored as rows in a table called BAR. The

relationships between Foo and Bar objects are stored in a table called FOO_BAR. There is a FooBar object as part of

the application.

GoalKicker.com – Hibernate Notes for Professionals

10

Commonly used when you want to store extra information on the join object such as the date the relationship was

created.

Section 3.2: Bi-Directional Many to Many using Hibernate

managed join table

@Entity

@Table(name="FOO")

public class Foo {

private UUID fooId;

@OneToMany

@JoinTable(name="FOO_BAR",

joinColumns = @JoinColumn(name="fooId"),

inverseJoinColumns = @JoinColumn(name="barId"))

private List<Bar> bars;

}

@Entity

@Table(name="BAR")

public class Bar {

private UUID barId;

@OneToMany

@JoinTable(name="FOO_BAR",

joinColumns = @JoinColumn(name="barId"),

inverseJoinColumns = @JoinColumn(name="fooId"))

private List<Foo> foos;

}

Specifies a relationship between many Foo objects to many Bar objects using an intermediate join table that

Hibernate manages.

The Foo objects are stored as rows in a table called FOO. The Bar objects are stored as rows in a table called BAR. The

relationships between Foo and Bar objects are stored in a table called FOO_BAR. However this implies that there is

no FooBar object as part of the application.

GoalKicker.com – Hibernate Notes for Professionals

11

Section 3.3: Bi-directional One to Many Relationship using

foreign key mapping

@Entity

@Table(name="FOO")

public class Foo {

private UUID fooId;

@OneToMany(mappedBy = "bar")

private List<Bar> bars;

}

@Entity

@Table(name="BAR")

public class Bar {

private UUID barId;

@ManyToOne

@JoinColumn(name = "fooId")

private Foo foo;

}

Specifies a two-way relationship between one Foo object to many Bar objects using a foreign key.

The Foo objects are stored as rows in a table called FOO. The Bar objects are stored as rows in a table called BAR. The

foreign key is stored on the BAR table in a column called fooId.

Section 3.4: Bi-Directional One to One Relationship managed

by Foo.class

@Entity

@Table(name="FOO")

public class Foo {

private UUID fooId;

@OneToOne(cascade = CascadeType.ALL)

@JoinColumn(name = "barId")

private Bar bar;

}

@Entity

@Table(name="BAR")

public class Bar {

private UUID barId;

@OneToOne(mappedBy = "bar")

private Foo foo;

}

GoalKicker.com – Hibernate Notes for Professionals

12

Specifies a two-way relationship between one Foo object to one Bar object using a foreign key.

The Foo objects are stored as rows in a table called FOO. The Bar objects are stored as rows in a table called BAR. The

foreign key is stored on the FOO table in a column called barId.

Note that the mappedBy value is the field name on the object, not the column name.

Section 3.5: Uni-Directional One to Many Relationship using

user managed join table

@Entity

@Table(name="FOO")

Advertisement

public class Foo {

private UUID fooId;

@OneToMany

@JoinTable(name="FOO_BAR",

joinColumns = @JoinColumn(name="fooId"),

inverseJoinColumns = @JoinColumn(name="barId", unique=true))

private List<Bar> bars;

}

@Entity

@Table(name="BAR")

public class Bar {

private UUID barId;

//No Mapping specified here.

}

@Entity

@Table(name="FOO_BAR")

public class FooBar {

private UUID fooBarId;

@ManyToOne

@JoinColumn(name = "fooId")

private Foo foo;

@ManyToOne

@JoinColumn(name = "barId", unique = true)

private Bar bar;

//You can store other objects/fields on this table here.

}

Specifies a one-way relationship between one Foo object to many Bar objects using an intermediate join table that

the user manages.

This is similar to a ManyToMany relationship, but if you add a unique constraint to the target foreign key you can

GoalKicker.com – Hibernate Notes for Professionals

13

enforce that it is OneToMany.

The Foo objects are stored as rows in a table called FOO. The Bar objects are stored as rows in a table called BAR. The

relationships between Foo and Bar objects are stored in a table called FOO_BAR. There is a FooBar object as part of

the application.

Notice that there is no mapping of Bar objects back to Foo objects. Bar objects can be manipulated freely without

affecting Foo objects.

Very commonly used with Spring Security when setting up a User object who has a list of Role's that they can

perform. You can add and remove roles to a user without having to worry about cascades deleting Role's.

Section 3.6: Uni-directional One to One Relationship

@Entity

@Table(name="FOO")

public class Foo {

private UUID fooId;

@OneToOne

private Bar bar;

}

@Entity

@Table(name="BAR")

public class Bar {

private UUID barId;

//No corresponding mapping to Foo.class

}

Specifies a one-way relationship between one Foo object to one Bar object.

The Foo objects are stored as rows in a table called FOO. The Bar objects are stored as rows in a table called BAR.

Notice that there is no mapping of Bar objects back to Foo objects. Bar objects can be manipulated freely without

affecting Foo objects.

GoalKicker.com – Hibernate Notes for Professionals

14

Chapter 4: HQL

HQL is Hibernate Query Language, it based on SQL and behind the scenes it is changed into SQL but the syntax is

different. You use entity/class names not table names and field names not column names. It also allows many

shorthands.

Section 4.1: Selecting a whole table

hql = "From EntityName";

Section 4.2: Select specific columns

hql = "Select id, name From Employee";

Section 4.3: Include a Where clause

hql = "From Employee where id = 22";

Section 4.4: Join

hql = "From Author a, Book b Where a.id = book.author";

GoalKicker.com – Hibernate Notes for Professionals

15

Chapter 5: Native SQL Queries

Section 5.1: Simple Query

Assuming you have a handle on the Hibernate Session object, in this case named session:

List<Object[]> result = session.createNativeQuery("SELECT * FROM some_table").list();

for (Object[] row : result) {

for (Object col : row) {

System.out.print(col);

}

}

This will retrieve all rows in some_table and place them into the result variable and print every value.

Section 5.2: Example to get a unique result

Object pollAnswered = getCurrentSession().createSQLQuery(

"select * from TJ_ANSWERED_ASW where pol_id = "+pollId+" and prf_log =

'"+logid+"'").uniqueResult();

with this query, you get a unique result when you know the result of the query is always going to be unique.

And if the query returns more than one value, you will get an exception

org.hibernate.NonUniqueResultException

You also check the details in this link here with more discription

So, please be sure that you know the query will return unique result

GoalKicker.com – Hibernate Notes for Professionals

16

Chapter 6: Mapping associations

Section 6.1: One to One Hibernate Mapping

Every Country has one Capital. Every Capital has one Country.

Country.java

package com.entity;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.OneToOne;

import javax.persistence.Table;

@Entity

@Table(name = "countries")

public class Country {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private int id;

@Column(name = "name")

private String name;

@Column(name = "national_language")

private String nationalLanguage;

@OneToOne(mappedBy = "country")

private Capital capital;

//Constructor

//getters and setters

}

Capital.java

package com.entity;

import javax.persistence.CascadeType;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.JoinColumn;

import javax.persistence.OneToOne;

import javax.persistence.Table;

@Entity

@Table(name = "capitals")

public class Capital {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private int id;

GoalKicker.com – Hibernate Notes for Professionals

17

private String name;

private long population;

@OneToOne(cascade = CascadeType.ALL)

@JoinColumn(name = "country_id")

private Country country;

//Constructor

//getters and setters

}

HibernateDemo.java

package com.entity;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

public class...