The objective of this example is to create event objects and store
these events in a database and retrieve them for display using
Hibernate. You may want to look at my article if Hibernate is not installed already on your system.
There are two approach to develop hibernate applications. The first one is “Using hibernate XML mapping files” and the other one is “Using JPA or Hibernate annotations”.
Create a new Java package in the src directory(source directory of your project) and enter org.hibernate.tutorial.domain as the package name.
The first class
Create a new Java class(Event.java) in the org.hibernate.tutorial.domain package.
Event class represents the event we want to store in the database; it is a simple JavaBean class with some properties:
Event.java : A simple persistent class
The mapping file
Create a new XML file(Event.hbm.xml) which is our mapping file in the org.hibernate.tutorial.domain package.
Hibernate needs to know how to load and store objects of the persistent class. This is where the Hibernate mapping file comes into play. The mapping file tells Hibernate what table in the database it has to access, and what columns in that table it should use.
Event.hbm.xml : A simple hibernate XML mapping
Hibernate configuration
At this point, you should have the persistent class and its mapping file in place. It is now time to configure Hibernate.
Create a new XML file and give this new configuration file the default name hibernate.cfg.xml and place it directly in the source directory(src directory) of your project, outside of any package.
hibernate.cfg.cml : A simple Hibernate XML configuration file
Note: If you want to log in to Oracle Database XE as the Administrator you must enter system for the user name and enter the password that was specified when Oracle Database XE was installed.
Note: The configuration above is for the Oracle XE database. If you use an another database management system already installed, you should change some properties in this configuration file. For example, if your database is MySQL, you must replace some properties like this :
org.hibernate.tutorial.util package
Create a new Java package in the src directory(source directory of your project) and enter org.hibernate.tutorial.util as the package name.
Startup and helpers
It is time to load and store some Event objects, but first you have to complete the setup with some infrastructure code. You have to startup Hibernate by building a global org.hibernate.SessionFactory object and storing it somewhere for easy access in application code. A org.hibernate.SessionFactory is used to obtain org.hibernate.Session instances. A org.hibernate.Session represents a single-threaded unit of work. The org.hibernate.SessionFactory is a thread-safe global object that is instantiated once.
Create a new Java class(HibernateUtil.java) in the org.hibernate.tutorial.util package that takes care of startup and makes accessing the org.hibernate.SessionFactory more convenient.
HibernateUtil.java : The HibernateUtil class for startup and SessionFactory handling
org.hibernate.tutorial package
Create a new Java package in the src directory(source directory of your project) and enter org.hibernate.tutorial as the package name.
Loading and storing objects
We are now ready to start doing some real work with Hibernate.
Create a new Java class(EventManager.java) with a main() method in the org.hibernate.tutorial package.
EventManager.java : The “HibernateApplication” main application code
The final appearance of the application should be as follows:
Now our project is ready. Right click to project or right click to EventManager.java and click Run As–>Java Application.
![Events Events](http://kaanmutlu.files.wordpress.com/2011/07/events1.png?w=640)
You will see the events stored in “EVENTS” table in the database if there is not a problem.
Note: If you get a message when you run your application like:
Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
You can add
line to the hibernate.cfg.xml file to solve this problem.
For more detailed explanation:
http://stackoverflow.com/questions/4588755/hibernate-disabling-contextual-lob-creation-as-createclob-method-threw-error
We will use JPA Annotations to replace the Hibernate XML mapping files with inline metadata.
You may want to copy your existing “HibernateApplication” project directory before you make the following changes—you’ll migrate from native Hibernate to standard JPA mappings.
Now delete the src/org.hibernate.tutorial.domain/Event.hbm.xml file. You’ll replace this file with annotations in the src/org.hibernate.tutorial.domain/Event.java class source.
Event.java: Mapping the Event class with Annotations
The other change you need to make to your project, besides deleting
the now obsolete XML mapping file, is a change in the Hibernate
configuration, in hibernate.cfg.xml.
Replace
line with
Finally, you should replace
line in HibernateUtil.java with
This is all you need to change to run the example application with
annotations.Try running it again. You should see the events stored in
the “EVENTS” table in your database.
There are two approach to develop hibernate applications. The first one is “Using hibernate XML mapping files” and the other one is “Using JPA or Hibernate annotations”.
Using Hibernate XML Mapping Files
org.hibernate.tutorial.domain packageCreate a new Java package in the src directory(source directory of your project) and enter org.hibernate.tutorial.domain as the package name.
The first class
Create a new Java class(Event.java) in the org.hibernate.tutorial.domain package.
Event class represents the event we want to store in the database; it is a simple JavaBean class with some properties:
Event.java : A simple persistent class
01 | package org.hibernate.tutorial.domain; |
02 |
03 | import java.util.Date; |
04 |
05 | public class Event { |
06 | private Long id; |
07 |
08 | private String title; |
09 | private Date date; |
10 |
11 | public Event() {} |
12 |
13 | public Long getId() { |
14 | return id; |
15 | } |
16 |
17 | private void setId(Long id) { |
18 | this .id = id; |
19 | } |
20 |
21 | public Date getDate() { |
22 | return date; |
23 | } |
24 |
25 | public void setDate(Date date) { |
26 | this .date = date; |
27 | } |
28 |
29 | public String getTitle() { |
30 | return title; |
31 | } |
32 |
33 | public void setTitle(String title) { |
34 | this .title = title; |
35 | } |
36 | } |
Create a new XML file(Event.hbm.xml) which is our mapping file in the org.hibernate.tutorial.domain package.
Hibernate needs to know how to load and store objects of the persistent class. This is where the Hibernate mapping file comes into play. The mapping file tells Hibernate what table in the database it has to access, and what columns in that table it should use.
Event.hbm.xml : A simple hibernate XML mapping
01 | <? xml version = "1.0" encoding = "UTF-8" ?> |
02 | <!DOCTYPE hibernate-mapping PUBLIC |
03 | "-//Hibernate/Hibernate Mapping DTD 3.0//EN" |
05 |
06 | < hibernate-mapping package = "org.hibernate.tutorial.domain" > |
07 |
08 | < class name = "Event" table = "EVENTS" > |
09 | < id name = "id" column = "EVENT_ID" > |
10 | < generator class = "increment" /> |
11 | </ id > |
12 | < property name = "date" type = "timestamp" column = "EVENT_DATE" /> |
13 | < property name = "title" column = "EVENT_TITLE" /> |
14 | </ class > |
15 |
16 | </ hibernate-mapping > |
At this point, you should have the persistent class and its mapping file in place. It is now time to configure Hibernate.
Create a new XML file and give this new configuration file the default name hibernate.cfg.xml and place it directly in the source directory(src directory) of your project, outside of any package.
hibernate.cfg.cml : A simple Hibernate XML configuration file
01 | <? xml version = "1.0" encoding = "UTF-8" ?> |
02 | <!DOCTYPE hibernate-configuration PUBLIC |
03 | "-//Hibernate/Hibernate Configuration DTD 3.0//EN" |
05 |
06 | < hibernate-configuration > |
07 |
08 | < session-factory > |
09 |
10 | <!-- Database connection settings --> |
11 | < property name = "connection.driver_class" >oracle.jdbc.driver.OracleDriver</ property > |
12 | < property name = "connection.url" >jdbc:oracle:thin:@127.0.0.1:1521:xe</ property > |
13 | < property name = "connection.username" >username</ property > |
14 | < property name = "connection.password" >password</ property > |
15 |
16 | <!-- SQL dialect --> |
17 | < property name = "dialect" >org.hibernate.dialect.OracleDialect</ property > |
18 |
19 | <!-- JDBC connection pool (use the built-in) --> |
20 | < property name = "connection.pool_size" >1</ property > |
21 |
22 | <!-- Enable Hibernate's automatic session context management --> |
23 | < property name = "current_session_context_class" >thread</ property > |
24 |
25 | <!-- Disable the second-level cache --> |
26 | < property name = "cache.provider_class" >org.hibernate.cache.NoCacheProvider</ property > |
27 |
28 | <!-- Echo all executed SQL to stdout --> |
29 | < property name = "show_sql" >true</ property > |
30 |
31 | <!-- Drop and re-create the database schema on startup --> |
32 | < property name = "hbm2ddl.auto" >update</ property > |
33 |
34 | < mapping resource = "org/hibernate/tutorial/domain/Event.hbm.xml" /> |
35 |
36 | </ session-factory > |
37 |
38 | </ hibernate-configuration > |
Note: The configuration above is for the Oracle XE database. If you use an another database management system already installed, you should change some properties in this configuration file. For example, if your database is MySQL, you must replace some properties like this :
01 | ... |
02 | <!-- Database connection settings --> |
03 | < property name = "connection.driver_class" >com.mysql.jdbc.Driver</ property > |
04 | < property name = "connection.url" >jdbc:mysql://localhost/SampleDB</ property > |
05 | < property name = "connection.username" >root</ property > |
06 | < property name = "connection.password" ></ property > |
07 |
08 | <!-- SQL dialect --> |
09 | < property name = "dialect" >org.hibernate.dialect.MySQLDialect</ property > |
10 | ... |
Create a new Java package in the src directory(source directory of your project) and enter org.hibernate.tutorial.util as the package name.
Startup and helpers
It is time to load and store some Event objects, but first you have to complete the setup with some infrastructure code. You have to startup Hibernate by building a global org.hibernate.SessionFactory object and storing it somewhere for easy access in application code. A org.hibernate.SessionFactory is used to obtain org.hibernate.Session instances. A org.hibernate.Session represents a single-threaded unit of work. The org.hibernate.SessionFactory is a thread-safe global object that is instantiated once.
Create a new Java class(HibernateUtil.java) in the org.hibernate.tutorial.util package that takes care of startup and makes accessing the org.hibernate.SessionFactory more convenient.
HibernateUtil.java : The HibernateUtil class for startup and SessionFactory handling
01 | package org.hibernate.tutorial.util; |
02 |
03 | import org.hibernate.SessionFactory; |
04 | import org.hibernate.cfg.Configuration; |
05 |
06 | public class HibernateUtil { |
07 |
08 | private static final SessionFactory sessionFactory = buildSessionFactory(); |
09 |
10 | private static SessionFactory buildSessionFactory() { |
11 | try { |
12 | // Create the SessionFactory from hibernate.cfg.xml |
13 | return new Configuration().configure().buildSessionFactory(); |
14 | } |
15 | catch (Throwable ex) { |
16 | // Make sure you log the exception, as it might be swallowed |
17 | System.err.println( "Initial SessionFactory creation failed." + ex); |
18 | throw new ExceptionInInitializerError(ex); |
19 | } |
20 | } |
21 |
22 | public static SessionFactory getSessionFactory() { |
23 | return sessionFactory; |
24 | } |
25 |
26 | } |
Create a new Java package in the src directory(source directory of your project) and enter org.hibernate.tutorial as the package name.
Loading and storing objects
We are now ready to start doing some real work with Hibernate.
Create a new Java class(EventManager.java) with a main() method in the org.hibernate.tutorial package.
EventManager.java : The “HibernateApplication” main application code
01 | package org.hibernate.tutorial; |
02 |
03 | import org.hibernate.Session; |
04 |
05 | import java.util.*; |
06 |
07 | import org.hibernate.tutorial.domain.Event; |
08 | import org.hibernate.tutorial.util.HibernateUtil; |
09 |
10 | public class EventManager { |
11 |
12 | public static void main(String[] args) { |
13 | EventManager mgr = new EventManager(); |
14 |
15 | mgr.createAndStoreEvent( "My First Event" , new Date()); |
16 |
17 | Calendar calendar = Calendar.getInstance(); |
18 | calendar.set(Calendar.YEAR, 2012 ); // Year |
19 | calendar.set(Calendar.MONTH, 0 ); // Month, The first month of the year is JANUARY which is 0 |
20 | calendar.set(Calendar.DATE, 1 ); // Day, The first day of the month has value 1. |
21 | mgr.createAndStoreEvent( "My Second Event" , calendar.getTime()); |
22 |
23 | List events = mgr.listEvents(); |
24 | for ( int i = 0 ; i < events.size(); i++) { |
25 | Event theEvent = (Event) events.get(i); |
26 | System.out.println( |
27 | "Event: " + theEvent.getTitle() + " Time: " + theEvent.getDate() |
28 | ); |
29 | } |
30 |
31 | HibernateUtil.getSessionFactory().close(); |
32 | } |
33 |
34 | private void createAndStoreEvent(String title, Date theDate) { |
35 | Session session = HibernateUtil.getSessionFactory().getCurrentSession(); |
36 | session.beginTransaction(); |
37 |
38 | Event theEvent = new Event(); |
39 | theEvent.setTitle(title); |
40 | theEvent.setDate(theDate); |
41 | session.save(theEvent); |
42 |
43 | session.getTransaction().commit(); |
44 | } |
45 |
46 | private List listEvents() { |
47 | Session session = HibernateUtil.getSessionFactory().getCurrentSession(); |
48 | session.beginTransaction(); |
49 | List result = session.createQuery( "from Event" ).list(); |
50 | session.getTransaction().commit(); |
51 | return result; |
52 | } |
53 |
54 | } |
![LastappearanceOfApp LastappearanceOfApp](http://kaanmutlu.files.wordpress.com/2011/07/lastappearanceofapp.png?w=640)
Now our project is ready. Right click to project or right click to EventManager.java and click Run As–>Java Application.
![Events Events](http://kaanmutlu.files.wordpress.com/2011/07/events1.png?w=640)
You will see the events stored in “EVENTS” table in the database if there is not a problem.
Note: If you get a message when you run your application like:
Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
You can add
1 | < property name = "hibernate.temp.use_jdbc_metadata_defaults" >false</ property > |
For more detailed explanation:
http://stackoverflow.com/questions/4588755/hibernate-disabling-contextual-lob-creation-as-createclob-method-threw-error
METHOD 2
Using Annotations
We will use JPA Annotations to replace the Hibernate XML mapping files with inline metadata.
You may want to copy your existing “HibernateApplication” project directory before you make the following changes—you’ll migrate from native Hibernate to standard JPA mappings.
Now delete the src/org.hibernate.tutorial.domain/Event.hbm.xml file. You’ll replace this file with annotations in the src/org.hibernate.tutorial.domain/Event.java class source.
Event.java: Mapping the Event class with Annotations
01 | package org.hibernate.tutorial.domain; |
02 |
03 | import java.util.Date; |
04 |
05 | import javax.persistence.Column; |
06 | import javax.persistence.Entity; |
07 | import javax.persistence.GeneratedValue; |
08 | import javax.persistence.Id; |
09 | import javax.persistence.Table; |
10 | import javax.persistence.Temporal; |
11 | import javax.persistence.TemporalType; |
12 |
13 | @Entity |
14 | @Table (name= "EVENTS" ) |
15 | public class Event { |
16 | @Id |
17 | @GeneratedValue |
18 | @Column (name= "EVENT_ID" ) |
19 | private Long id; |
20 |
21 | @Column (name= "EVENT_TITLE" ) |
22 | private String title; |
23 |
24 | @Temporal (TemporalType.TIMESTAMP) |
25 | @Column (name= "EVENT_DATE" ) |
26 | private Date date; |
27 |
28 | public Event() {} |
29 |
30 | public Long getId() { |
31 | return id; |
32 | } |
33 |
34 | private void setId(Long id) { |
35 | this .id = id; |
36 | } |
37 |
38 | public Date getDate() { |
39 | return date; |
40 | } |
41 |
42 | public void setDate(Date date) { |
43 | this .date = date; |
44 | } |
45 |
46 | public String getTitle() { |
47 | return title; |
48 | } |
49 |
50 | public void setTitle(String title) { |
51 | this .title = title; |
52 | } |
53 | } |
Replace
1 | < mapping resource = "org/hibernate/tutorial/domain/Event.hbm.xml" /> |
line with
1 | < mapping class = "org.hibernate.tutorial.domain.Event" /> |
1 | return new Configuration().configure().buildSessionFactory(); |
line in HibernateUtil.java with
1 | Configuration cfg = new Configuration(); |
2 | cfg.addAnnotatedClass(org.hibernate.tutorial.domain.Event. class ); |
3 | return cfg.configure().buildSessionFactory(); |
No comments:
Post a Comment
You can enter queries here...