Hibernate Java Application

First of all, you need to tell Hibernate some information regarding the database system you intend to use, such as host name, port number, JDBC driver class name, database connection URL… via some kind of configuration. Flexibly, Hibernate provides several ways for supplying database configuration:

    •          via properties file.
    •           via XML file.
    •           via JNDI data source.
    •           Programmatic configuration.
    •           Setting system properties.

We choose XML configuration file. In Eclipse, create a new XML file undersrc directory with this name: hibernate.cfg.xml. Put some configuration information in this file as following:

 

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>        
  <session-factory>
    <!-- Database connection settings -->
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/contactdb</property>
    <property name="connection.username">root</property>
    <property name="connection.password">P@ssw0rd</property>
  </session-factory>
</hibernate-configuration>

We specify JDBC class driver name (for MySQL), connection URL (which also specifies host name, port number, and database name), user name and password to connect to the database.

The class org.hibernate.cfg.Configuration is used to load the configuration file:

Configuration conf = new Configuration().configure();

The configure() method will read configuration from hibernate.cfg.xml file under program’s classpath.

There are also some overloaded versions of configure() method which allow you to load configuration file in different ways.

The above configuration is only for necessary information. In addition, Hibernate provides a variety of settings such as connection pooling, transaction, debugging… however we don’t cover all of them in this simple tutorial. Just add this line to the hibernate.cfg.xml file:

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

which tells Hibernate to show all SQL statements to the standard output.

Working with Hibernate session

Hibernate provides its database services via a session. In other words, all database operations are executed under context of a Hibernate session. The session manages mapped objects and offers database’s CRUD (create, read, update, delete) operations. Working with Hibernate’s API involves in working with its Session and Session’s relevant methods.

The following code obtains a new session from a session factory:

Configuration configuration = new Configuration().configure();
ServiceRegistryBuilder registry = new ServiceRegistryBuilder();
registry.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = registry.buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);


The Session interface defines a number of methods for executing CRUD operations with mapped objects. The following table lists the most common methods provided by the session:

#

Method name

Return

Description

Issued SQL statement

1

beginTransaction()

Transaction

Creates a Transaction object or returns an existing one, for working under context of a transaction.

 

2

getTransaction()

Transaction

Returns the current transaction.

 

3

get(Class class, Serializable id)

Object

Loads a persistent instance of the given class with the given id, into the session.

SELECT

4

load(Class class, Serializable id)

Object

Does same thing as get()method, but throws anObjectNotFound error if no row with the given id exists.

SELECT

5

persist(Object)

void

saves a mapped object as a row in database

INSERT

6

save(Object)

Serializable

Does same thing as persist()method, plus returning a generated identifier.

INSERT

7

update(Object)

void

Updates a detached instance of the given object and the underlying row in database.

UPDATE

8

saveOrUpdate(Object)

void

Saves the given object if it does not exist, otherwise updates it.

INSERT or UPDATE

9

delete(Object)

void

Removes a persistent object and the underlying row in database.

DELETE

10

close()

void

Ends the current session.

 

11

flush()

void

Flushes the current session. This method should be called before committing the transaction and closing the session.

 

12

disconnect()

void

Disconnects the session from current JDBC connection.

Working with Hibernate transaction

Multiple database operations should be executed inside a transaction in order to protect consistence of data in the database in case of exceptions or errors occurred. The following skeleton code illustrates working with a transaction in Hibernate:

session.beginTransaction();
try {
    session.persist(Object);
    session.update(Object);
    session.delete(Object);
} catch (Exception
 ex) {
    session.getTransaction().rollback();
}
session.getTransaction().commit();
session.close();


When working with transaction, it requires committing the transaction to make permanent changes to the database, and finally, close the session.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值