Hibernate
Composite key:
https://forum.hibernate.org/viewtopic.php?p=2306165&sid=857145b56a9e06c8fa10aca8199c7312
Interview question:
http://java-success.blogspot.in/2010/12/hibernate-interview-questions-q.html
Jar files required :
antlr-2.7.6.jar
commons-collections-3.1.jar
dom4j-1.6.1.jar
hibernate-commons-annotations-3.2.0.Final.jar
hibernate-core-3.6.7.Final.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
javassist.jar
jms-1.1.jar
jsr250-api-1.0.jar
jta-1.1.jar
log4j-1.2.16.jar
ojdbc14.jar
slf4j-api-1.6.1.jar
slf4j-log4j12-1.6.1.jar
+
your specific driver jar file
Configuration files
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mysqltest</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">mysql</property> <!-- connection property -->
<property name="show_sql">true</property> <!-- echo sql statement on console -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- tells the hibernate which database using so that can generate adequate sql -->
<property name="hibernate.hbm2ddl.auto">create</property> <!-- Automatically creates, updates, or drops database schema on startup and shut down There are three possible values: create, createdrop, and update Be careful with create-drop -->
<property name="current_session_context_class">thread</property> <!-- Enable Hibernate's automatic session context management This is mandatory when created session using Session session = new Configuration().configure().buildSessionFactory().getCurrentSession() -->
<!-- Mapping files -->
<mapping resource = "bookapp.hbm.xml"/>
</session-factory>
</hibernate-configuration>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.bookstore">
<class name="BookDetails" table="BookStore">
<id name="id" type="int" column="id"> <!-- this is must to define -->
<generator class="native"></generator> <!-- native -> has to be generated by database -->
</id>
<property name="name" type="string" column="bname"/>
<property name="author" type="string" column="author"/>
<property name="cost" type="int" column="bcost"/>
</class>
</hibernate-mapping>
SessionFactory and Session
The Session is used to create a new database object, read in objects from the database,
update the objects in the database, and delete objects from the database. It allows us to manage
the transaction boundaries of database access.
If you are familiar with the connected approach, it helps to think of a Session as
being somewhat like a JDBC connection, and the SessionFactory, which provides Session
objects, as being somewhat like a ConnectionPool, which provides Connection objects. The
SessionFactory is an expensive object—needlessly duplicating it will cause problems quickly,
and creating a SessionFactory is a relatively time-consuming process. Ideally, you should have
a single SessionFactory for each database your application will access. The SessionFactory
is threadsafe, so it is not necessary to obtain one for each thread. However, you will create
numerous Session objects—at least one for each thread using Hibernate as the Session is not
threadsafe—and, often, you will want to create multiple Session instances even during the
lifetime of a specific thread.
Best practice always created SessionFactory once(example)
SessionFactory is once per application per database. Use a suitable singleton class to enforcethis. Sessions are once per thread. Use ThreadLocal variables to enforce this, or use the built-in
SessionFactory.getCurrentSession() method available in Hibernate 3.0.1 and higher.
package com.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
public static final SessionFactory SESSION_FACTORY;
static{
try{
SESSION_FACTORY = new Configuration().configure().buildSessionFactory();
}catch (Throwable e) {
System.err.println("Initial session factory creation failed " + e);
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getFactory(){
return SESSION_FACTORY;
}
}
How to create Session
Scenario1
Scenario1
Session session = HibernateUtil.getFactory().getCurrentSession();
session.beginTransaction();
_ _ _
session.getTransaction.commit();
session.close();
// for above scenario we need to configurethread in hibernate.cfg.xml "Enable Hibernate's automatic session context management"
Scenario2
tx = null;
} catch (HibernateException e) {
if (tx != null) tx.rollback();
} finally {
session.close();
}
Example
public void addBook(String bookName, String authorName, int bookCost){
//using persistent object to store data in database
// Session session = HibernateUtil.getFactory().getCurrentSession();
// session.beginTransaction();
//
// BookDetails bd = new BookDetails();
// bd.setName(bookName);
// bd.setAuthor(authorName);
// bd.setCost(bookCost);
//
// session.save(bd);
// session.getTransaction().commit();
Session session = HibernateUtil.getFactory().openSession();
Transaction tx = null;
try{
tx = session.getTransaction();
tx.begin();
BookDetails bd = new BookDetails();
bd.setName(bookName);
bd.setAuthor(authorName);
bd.setCost(bookCost);
session.save(bd);
tx.commit();
tx = null;
} catch (HibernateException e) {
if (tx != null) tx.rollback();
} finally {
session.close();
}
}
// for above scenario we need to configure
Scenario2
Session session = HibernateUtil.getFactory().openSession();
Transaction tx = null;
try{
tx = session.getTransaction();
tx.begin();
_ _ _ _
tx.commit();
} catch (HibernateException e) {
if (tx != null) tx.rollback();
} finally {
session.close();
}
// for above scenario no need to configure current_session_context_class
public void addBook(String bookName, String authorName, int bookCost){
//using persistent object to store data in database
// Session session = HibernateUtil.getFactory().getCurrentSession();
// session.beginTransaction();
//
// BookDetails bd = new BookDetails();
// bd.setName(bookName);
// bd.setAuthor(authorName);
// bd.setCost(bookCost);
//
// session.save(bd);
// session.getTransaction().commit();
Session session = HibernateUtil.getFactory().openSession();
Transaction tx = null;
try{
tx = session.getTransaction();
tx.begin();
BookDetails bd = new BookDetails();
bd.setName(bookName);
bd.setAuthor(authorName);
bd.setCost(bookCost);
session.save(bd);
tx.commit();
tx = null;
} catch (HibernateException e) {
if (tx != null) tx.rollback();
} finally {
session.close();
}
}
Although you should probably use HQL wherever possible, Hibernate does provide a way to
use native SQL statements directly through Hibernate. One reason to use native SQL is that
your database supports some special features through its dialect of SQL that is not supported
in HQL. Another reason is that you would like to call stored procedures from your Hibernate
application.
Example for HQL and SQL
public void countBook(){
session.beginTransaction();
//using aggregate functIon
List list = session.createQuery("select count(*) from BookDetails").list(); // here using Java class name
System.out.println("Using Agg function " + list);
//using native sql
List list1 = session.createSQLQuery("select count(*) as count from BookStore").addScalar("count",Hibernate.INTEGER).list();
System.out.println("Usin native " + list);
session.getTransaction().commit();
}
public void listBook(){
//NatIve sql query
Session session = HibernateUtil.getFactory().getCurrentSession();
session.beginTransaction();
List list = session.createSQLQuery("select * from BookStore").addEntity(BookDetails.class).list(); // here using database table name
Iterator<BookDetails> Item = list.iterator();
while(Item.hasNext()){
System.out.println(Item.next());
}
session.getTransaction().commit();
}
public SQLQuery createSQLQuery(String queryString) throws HibernateException
After you pass a string containing the SQL query to the createSQLQuery() method, you
should associate the SQL result with an existing Hibernate entity, a join, or a scalar result. The
SQLQuery interface has addEntity(), addJoin(), and addScalar() methods. For the entities and
joins, you can specify a lock mode, which we discuss in Chapter 9. The addEntity() methods take
an alias argument and either a class name or an entity name. The addJoin() methods take an
alias argument and a path to join.
Criteria Queries
- Using Simple Criteria
-
Compounding Criteria
-
Applying Criteria to Associations
-
Querying by ExampleSimple Criteria
- Criteria criteria = session.createCriteria(Track.class); return criteria.list();- Criteria criteria = session.createCriteria(Track.class);
criteria.add(Expression.le("playTime", length)); return criteria.list();- Criteria criteria = session.createCriteria(Track.class);
criteria.add(Expression.le("playTime", length)); criteria.addOrder(Order.asc("title")); return criteria.list();
Compound Criteria
- Criteria criteria = session.createCriteria(Track.class);
criteria.add(Expression.le("playTime", length));
criteria.add(Expression.like("title", "%A%"));
criteria.addOrder(Order.asc("title"));
return criteria.list();
- Criteria criteria = session.createCriteria(Track.class);
Disjunction any = Expression.disjunction(); any.add(Expression.le("playTime", length)); any.add(Expression.like("title", "%A%")); criteria.add(any); criteria.addOrder(Order.asc("title")); return criteria.list();orreturn session.createCriteria(Track.class).add(Expression.disjunction(). add(Expression.le("playTime", length)).add(Expression.like("title", "%A%"))). addOrder(Order.asc("title")).list();Applying Criteria to Associations- Criteria criteria = session.createCriteria(Track.class);Criteria artistCriteria = criteria.createCriteria("artists"); artistCriteria.add(Expression.like("name", namePattern)); criteria.addOrder(Order.asc("title")); return criteria.list();
No comments:
Post a Comment