0% found this document useful (0 votes)
100 views

Hibernate Coding

This document provides an example of configuring Hibernate for a simple Java application. It includes the Hibernate configuration file, mapping file, and Java client class. The configuration file defines the database connection details and mapping. The mapping file maps the Simple Java class and table. The client class saves a Simple object to the database using a Hibernate Session.

Uploaded by

lcbk2133
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
100 views

Hibernate Coding

This document provides an example of configuring Hibernate for a simple Java application. It includes the Hibernate configuration file, mapping file, and Java client class. The configuration file defines the database connection details and mapping. The mapping file maps the Simple Java class and table. The client class saves a Simple object to the database using a Hibernate Session.

Uploaded by

lcbk2133
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 10

1.

Simple Example
<?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">

<!-- Generated by MyEclipse Hibernate Tools. -->


<hibernate-configuration>

<session-factory>
<property name="connection.username">username</property>
<property name="connection.url">
jdbc:oracle:thin:username/password@localhost:1521/XE
</property>
<property name="dialect">
org.hibernate.dialect.Oracle9Dialect </property>
<property
name="myeclipse.connection.profile">MyDriver</property>
<property name="connection.password">password</property>
<property name="connection.driver_class">
oracle.jdbc.driver.OracleDriver</property>

<mapping resource="./Simple.hbm.xml" />


</session-factory>
</hibernate-configuration>

Simple.hbm.xml :
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate
Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="Simple" table="SIMPLE" schema="USERNAME">
<id name="id" type="java.lang.Long">
<column name="ID" precision="2" scale="0" />
<generator class="assigned" />
</id>
<property name="name" type="java.lang.String">
<column name="NAME" length="21" />
</property>
</class>
</hibernate-mapping>

Client class
import org.hibernate.*;
import org.hibernate.cfg.*;
import org.hibernate.transaction.*;
public class mainSimple {

public mainSimple() {
// TODO Auto-generated constructor stub
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SessionFactory sf = new Configuration().configure().
buildSessionFactory();
Session ses = sf.openSession();
Transaction tx = ses.beginTransaction();
Simple sob=new Simple();
Sob.setId(21);
Sob.setName(“LCBK Raju”);
Ses.save(sob);
Tx.close();
Ses.close();
}
}

2. Create session factory:


a.
SessionFactory sessions = new Configuration()
.addResource("hello/Message.hbm.xml")
.setProperties( System.getProperties() )
.buildSessionFactory();
b.
SessionFactory sessions = new Configuration()
.addClass(org.hibernate.auction.model.Item.class)
.addClass(org.hibernate.auction.model.Category.class)
.addClass(org.hibernate.auction.model.Bid.class)
.setProperties( System.getProperties() )
.buildSessionFactory();
c. addjar
d. SessionFactory ses=new
Configuration().configure(“/aaa/bbb.xml”)….
e. General Way(hibernate.config.xml as config file)
SessionFactory ses=new
Configuration().configure().buildsessionFactory();

3.c3po connection pooling settings


hibernate.connection.driver_class = oracle.jdbc.driver.OracleDriver
hibernate.connection.url =
jdbc:oracle:thin:username/password@localhost:1521/XE
hibernate.connection.username = auctionuser
hibernate.connection.password = secret
hibernate.dialect = net.sf.hibernate.dialect.PostgreSQLDialect
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.timeout=300
hibernate.c3p0.max_statements=50
hibernate.c3p0.idle_test_period=3000

4. Container managed hibernate.properties


hibernate.connection.datasource = java:/comp/env/jdbc/AuctionDB
hibernate.transaction.factory_class = \
net.sf.hibernate.transaction.JTATransactionFactory
hibernate.transaction.manager_lookup_class = \
net.sf.hibernate.transaction.JBossTransactionManagerLookup
hibernate.dialect = net.sf.hibernate.dialect.PostgreSQLDialect

5. <property name="show_sql">true</property>// logging all


generated SQL to console

6.Session Factory Class example


a.
package src2;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {

/**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static String CONFIG_FILE_LOCATION =
"/hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new
ThreadLocal<Session>();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;

static {
try {
configuration.configure(configFile);
sessionFactory =
configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating
SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}

/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();

if (session == null || !session.isOpen()) {


if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ?
sessionFactory.openSession()
: null;
threadLocal.set(session);
}

return session;
}

/**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory =
configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating
SessionFactory %%%%");
e.printStackTrace();
}
}

/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);

if (session != null) {
session.close();
}
}

/**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory()
{
return sessionFactory;
}

/**
* return session factory
*
* session factory will be rebuilded in the next call
*/
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}

/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}

}
b. Get Session Factory
Session ses=HibernateSessionfactory.getSession();

8. Hibernate uses reflection in mappings


a.
the following mappings are equivalent:
<property name="description" column="DESCRIPTION"
type="string"/>
<property name="description" column="DESCRIPTION"/>
b. u can omit column if pojo property name column name are
same.
<property name=”id”/>
c.
<property name="initialPrice" column="INITIAL_PRICE" not-
null="true"/>
d. derived properties
<property name="totalIncludingTax"
formula="TOTAL + TAX_RATE * TOTAL"
type="big_decimal"/>
e. U don’t required POJO
<property name="name"
column="NAME"
type="string"
access="field"/>
f.
<property name="name"
column="NAME" type="string" insert="false" update="false"/>
g. class level setting
<class name="org.hibernate.auction.model.User"
dynamic-insert="true" dynamic-update="true">
...
</class>
h.
If the complete class is immutable, set the immutable="false" in
the class mapping
i. Quoted properties
<property name="description" column="`Item Description`"/>
j. Naming Strategy ---- Add Notes
k. Schema
1.<hibernate-mapping>
<class
name="org.hibernate.auction.model.Category"
table="CATEGORY"
schema="AUCTION">
...
</class>
</hibernate-mapping>
2. <hibernate-mapping
default-schema="AUCTION">
..
</hibernate-mapping>
L. <hibernate-mapping
package="org.hibernate.auction.model">
<class name="Category" table="CATEGORY">
9.
a. Hibernate exposes database identity to the application in two ways:
■ The value of the identifier property of a persistent instance
■ The value returned by Session.getIdentifier(Object o)
b.
Choosing Primary Key
<generator class="XXX" />
XXX: assigned, native, identity, hilo, sequence, increment, uuid.hex

10. An object of entity type have DB identity. An object of value


type does not have DB identity.

11. Composition: Life cycle of part dependent on life cycle of the


whole.
Hibernate uses term component for a user defined class that is
persisted to same table as owning entity.
For an example User class(Entity type), Address Class(Value type)

<class name=”user” table=”USER”>


<id name=”UserId” column=”uid”>
<generator type=”assigned”/></id>
<property…………….
……………………………>

<component name=”homeAdress” class=”address”>


<property name-----------
-------- > </component>
// reusing component
<component name=”offAdress” class=”address”>
………………………………………
………………………………</component></class>
Table would be
userId, username, off_street,off_fno, home_street, home_fno
(office address) (home address) components

For bi-directional composition we need to do


<component name=”homeAdress” class=”address”>
<parent name=”user”/>//tell the parent
<property name-----------
-------- > </component>
So we can call Adress.getUser() now.
Limitations:
1. shared references are not possible because only user can acess it.
2. If u store a component with null values then hibernate returns a null
component.

12. 3 different approaches to representing inheritance hierarchy.


a. Table per class: No polymorphism,
Associations
Hibernate Associations are inherently unidirectional.
ManyToOne: UnDirectional

public class Bid {


...
private Item item;
public void setItem(Item item) {
this.item = item;
}
public Item getItem() {
return item;
}
...
}
Next, here’s the Hibernate mapping for this association:
<class
name="Bid"
table="BID">
...
<many-to-one
name="item"
column="ITEM_ID"
class="Item"
not-null="true"/>
</class>
This mapping is called a unidirectional many-to-one association. The
column ITEM_ID
in the BID table is a foreign key to the primary key of the ITEM table.

ManyToOne Bidirectional:
public class Item {
...
private Set bids = new HashSet();
public void setBids(Set bids) {
this.bids = bids;
}
public Set getBids() {
return bids;
}
public void addBid(Bid bid) {
bid.setItem(this);
bids.add(bid);
}
...
}

Basic One to Many Mapping.

<class name="Item" table="ITEM">


...
<set name="bids">
<key column="ITEM_ID"/>
<one-to-many class="Bid"/>
</set>
</class>

You might also like