1.
Simple Example
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"[Link]
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="[Link]">username</property>
<property name="[Link]">
jdbc:oracle:thin:username/password@localhost:1521/XE
</property>
<property name="dialect">
[Link].Oracle9Dialect </property>
<property
name="[Link]">MyDriver</property>
<property name="[Link]">password</property>
<property name="connection.driver_class">
[Link]</property>
<mapping resource="./[Link]" />
</session-factory>
</hibernate-configuration>
[Link] :
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate
Mapping DTD 3.0//EN"
"[Link]
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="Simple" table="SIMPLE" schema="USERNAME">
<id name="id" type="[Link]">
<column name="ID" precision="2" scale="0" />
<generator class="assigned" />
</id>
<property name="name" type="[Link]">
<column name="NAME" length="21" />
</property>
</class>
</hibernate-mapping>
Client class
import [Link].*;
import [Link].*;
import [Link].*;
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 = [Link]();
Transaction tx = [Link]();
Simple sob=new Simple();
[Link](21);
[Link](“LCBK Raju”);
[Link](sob);
[Link]();
[Link]();
}
}
2. Create session factory:
a.
SessionFactory sessions = new Configuration()
.addResource("hello/[Link]")
.setProperties( [Link]() )
.buildSessionFactory();
b.
SessionFactory sessions = new Configuration()
.addClass([Link])
.addClass([Link])
.addClass([Link])
.setProperties( [Link]() )
.buildSessionFactory();
c. addjar
d. SessionFactory ses=new
Configuration().configure(“/aaa/[Link]”)….
e. General Way([Link] as config file)
SessionFactory ses=new
Configuration().configure().buildsessionFactory();
3.c3po connection pooling settings
[Link].driver_class = [Link]
[Link] =
jdbc:oracle:thin:username/password@localhost:1521/XE
[Link] = auctionuser
[Link] = secret
[Link] = [Link]
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
[Link]=300
hibernate.c3p0.max_statements=50
hibernate.c3p0.idle_test_period=3000
4. Container managed [Link]
[Link] = java:/comp/env/jdbc/AuctionDB
[Link].factory_class = \
[Link]
[Link].manager_lookup_class = \
[Link]
[Link] = [Link]
5. <property name="show_sql">true</property>// logging all
generated SQL to console
[Link] Factory Class example
a.
package src2;
import [Link];
import [Link];
import [Link];
/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link [Link] }.
*/
public class HibernateSessionFactory {
/**
* Location of [Link] 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 =
"/[Link]";
private static final ThreadLocal<Session> threadLocal = new
ThreadLocal<Session>();
private static Configuration configuration = new Configuration();
private static [Link] sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;
static {
try {
[Link](configFile);
sessionFactory =
[Link]();
} catch (Exception e) {
[Link]
.println("%%%% Error Creating
SessionFactory %%%%");
[Link]();
}
}
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) [Link]();
if (session == null || ![Link]()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ?
[Link]()
: null;
[Link](session);
}
return session;
}
/**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
[Link](configFile);
sessionFactory =
[Link]();
} catch (Exception e) {
[Link]
.println("%%%% Error Creating
SessionFactory %%%%");
[Link]();
}
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) [Link]();
[Link](null);
if (session != null) {
[Link]();
}
}
/**
* return session factory
*
*/
public static [Link] getSessionFactory()
{
return sessionFactory;
}
/**
* return session factory
*
* session factory will be rebuilded in the next call
*/
public static void setConfigFile(String configFile) {
[Link] = configFile;
sessionFactory = null;
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}
}
b. Get Session Factory
Session ses=[Link]();
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="[Link]"
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="[Link]"
table="CATEGORY"
schema="AUCTION">
...
</class>
</hibernate-mapping>
2. <hibernate-mapping
default-schema="AUCTION">
..
</hibernate-mapping>
L. <hibernate-mapping
package="[Link]">
<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 [Link](Object o)
b.
Choosing Primary Key
<generator class="XXX" />
XXX: assigned, native, identity, hilo, sequence, increment, [Link]
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 [Link]() 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) {
[Link] = 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) {
[Link] = bids;
}
public Set getBids() {
return bids;
}
public void addBid(Bid bid) {
[Link](this);
[Link](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>