Hibernate tutorial with Eclipse

http://www.mastertheboss.com/quickstart-tutorials-hibernate/jpa/hibernate-tutorial-with-eclipse

Hibernate is an object/relational mapping tool for Java environments. What does it mean the term object/relational mapping? simply a technique of mapping a data representation from an object model to a relational data model with a SQL-based schema.

Hibernate tutorial with Eclipse

For this tutorial we'll use Hibernate 3.5.6 GA which you can download here:

 

http://www.hibernate.org/downloads 

The tutorial will be built using Eclipse Enterprise, anyway, since we'll create the Project as simple java project you can easily adapt it on any other IDE. Ok, at fist let's create a new Java project. We'll name it "Hibernate tutorial".

hibernate tutorial example

Next step is adding a Java class which will be mapped on the DB. We'll create class com.sample.Person :

hibernate tutorial example

Class is a sample JavaBean with properties and getters/setters

01. package com.sample;
02.  
03. public class Person {
04. Long id;
05. String name;
06. String surname;
07. String address;
08.  
09. public Long getId() {
10. return id;
11. }
12. private void setId(Long id) {
13. this.id = id;
14. }
15. public String getName() {
16. return name;
17. }
18. public void setName(String name) {
19. this.name = name;
20. }
21. public String getSurname() {
22. return surname;
23. }
24. public void setSurname(String surname) {
25. this.surname = surname;
26. }
27. public String getAddress() {
28. return address;
29. }
30. public void setAddress(String address) {
31. this.address = address;
32. }
33. }          

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. 

Create a file named Person.hbm.xml in the same package/folder of your JavaBean Person.

01. <?xml version="1.0"?>
02. <!DOCTYPE hibernate-mapping PUBLIC
03. "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
05.  
06. <hibernate-mapping>
07.  
08. <class name="com.sample.Person" table="Person">
09.  
10. <id name="id" column="ID">
11. <generator class="native" />
12. </id>
13.  
14. <property name="name">
15. <column name="NAME" length="16" not-null="true" />
16. </property>
17.  
18. <property name="surname">
19. <column name="SURNAME" length="16" not-null="true" />
20. </property>
21.  
22. <property name="address">
23. <column name="ADDRESS" length="16" not-null="true" />
24. </property>
25.  
26. </class>
27. </hibernate-mapping>

The id element is the declaration of the identifier property, name="id" declares the name of the Java property - The column attribute tells Hibernate which column of the PERSON table we use for this primary key.


The nested generator element specifies the identifier generation strategy: in this case we used native, which picks the best strategy depending on the configured database (dialect). 

The fields are enlist as "property". Notice the column attribute is added on every property even if this can be skipped if java property = database field.

Hibernate configuration file


This file contains the configuration information needed by Hibernate to connect to a RDBMS. For Hibernate's configuration, we can use a simple hibernate.properties file, a slightly more sophisticated hibernate.cfg.xml file, or even complete programmatic setup. Most users prefer the XML configuration file.

 

01. <!DOCTYPE hibernate-configuration PUBLIC
02. "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
04.  
05. <hibernate-configuration>
06. <session-factory>
07.  
08. <!-- hibernate dialect -->
09. <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
10.  
11.  
12. <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
13. <property name="hibernate.connection.url">jdbc:mysql://localhost/hibernatetutorial</property>
14. <property name="hibernate.connection.username">hibernate</property>
15. <property name="hibernate.connection.password">hibernate</property>
16. <property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
17.  
18. <!-- Automatic schema creation (begin) === -->
19. <property name="hibernate.hbm2ddl.auto">create</property>
20.  
21.  
22. <!-- Simple memory-only cache -->
23. <property name="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property>
24.  
25. <!-- Enable Hibernate's automatic session context management -->
26. <property name="current_session_context_class">thread</property>
27.  
28. <!-- ############################################ -->
29. <!-- # mapping files with external dependencies # -->
30. <!-- ############################################ -->
31.  
32. <mapping resource="com/sample/Person.hbm.xml" />
33.  
34. </session-factory>
35. </hibernate-configuration>

As you can see, hibernate.cfg.xml configures the dialect, the JDBC parameters, the connection pool, the cache provider and the single classes mapped.


This example uses MySQL as database. You need to create a database named "hibernatetutorial" and assign to the user "hibernate" all the privileges required.

mysql> create database hibernatetutorial;
Query OK, 1 row affected (0.00 sec)

CREATE USER 
'hibernate'@'localhost' IDENTIFIED BY 'hibernate';

mysql> use hibernatetutorial;
Database changed

mysql> grant all privileges on hibernatetutorial to hibernate;
Query OK, 0 rows affected (0.03 sec)

  

In this configuration file we have set the property "hibernate.hbm2ddl.auto" to true which means automatic drop/creation of the database schema. Remember to comment this line after the first run.

At the bottom we have declared the resource "com/sample/Person.hbm.xml" which is the mapping for Class Person.

The hibernate.cfg.xml file needs to be added to classpath. We recommend creating a new folder for storing the configuration file, for example conf, and add this folder to the CLASSPATH. In Eclipse you have this option in the "Java Build Path" manu, reached from "Properties".

hibernate example tutorial

Project libraries

Ok, now the mapping is complete. Before creating a client appllication we'll add some libraries to the project. The following libraries can be found in Hibernate distribution:

  • hibernate3.jar                        [ Root Directory]

  • slf4j-api-1.5.8.jar                     [lib\required]

  • antlr-2.7.6.jar                          [lib\required]

  • commons-collections-3.1.jar    [lib\required]

  • dom4j-1.6.1.jar                       [lib\required]

  • javassist-3.9.0.GA.jar             [lib\required]

  • jta-1.1.jar                               [lib\required]


Then you need mysql JDBC connector (or the right connector for your RDBMS)

  • mysql-connector-java.jar 

     

Ok. Last library needed is the Simply Logging Facade util. This library allows to plug in the desired logging framework at deployment time (log4j /jdk1.4).

We have tested with the following version:
http://www.slf4j.org/dist/slf4j-1.5.2.zip

You can then choose either log4j or JDK logging implementation: for example if you choose JDK14 logging implementation simply add the following jar:

  • slf4j-jdk14-1.5.2.jar

Accessing your Bean

For completing our Hibernate tutorial we'll create a Java Class “TestPerson” in the package “com.sample”. Add the following source code. It includes methods to create entries in the database, to update and to list them.

01. package com.sample;
02.  
03. import java.util.List;
04.  
05. import org.hibernate.Query;
06. import org.hibernate.Session;
07.  
08.  
09. public class TestPerson {
10.  
11. public static void main(String[] args) {
12. Session session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
13.  
14. session.beginTransaction();
15.  
16. createPerson(session);
17.  
18. queryPerson(session);
19.  
20. }
21.  
22. private static void queryPerson(Session session) {
23. Query query = session.createQuery("from Person");                
24. List <Person>list = query.list();
25. java.util.Iterator<Person> iter = list.iterator();
26. while (iter.hasNext()) {
27.  
28. Person person = iter.next();
29. System.out.println("Person: \"" + person.getName() +"\", " + person.getSurname() +"\", "+person.getAddress());
30.  
31. }
32.  
33. session.getTransaction().commit();
34.  
35. }
36.  
37. public static void createPerson(Session session) {
38. Person person = new Person();
39.  
40. person.setName("Barak");
41. person.setSurname("Obhama");      
42. person.setAddress("White House");      
43.  
44. session.save(person);
45. }
46. }

As you can see the TestPerson starts at first building a SessionFactory: this object is used to open up new Sessions. A Session represents a single-threaded unit of work, the SessionFactory is a thread-safe global object, instantiated once.

A Session is a single unit of work and begins when it is first needed, that is when the first call to getCurrentSession() is made. It is then bound by Hibernate to the current thread. When the transaction ends, either through commit or rollback, Hibernate automatically unbinds the Session from the thread and closes it for you.

In this example we use a SessionFactoryUtil class to instantiate the SessionFactory just once:

01. package com.sample;
02.  
03. import org.hibernate.Session;
04. import org.hibernate.SessionFactory;
05. import org.hibernate.cfg.Configuration;
06.  
07.  
08. public class SessionFactoryUtil {
09.  
10. private static final SessionFactory sessionFactory;
11.  
12. static {
13. try {
14. // Create the SessionFactory from hibernate.cfg.xml
15. sessionFactory = new Configuration().configure().buildSessionFactory();
16. catch (Throwable ex) {
17. // Make sure you log the exception, as it might be swallowed
18. System.err.println("Initial SessionFactory creation failed." + ex);
19. throw new ExceptionInInitializerError(ex);
20. }
21. }
22.  
23. public static SessionFactory getSessionFactory() {
24. return sessionFactory;
25. }
26.  
27. }

Ok, if you have completed all the steps your project should look like this:

hibernate tutorial example<

Hibernate Troubleshooting:

Here are some common runtime errors and their possible solution:

org.hibernate.HibernateException: No CurrentSessionContext configured

You haven't configured the current_session_context_class property. Add this to your hibernate.cfg.xml:
 <property name="current_session_context_class">thread</property>

 

org.hibernate.MappingException: Unknown entity: sample.hibernate.Person

It's likely that you have not added (or added with wrong Classname/namespace) the Class Mapping file.

 

Could not parse mapping document from resource sample/hibernate/Person.hbm.xml
Exception in thread "main" java.lang.ExceptionInInitializerError

Maybe you have forgot to add the DTD information at the top of your Person.hbm.xml

 

Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

You are missing the Simply Logging Facade util. Download it http://www.slf4j.org/dist/slf4j-1.5.2.zip and then add either log4j or JDK14 implementation.

Hibernate tutorial code:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值