Showing posts with label hibernate. Show all posts
Showing posts with label hibernate. Show all posts

Java J2EE Spring Hibernate Interview Questions and Answers: with annotations and Spring framework

This is more like a Hibernate and Spring tutorial. Takes you through the key steps with code snippets. Also, very handy to refresh your memory prior to your job interviews.

Q. What are the general steps involved in creating Hibernate related class?
A. The general steps involved in creating Hibernate related classes involve the following steps

  • Define the domain (aka entity) objects like Employee, Address, etc to represent relevant tables in the underlying database with the appropriate annotations or using the *.hbm.xml mapping files.
  • Define the Repository  (aka DAO -- Data Access Objects) interfaces and implementations classes that use the domain objects and the hibernate session to perform data base CRUD (Create, Read, Update and Delete) operations the hibernate way.
  • Define the service interfaces and the classes that make use of one or more repositories (aka DAOs) in a transactional context.A transaction manager will be used to coordinate transactions (i.e. commit or rollback) between  a number of repositories.
  • Finally, use an IoC container like Spring framework to wire up the Hibernate classes like SessionFactory, Session, transaction manager, etc and the user defined repositories, and the service classes. A number of interceptors can be wired up as well for deadlock retry, logging, auditing, etc using Spring.
For more detail, refer to Spring and Hibernate integration Interview questions and answers
Q. How would you define a hibernate domain object with table mappings, native named queries, and custom data conversion using annotations?
A.

Firstly, define a parent domain object class for any common method implementations.


package com.myapp.domain.model;

public class MyAppDomainObject {

//for example
protected boolean isPropertyEqual(Object comparee, Object compareToo) {
if (comparee == null) {
if (compareToo != null) {
return false;
}
} else if (!comparee.equals(compareToo)) {
return false;
}
return true;
}

}


Now, extend the common DomainObject for specific DomainObject classes.


package com.myapp.domain.model;

@Entity
@org.hibernate.annotations.Entity(selectBeforeUpdate = true)
@Table(name = "tbl_employee")
@TypeDefs(value = { @TypeDef(name = "dec", typeClass = DecimalUserType.class)}) // custom data type conversion

@NamedNativeQueries({
@NamedNativeQuery(name = "HighSalary", query = "select * from tbl_employee where salary > :median_salary " , resultClass = Employee.class),
@NamedNativeQuery(name = "LowSalary", query = "select * from tbl_employee where salary < :median_salary " , resultClass = Employee.class)
})

public class Employee extends MyAppDomainObject implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "employee_id")
private Long id;

@Column(name = "emp_code")
private String accountCode;

@Column(name = "manager_code")
private String adviserCode;



@Column(name = "type")
@Enumerated(EnumType.STRING)
private EmployeeType type = EmployeeType.PERMANENT;


@Type(type = "dec")
@Column(name = "base_salary")
private Decimal salary = Decimal.ZERO;

@Transient
private Decimal salaryWithBonus; //not persisted to database

@Formula("base_salary*2")
private Decimal doubleSalary; //derived or calculated read only property

@Formula("(select base_salary where type = 'Permanent' )")
private Decimal permanantLeaveLoading; //derived or calculated read only property


@OneToOne(cascade = { CascadeType.REFRESH })
@JoinColumn(name = "emp_code", insertable = false, updatable = false)
private EmployeeExtrInfo extraInfo;

@ManyToOne(cascade = { CascadeType.REFRESH })
@JoinColumn(name = "manager_code", insertable = false, updatable = false)
private Manager manager;

@OneToMany(cascade = { ALL, MERGE, PERSIST, REFRESH }, fetch = FetchType.LAZY)
@JoinColumn(name = "emp_code", nullable = false)
@Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE_ORPHAN })
private List<PaymentDetail> paymentDetails = new ArrayList<PaymentDetail>();

//getters and setters omitted for brevity

}

The dependency classes like EmployeeExtrInfo, Manager, and PaymentDetail will be mapped in a similar manner as the Employee class. The EmployeeType enum class is shown below. Also note the verys usefull annotations like @NamedNativeQueries, @TypeDefs, and @Formula. The @Formula marks a property as derived, or calculated, read-only property, where its value is calculated at fetch time using SQL expressions.

package com.myapp.domain.model;


public enum EmployeeType {

PERMANENT("Permanent"),
CONTRACTOR("Contractor"),
CASUAL("Casual");

private String type;

private EmployeeType (String type) {
this.type = type;
}

public String getType() {
return this.type;
}
}


The "dec" is a custom data type, you need to define the custom data type class. The "salary" attribute will be making use of this special data type. This is ust a trivial example, but more powerful custom type conversion classes can be created.

package com.myapp.domain.model;

import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Properties;

import org.hibernate.usertype.ParameterizedType;
import org.hibernate.usertype.UserType;

public class DecimalUserType implements UserType, ParameterizedType {
public static final int PRECISION = 28;
public static final int SCALE = 15;

public int[] sqlTypes() {
return new int[]{Types.DECIMAL};
}

public Class<Decimal> returnedClass() {
return BigDecimal.class;
}

public boolean equals(Object x, Object y) {
if (x == y) {
return true;
}
if (x == null || y == null) {
return false;
}
return x.equals(y);
}

public int hashCode(Object x) {
return 0;
}

public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws SQLException {
BigDecimal forReading = rs.getBigDecimal(names[0]);

if (forReading == null) {
return null;
}

return forReading.setScale(2, RoundingMode.HALF_EVEN); //round to 2 decimal places
}


public void nullSafeSet(PreparedStatement st, Object value, int index) throws SQLException {
if (value == null) {
st.setNull(index, Types.NUMERIC);
return;
}


BigDecimal forSaving = (BigDecimal) value;
st.setBigDecimal(index, forSaving.setScale(2, RoundingMode.HALF_EVEN));
}

public Object deepCopy(Object value) {
return value;
}

public boolean isMutable() {
return false;
}

public Serializable disassemble(Object value) {
return null;
}

public Object assemble(Serializable cached, Object owner) {
return null;
}

public Object replace(Object original, Object target, Object owner) {
return original;
}

public void setParameterValues(Properties parameters) {
}
}



The named queries are also shown above with the @NamedNativeQueries and @NamedNativeQuery annotations. The parametrized values like :median_salary needs to be supplied via the Hibernate repository class that makes use of the Employee domain object. Firstly define the interface.

package com.myapp.domain.repo;

import java.util.List;


public interface EmployeeTableRepository {

Employee saveEmployee(Employee employee) throws RepositoryException ;
Employee loadEmployee(Long employeeId) throws RepositoryException ;
List<Employee> findAllEmployeesWithHighSalary(BigDecimal medianSalary) throws RepositoryException;
List<Employee> findAllEmployeesWithLowSalary(BigDecimal medianSalary) throws RepositoryException

}




Next the implementation of the above interface.
package com.myapp.domain.repo;


@SuppressWarnings("unchecked")
public class EmployeeTableHibernateRepository extends HibernateDaoSupport implements EmployeeTableRepository {

public EmployeeTableHibernateRepository (HibernateTemplate hibernateTemplate) {
setHibernateTemplate(hibernateTemplate);
}

//The employee objects gets constructed and passed to repo via the Business Service layer
public Employee saveEmployee(Employee employee) throws RepositoryException {
Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
session.saveOrUpdate(employee);
session.flush();
session.evict(employee);
return this.loadEmployee(employee.getId());
}

public Employee loadEmployee(Long employeeId) throws RepositoryException {
Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
Criteria crit = session.createCriteria(Employee.class);
crit.add(Restrictions.eq("id",employeeId));
List<Employee> employees = crit.list();
if (employees.size() == 1) {
return employees.get(0);
}

//this is a custom exception class
throw new RepositoryException("Found more than one or no employee with Id:" + employeeId);
}


public List<Employee> findAllEmployeesWithHighSalary(BigDecimal medianSalary) throws RepositoryException {
Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
Query query = session.getNamedQuery("HighSalary"); // query name defined in Employee class
query.setBigDecimal(":median_salary", medianSalary); // query parameter defined in Employee class
return (List<Employee>) query.list();
}

public List<Employee> findAllEmployeesWithLowSalary(BigDecimal medianSalary) throws RepositoryException {
Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
Query query = session.getNamedQuery("LowSalary"); // query name defined in Employee class
query.setBigDecimal(":median_salary", medianSalary); // query parameter defined in Employee class
return (List<Employee>) query.list();
}


//other methods can be defined here
}

The Service classes shown below will be making use of the repository (or DAO) classes. The service class can use any number of the repository classes, and also responsible for cordinating the transaction as well with a TransactionManger. In the example below, we will be using the "PlatformTransactionManager" implementation provided by the Spring framework.
package com.myapp.service;

public interface EmployeeService {

Employee saveEmployee(Employeee employee) throws RepositoryException;
Employee loadEmployee(Long employeeId) throws RepositoryException;

}

The implementation class is shown with the transaction manager. The employeeRepository and transactionManager are dependency injected
package com.myapp.service;


import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
//....other imports

public class EmployeeServiceImpl implements EmployeeService {


private final EmployeeTableRepository employeeRepository;
private PlatformTransactionManager transactionManager;

public EmployeeServiceImpl (EmployeeTableRepository employeeRepository, PlatformTransactionManager transactionManager) {
this.employeeRepository = employeeRepository;
this.transactionManager = transactionManager;
}


public Employee saveEmployee(Employeee employee) throws RepositoryException {
TransactionStatus transactionStatus =
transactionManager.getTransaction(new DefaultTransactionDefinition(
TransactionDefinition.PROPAGATION_REQUIRED));
try {
employee = this.employeeRepository.saveEmployee(employee);
} catch (Exception e) {
transactionManager.rollback(transactionStatus);
throw new RepositoryException(e);
} finally {
if (!transactionStatus.isCompleted()) {
transactionManager.commit(transactionStatus);
}
}
return employee;
}

public Employee loadEmployee(Long employeeId) throws RepositoryException {
return this.employeeRepository.loadEmployee(employeeId);
}


//....other methods

}




Q. How will you wire up the code snippet discussed above using Spring?
A. The following 3 Spring configuration files are used for wiring up the classes defined above.


  • The daoContext.xml file to define the hibernate session factory, jndi data source, hibernate properties, and the user defined domain class and the repository.
  • The transactionContext.xml file to define the transaction manager.
  • The servicesContext.xml to define the custom services class


Firstly the daoContext.xml file:


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

<bean id="dataSourceMyDB" class="org.springframework.jndi.JndiObjectFactoryBean" scope="singleton">
<property name="jndiName">
<value>java:comp/env/jdbc/dataSource/mydb</value>
</property>
</bean>

<bean id="hibernateProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="properties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SybaseDialect</prop>
<prop key="hibernate.generate_statistics">false</prop>
<prop key="hibernate.hbm2ddl.auto">verify</prop>
<prop key="hibernate.jdbc.batch_size">50</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.cache.use_query_cache">false</prop>
<prop key="hibernate.cache.use_second_level_cache">false</prop>
<prop key="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</prop>
</props>
</property>
<property name="location">
<value>classpath:/hibernate.properties</value>
</property>
</bean>

<bean id="hibernateAnnotatedClasses" class="org.springframework.beans.factory.config.ListFactoryBean">
<property name="sourceList">
<list>
<value>com.myapp.domain.model.Employee</value>
</list>
</property>
</bean>

<bean id="hibernateSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSourceShadow" />
<property name="hibernateProperties">
<ref local="hibernateProperties" />
</property>
<property name="entityInterceptor">
</property>
<property name="annotatedClasses">
<ref local="hibernateAnnotatedClasses" />
</property>
<property name="annotatedPackages">
<list></list>
</property>
</bean>

<bean id="daoTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<constructor-arg index="0" ref="sessionFactory" />
<constructor-arg index="1" value="true" />
</bean>

<!-- Repository beans -->
<bean id="employeeTableRepository" class="com.myapp.domain.repo.EmployeeTableHibernateRepository">
<constructor-arg ref="daoTemplate" />
</bean>

</beans>



The transactionContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

<!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->

<alias name="hibernateSessionFactory" alias="sessionFactory"/>

<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="advisorAutoProxy" class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" />
<bean id="transactionAttrSource" class="org.springframework.transaction.interceptor.TransactionAttributeSourceAdvisor">
<property name="transactionInterceptor" ref="transactionInterceptor" />
</bean>
<bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager" ref="transactionManager" />
<property name="transactionAttributeSource">
<bean class="org.springframework.transaction.annotation.AnnotationTransactionAttributeSource" />
</property>
</bean>

</beans>



Finally the servicesContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<!-- CONFIGURE SERVICE BEANS -->
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<bean id="employeeService" class="com.myapp.service.EmployeeService">
<constructor-arg ref="employeeTableRepository" />
<constructor-arg ref="transactionManager" />
</bean>

</beans>

Q. How will you go about writing an integration or unit test for the EmployeeService described above?
A. Since the dataSource is looked up via JNDI, you need to emulate the JNDI lookup.  This can be achieved with the Spring helper classes SimpleNamingContextBuilder and DriverManagerDataSource.

This involves 3 steps.

  • Define a bootsrapper class that emulates JNDI lookup using Spring helper classes like SimpleNamingContextBuilder and DriverManagerDataSource. For example, SybaseDevBootstrapper.java file.
  • Wire-up this via a Spring config file named sybaseDevBootstrapContext.xml.
  • Finally, write the JUnit test class EmployeeServicesSybTest.java.
  • Define the TestExecutionListeners if required.
 Firstly the SybaseDevBootstrapper.java


package com.myapp.test.db;

import javax.naming.NamingException;

import org.springframework.beans.factory.BeanCreationException;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.mock.jndi.SimpleNamingContextBuilder;

/**
* helper class to bootstrap the sybase database datasources
*/
public class SybaseDevBootstrapper {

public static final String JNDI_BINDING_DB = "java:comp/env/jdbc/dataSource/mydb";
public static final String DRIVER_CLASS = "com.sybase.jdbc3.jdbc.SybDriver";

private SimpleNamingContextBuilder builder; //Spring JNDI emulator class

/**
* setup sybase databases, and bind to specific places in jndi tree
*/
public void start() {
try {
builder = SimpleNamingContextBuilder.emptyActivatedContextBuilder();

DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName(DRIVER_CLASS);
ds.setUrl("jdbc:sybase:Tds:host-name:10004/my_db");
ds.setUsername("user");
ds.setPassword("pwd");
builder.bind(JNDI_BINDING_DB, ds);


} catch (NamingException e) {
throw new BeanCreationException(e.getExplanation());
}
}

public void stop() {
builder.deactivate();
builder.clear();
}
}




Next, wire the above Java class.



<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd"
default-autowire="byName">

<bean id="sybaseDevBootstrapper" class="com.myapp.test.db.SybaseDevBootstrapper" init-method="start" destroy-method="stop"/>

</beans>



Finally the test class EmployeeServicesSybTest.java


package com.myapp.test.services;

import javax.annotation.Resource;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;

//...other imports


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={
"classpath:/sybaseDevBootstrapContext.xml",
"classpath:/transactionContext.xml",
"classpath:/daoContext.xml",
"classpath:/servicesContext.xml",
})
@TestExecutionListeners(value = {
DependencyInjectionTestExecutionListener.class,
SessionBindingHibernateListener.class
})

public class EmployeeServicesSybTest {

@Resource
EmployeeService employeeService;

@Test
public void testSaveEmployee() throws RepositoryException {
Assert.assertTrue(employeeService != null);

Employee employee = new Emloyee();
//....assign values here

employeeService.seaveEmployee(employee);

}

}


The JUnit's way of setting up cross cutting concerns like security, locale, currency, timezone, and any other pre-initilization rules for the test cases function correctly is via annoattions like @Before and @After. The Spring's TestContext framework uses the anootation @TestExecutionListeners to acheive setting up of these cross cutting concerns. In the above example, we are using the DependencyInjectionTestExecutionListener.class from the Spring framework to provide support for dependncy injection and the custom SessionBindingHibernateListener.class to bind the session to the current thread. The custom implementation shown below extends the AbstractTestExecutionListener, which is the abstract implementation of TestExecutionListener class from the Spring framework.





/**
* Helper class for binding sessions to the current thread
*
*/
public class SessionBindingHibernateListener extends SessionBindingListener {

private static final String BEAN_NAME = "hibernateSessionFactory";

public SessionBindingHibernateListener() {
super(BEAN_NAME);
}
}








import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.SessionHolder;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.support.AbstractTestExecutionListener;
import org.springframework.transaction.support.TransactionSynchronizationManager;


/**
* Helper class for binding sessions to the current thread
*
*/
public class SessionBindingListener extends AbstractTestExecutionListener {

private final String beanName;

public SessionBindingListener(String beanName) {
this.beanName = beanName;
}

@Override
public void prepareTestInstance(TestContext testContext) throws Exception {
ApplicationContext context = testContext.getApplicationContext();
SessionFactory sessionFactory = (SessionFactory) context.getBean(beanName);

Session session = SessionFactoryUtils.getSession(sessionFactory, true);
session.setFlushMode(FlushMode.MANUAL);
if (!TransactionSynchronizationManager.hasResource(sessionFactory)) {
TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
}
}
}


Java J2EE Spring Spring Interview Questions and Answers: Hibernate integration

Q. How would you integrate Hibernate with Spring?
A. The hibernate can be wired up via Spring as shown below.

STEP 1: The Hibernate properties.

   
   <!--  hibernate properties-->
   <bean id="myappHibernateProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="properties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.SybaseDialect</prop>
                <prop key="hibernate.show_sql">false</prop>
                <prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.SingletonEhCacheProvider</prop>
            </props>
        </property>
    </bean>


STEP 2: The DataSource.

    
   
 <!-- datasource configured via JNDI-->   
  <bean id="myappDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName">
            <value>java:comp/env/jdbc/dataSource/myapp-ds</value>
        </property>
  </bean>   

 
 STEP 3: The hibernate mapping files. The mapping file tells Hibernate what table in the database it has to access, and what columns in that table it should use.


    
 
   <bean name="myappHibernateMappingFiles" class="org.springframework.beans.factory.config.ListFactoryBean">
        <property name="sourceList">
            <list>
                <value>hbm/Order.hbm.xml</value>
                <value>hbm/Trade.hbm.xml</value>
                <value>hbm/Customer.hbm.xml</value>
            </list>
        </property>
    </bean>
   
   
STEP 4: An empty interceptor

    
   
    <!-- An interceptor that does nothing. May be used as a base class for application-defined custom interceptors. -->
    <bean id="myappEntityInterceptor" class="org.hibernate.EmptyInterceptor" />
   

   
STEP 5: Usually an application has a single SessionFactory instance and threads servicing client requests obtain Session instances from this factory.

    
   
    <!-- Define the session factory -->
    <bean name="myappSessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" autowire="byName">
        <property name="hibernateProperties">
            <ref bean="myappHibernateProperties"/>
        </property>
        <property name="dataSource">
            <ref bean="myappDataSource"/>
        </property>
        <property name="mappingResources">
            <ref bean="myappHibernateMappingFiles"/>
        </property>
        <property name="entityInterceptor">
            <ref bean="myappEntityInterceptor"/>
        </property>
    </bean>
   

STEP 6: The hibernate template. Helper class that simplifies Hibernate data access code.    

    
   
    <!-- Hibernate Template -->
    <bean name="myappHibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate" autowire="no" scope="prototype">
        <property name="sessionFactory">
            <ref bean="myappSessionFactory"/>
        </property>
        <property name="allowCreate">
            <value>false</value>
        </property>
        <property name="maxResults">
            <value>50000</value>
        </property>
        <property name="flushMode">
            <value>3</value>
        </property>
    </bean>

   
STEP 7: The repository class for data access logic.

    
   
    <!-- Constructor Inject the Template into your Repository classes  (Data acess layer)  -->
     <bean id="myappOrderRepository" class="com.HibernateOrderRepository">
        <constructor-arg><ref bean="myappHibernateTemplate" /></constructor-arg>
    </bean>

   
STEP 8: The service class that uses one or more repositories.    

    
     
     <!-- Service Layer: myappOrderRepository is injected via setter injection  -->
     <bean id="myappOrderService" class="com.OrderServiceImpl">
           <property><ref bean="myappOrderRepository" /></property>
    </bean>
   

 STEP 9: The repository interface and class that makes use if the hibernate template.

    
package com;

import com.ObjectNotFoundException;

public interface OrderRepository {
    public Order load(Long identity) throws ObjectNotFoundException;
    public void save(Order order);
}



The template.load, template.save, etc are database operations via the HibernateTemplate.

    
package com;

import org.apache.log4j.Logger;
import org.springframework.orm.hibernate3.HibernateObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.ObjectNotFoundException;
import com.Order;
import com.OrderRepository;


public class HibernateOrderRepository implements OrderRepository {
   
    private static final Logger LOG = Logger.getLogger(HibernateOrderRepository.class);

    private final HibernateTemplate template;
 

    public HibernateOrderRepository(HibernateTemplate template) {
        this.template = template;
    }

    @Override
    /**
     * Read Order from database
     */
    public Order load(Long identity) throws ObjectNotFoundException {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Loading " + identity);
        }
        try {
            return template.load(Order.class,identity);
        } catch (HibernateObjectRetrievalFailureException e) {
            throw new ObjectNotFoundException(identity + " not found", e);
        }
    }

    /**
     * Save the record to database
     * @param order     */
    public void save(Order order) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Saving " + order);
        }
        template.save(order);
    }
}



Q: How do you wire up a transaction manager?
A:

STEP 1: Define a transaction manager.

<!-- Transaction Manger -->
<bean name="myappTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="myappSessionFactory" />
</bean>


STEP 2: Create a transaction interceptor that uses the above transaction manager.

<bean id="myappHibernateInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager" ref="myappTransactionManager" />
<property name="transactionAttributes">
<props>
<prop key="*">PROPAGATION_REQUIRED,-Exception</prop>
</props>
</property>
</bean>


STEP 3: Create other optional interceptors for logging, deadlock retry, etc.

<!-- SERVICE INTERCEPTORS -->

<bean id="myappLoggingInterceptor" class="com.MyAppLoggingInterceptor" />
<bean id="myappDeadlockRetryInterceptor" class="com.OracleDeadlockRetryInterceptor" />

STEP 4: Wire up the interceptors to an abstract service

<!-- SERVICES -->

<bean id="myappAbstractService" abstract="true" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interceptorNames">
<list>
<value>myappLoggingInterceptor</value>
<value>myappDeadlockRetryInterceptor</value>
<value>myappHibernateInterceptor</value>
</list>
</property>
</bean>


STEP 5: The concrete service that uses the myappOrderRepository along with the interceptors. Especially the "myappHibernateInterceptor" that performs transaction demarcation.

<bean id="myappOrderService" parent="myappAbstractService">
<property name="proxyInterfaces">
<value>com.mgl.mts.oms.model.service.OrderService</value>
</property>
<property name="target">
<bean class="com.OrderServiceImpl">
<constructor-arg><ref bean="myappOrderRepository" /></constructor-arg>
</bean>
</property>
</bean>



STEP 6 The OrderServiceImpl class looks like

package com;

import ....

public class OrderServiceImpl implements OrderService {

private final Logger LOG = Logger.getLogger(OrderServiceImpl.class);

private final OrderRepository orderRepository;

public OrderServiceImpl(OrderRepository orderRepository) {
this.orderRepository = orderRepository;
}

//......
}

Note: The OrderServiceImpl will have the interceptors turned using AOP to manage transaction, logging, and deadlock retry. The diagram below gives a big picture of interceptors, service, and repository.


Note: The deadlock retry filter is an interesting one. When an exception is thrown, it is inspected using a pattern matching (i.e. regular expression)  to see if it is due to deadlock. If it is due to deadlock the invocation is repeated. This makes the call again to the target, which is the OrderServiceimpl via the TransactionInterceptor, which starts a new transaction.


Here is an example of the custom interceptor -- myappLoggingInterceptor. Aspect-Oriented Programming (AOP) offers a better solution to many problems. he AOP Alliance project (aopalliance-x.x.jar) is a joint open-source project between several software engineering people who are interested in AOP and Java.


package com.test;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;


public class MyAppLoggingInterceptor implements MethodInterceptor {

private static final Logger LOG = Logger.getLogger(MyAppLoggingInterceptor.class);

@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
long begin = System.currentTimeMillis();

//proceed to the next interceptor on the chain
Object result = invocation.proceed();

long end = System.currentTimeMillis();;

LOG.info("Time elapsed " + (end - begin) + " ms");

return result;
}

}


The deadlock retry interceptor


package com.test;

import java.sql.SQLException;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;


public class OracleDeadlockRetryInterceptor implements MethodInterceptor {

private static final Logger LOG = Logger.getLogger(OracleDeadlockRetryInterceptor.class);

private int attempts = 3;

@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
return doInvoke(invocation, 1);
}

private Object doInvoke(MethodInvocation invocation, int count) throws Throwable {
try {
//proceed to next interceptor
return invocation.proceed();
} catch (Exception exception) {
if (!isDeadlockException(exception)) {
throw exception;
}
LOG.warn("A Database deadlock occured. Will try again.", exception);
if (count < attempts) {
count++;
return doInvoke(invocation, count);
}
throw new SQLException("Service Invocation failed " + attempts
+ " times with a SQLException.", exception);
}
}

} 

More Spring Interview Questions and Answers

Spring Framework Hibernate automatic dirty checking of persistent objects and handling detached objects



Q. What do you understand by automatic dirty checking in Hibernate?
A. Dirty checking is a feature of hibernate that saves time and effort to update the database when states of objects are modified inside a transaction. All persistent objects are monitored by hibernate.It detects which objects have been modified and then calls update statements on all updated objects.

Hibernate Session contains a PersistenceContext object that maintains a cache of all the objects read from the database as a Map. So, when you modify an object within the same session, Hibernate compares the objects and triggers the updates when the session is flushed. The objects that are in the PersistenceContext are pesistent objects.

Q. How do you perform dirty checks for detached objects?
A. When the session is closed, the PersistenceContext is lost and so is the cached copy, and the persistent object becomes a detached object. Detached objects can be passed all the way to the presentation layer.  When you reatch a detached object through merge( ), update( ), or saveOrUpdate( ) methods, a new session is created with an empty PersistenceContext, hence there is nothing to compare against to perform the dirty check. Here is how you overcome this scenario with the help of the following annotation selectBeforeUpdate = true, by default it is set to false.


To save the change to a detached object, you do something like


employee.setLastname("Smith");              // modifying a detached object
Session sess = sessionFactory.getSession(); // open a new session with an empty PersistenceContext
Transaction tx = sess.beginTransaction(); //begin a new transaction
sess.update(employee); //The detached object becomes a persistent object by reattaching
employee.setFirstName("John"); //modify the persistent object
tx.commit();


When the update() call is made, hibernate issues an SQL UPDATE statement. This happens irrespective of weather the object has changed after detaching or not. One way to avoid this UPDATE statement while reattaching is by setting the select-before-update= “true”. If this is set, hibernates tries to determine if the UPDATE needed by executing the SELECT statement.

@Entity
@org.hibernate.annotations.Entity(selectBeforeUpdate = true)
@Table(name = "tbl_employee")
public class Employee extends MyAppDomainObject implements Serializable {
.....
}


In rare scenarios, where you are confident that a particular object can never be modified, hence you can tell hibernate that an UPDATE statement will never be needed by setting the following annotation

@Entity
@org.hibernate.annotations.Entity(mutable = false)
@Table(name = "tbl_employee")
public class Employee extends MyAppDomainObject implements Serializable {
.....
}


Alternatively, if you want to decide if an object's state has changed or not and then decide if a redundant update call to be made or not, you can implement your own DirtyCheckInterceptor by either implementing Hibenate's Inteceptor interface or extending the EmptyInterceptor class. The interceptor can be bootstrapped as shown below

SessionFactory.openSession( new DirtyCheckInterceptor() );


and, Hibernate's FlushEntityEventListener's onFlushEntity implementation calls the registered interceptor before making an update call.

Another possible approach would be to clone the detached objects and store it somewhere in a HttpSession and then use that to populate the PersistenceContext when reattaching the object. For example,

Session sess = sessionFactory.getSession();
PersistenceContext persistenceContext = session instanceof SessionImpl ? ((SessionImpl) session).getPersistenceContext(): null;

if (persistenceContext != null) {
addPreviouslyStoredEntitiesToPersistenceContext(persistenceContext, storedObjects);
}



Q. What do you understand by the terms optimistic locking versus pessimistic locking?
A. Optimistic locking means a specific record in the database table is open for all users/sessions. Optimistic locking uses a strategy where you read a record, make a note of the version number and check that the version number hasn't changed before you write the record back. When you write the record back, you filter the update on the version to make sure that it hasn't been updated between when you check the version and write the record to the disk. If the record is dirty (i.e. different version to yours) you abort the transaction and the user can re-start it.

You could also use other strategies like checking  the timestamp or all the modified fields (this is useful for legacy tables that don't have version number or timestamp column). Note: The strategy to compare version numbers and timestamp will work well with detached hibernate objects as well. Hibernate will  automatically manage the version numbers.

In Hibernate, you can use either long number or Date for versioning

@Version
private long id;


or

@Version
private Date version;


and mark

@Entity
@org.hibernate.annotations.Entity(selectBeforeUpdate = true, optimisticLock=OptimisticLockType.VERSION)
@Table(name = "tbl_employee")
public class Employee extends MyAppDomainObject implements Serializable {
.....
}


if you have a legacy table that does not have a version or timestamp column, then use either

@Entity
@org.hibernate.annotations.Entity(selectBeforeUpdate = true, optimisticLock=OptimisticLockType.ALL)
@Table(name = "tbl_employee")
public class Employee extends MyAppDomainObject implements Serializable {
.....
}


for all fields and

@Entity
@org.hibernate.annotations.Entity(selectBeforeUpdate = true, optimisticLock=OptimisticLockType.DIRTY)
@Table(name = "tbl_employee")
public class Employee extends MyAppDomainObject implements Serializable {
.....
}


for dirty fileds only.

Pessimistic locking means a specific record in the database table is open for read/write only for that current session. The other session users can not edit the same because you lock the record for your exclusive use until you have finished with it. It has much better integrity than optimistic locking, but requires you to be careful with your application design to avoid deadlocks. In pessimistic locking, appropriate transaction isolation levels need to be set, so that the records can be locked at different levels. The general isolation levels are

  • Read uncommitted isolation
  • Read committed isolation
  • Repeatable read isolation
  • Serializable isolation


It can be dangerous to use "read uncommitted isolation" as it uses one transaction’s uncommitted changes in a different transaction. The "Serializable isolation"  is used to protect phantom reads, phantom reads are not usually problematic, and this isolation level tends to scale very poorly. So, if you are using pessimistic locking, then read commited and repeatable reads are the most common ones.

J2EE Spring Hibernate 1.4. Advantages of MVC Architecture

Since there are multiple layers representing multiple logics there will be clean separation of roles or logics.
  • Modification of one logic does not effect other logics.
  • Easy to maintain and enhance the project.
  • Parallel development is possible due to this productivity is very good.
  • Project Leader divides a team into two parts.
  • 1. Web Authors
  • 2. J2EE Developers.
1.Web Authors : These programmers use JSP in developers presentation logic of the application.
2.J2EE Developers: These programmers use J2EE technologies like servlets EJB and e.t.c, to develop integration logic and business logic, persistence logic of the application.
While working with EJB , Spring and Hibernate technologies in model layer we can take the advantage of built in middle ware services due to this programmer will not be over burdened.

Java J2EE Spring Simple Hibernate Example on Inserting Employee details using MySql

Hibernate is a solution for object relational mapping and a persistence management solution or persistent layer. This is probably not understandable for anybody learning Hibernate.

What you can imagine is probably that you have your application with some functions (business logic) and you want to save data in a database. When you use Java all the business logic normally works with objects of different class types. Your database tables are not at all objects.

Hibernate provides a solution to map database tables to a class. It copies the database data to a class. In the other direction it supports to save objects to the database. In this process the object is transformed to one or more tables.

Saving data to a storage is called persistence. And the copying of tables to objects and vice versa is called object relational mapping.

Example program on Hibernate.

Required jars to run simple hibernate program.

antlr-2.7.6
commons-collections-3.1
dom4j-1.6.1
hibernate3
hsqldb
javassist-3.4.GA
jta-1.1
slf4j-api-1.5.6
slf4j-simple-1.5.6

download the jar files of Hibernate.
To run the Hibernate program we need four elements or files.
They are:

1.PojoClass.java
2.hibernate.cfg.xml
3.pojoclass.hbm.xml
4.ClientFile.java (with main method)

In our Example the files are:


In our example we are using MySql database.For that we need the driver_class,connection_url,username,password,MySqldialect.
These are configured in hibernate.cfg.xml file to configure the MySql database.

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

<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://192.168.1.101:3306/TEST</property>
<property name="connection.username">test</property>
<property name="connection.password">test</property>

<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>

<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>

<!-- Mapping files -->
<mapping resource="com/javabynataraj/empdet.hbm.xml"/>


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

Then by providing mapping to the java pojo class to database table we can do the operations whether inserting the data or updating or deleting using Session,SessionFactory,Transaction interfaces and Configuration class.

The pojo class Example:

package com.javabynataraj;

import java.io.Serializable;

public class Empdet implements Serializable{

int eno;
String ename;
int esal;
String eadd;

public Empdet(){

}

public int getEno() {
return eno;
}
public void setEno(int eno) {
this.eno = eno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public int getEsal() {
return esal;
}
public void setEsal(int esal) {
this.esal = esal;
}
public String getEadd() {
return eadd;
}
public void setEadd(String eadd) {
this.eadd = eadd;
}
}

Only the data is going to inserted or updated scenarios we use Transaction ,for select query we don't use Transaction.

Write  a pojo class to get and set the values from database and the user.And we can do serialize the pojo class object .And we have to write a constructor for this class additionally.

We have taken here four variables based on table in database.
    int eno;
    String ename;
    int esal;
    String eadd;

And Map the pojo calss names and database table columns in empdet.hbm.xml as below given:
Java Persistence with Hibernate


<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class name="com.javabynataraj.Empdet" table="empdet">

<id name="eno" type="int" column="eno">
<generator class="increment"/>
</id>
<property name="ename" type="string" column="ename" />
<property name="esal" type="int" column="esal" />
<property name="eadd" type="string" column="eadd" />
</class>

</hibernate-mapping>

The final step is writing Clientfile(Empdetails.java)to insert employee details in the database table using pojo class.

package com.javabynataraj;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class Empdetails {
public static void main(String[] args) {

Configuration conf = new Configuration().configure();
SessionFactory factory = conf.buildSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();

Empdet edet = new Empdet();

edet.setEno(1);
edet.setEname("murali");
edet.setEsal(5000);
edet.setEadd("Chennai");

session.save(edet);

tx.commit();
System.out.println("The data has been saved......");
}

}

After running your Client file (Empdetails.java)as normal java program.then you will display with hibernate query and the last given print statement.
Given below..

The database table in MySql is:

based on given primary key generation the eno will generate automatically by increment order.

Download the above Example Here.

For Reference:
Harnessing Hibernate

Java J2EE Spring What is lazy loading in Hibernate?

Lazy setting decides whether to load child objects while loading the Parent Object.You need to do this setting respective hibernate mapping file of the parent class.lazy = true (means not to load child)By default the lazy loading of the child objects is true. This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent.In this case hibernate issues a fresh database call to load the child when getChild() is actully called on the Parent object.But in some cases you do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database.
                     
                                Example: lazy=true (default)Address child of User class can be made lazy if it is not required frequently. lazy=false but you may need to load the Author object for Book parent whenever you deal with the book for online bookshop.

Lazy fetching means for example in hibernate if we use load() method then load() is lazy fetching i.e it is not going to touch the database until we write empobject.getString( eno );So when we write above statement in that instance it touch the database and get all the data from database. It is called as lazy loading.If we see another example i.e session.get(...) method is used then at that instance it is going to touch the database and get the data and place the data in session object it is called as eager loading.

Java J2EE Spring Hibernate load( ) vs get( )

The following Hibernate code snippet retrieves a User object from the database:

load()
--------------
1). Only use the load() method if you are sure that the object exists.
2). load() method will throw an exception if the unique id is not found in the database.
3). load() just returns a proxy by default and database won’t be hit until the proxy is first invoked.



Session session = << Get session from SessionFactory >>
Long itemId = << Get the item id from request >>

try{
Item item = session.load(Item.class, itemId);
Bid bid = new Bid();
bid.setItem(item);
session.saveOrUpdate(bid);
} catch(ObjectNotFoundException e) {
log.error("Bid placed for an unavailable item");
// Handle the error condition appropriately
}


get( )
---------
1). If you are not sure that the object exists, then use one of the get() methods.
2). get() method will return null if the unique id is not found in the database.
3). get() will hit the database immediately. 


Session session = << Get session from SessionFactory >>
Long itemId = << Get the item id from request >>

Item item = (Item) session.get(Item.class, itemId);

if(item != null) {
Bid bid = new Bid();
bid.setItem(item);
session.saveOrUpdate(bid);
} else {
log.error("Bid placed for an unavailable item");
// Handle the error condition appropriately
}


For References:

 Java Persistence with Hibernate Hibernate in Action (In Action series) Hibernate Recipes: A Problem-Solution Approach (Expert's Voice in Open Source)

Spring Hibernate Spring and Hibernate simple JDBC example



Q. How would you go about using Spring and Hibernate frameworks to make JDBC calls?
A.

STEP 1: Firstly, define the environment specific data in a properties file named datastore.properties with datasource details

jdbc.driver=com.sybase.jdbc3.jdbc.SybDriver
jdbc.url=jdbc:sybase:Tds:serverName:2000/my_database
jdbc.username=user
jdbc.password=password

STEP 2: Define the spring context file (myAppContext.xml) to wire up the data source and data access objects

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util"
xmlns:batch="http://www.springframework.org/schema/batch"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd
http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">



<!-- STEP1: read configuration data from .properties file -->
<context:property-placeholder location="classpath:datastore.properties" />

<!-- STEP2: Data Source -->
<bean id="dataSourceMyDs" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>

<!-- STEP3: Hibernate Properties like dialect, showSql, etc -->
<bean id="hibernateProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="properties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SybaseDialect</prop>
<prop key="hibernate.generate_statistics">false</prop>
<prop key="hibernate.hbm2ddl.auto">verify</prop>
<prop key="hibernate.jdbc.batch_size">50</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.cache.use_query_cache">false</prop>
<prop key="hibernate.cache.use_second_level_cache">false</prop>
<prop key="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</prop>
</props>
</property>
<property name="location">
<value>classpath:/hibernate.properties</value>
</property>
</bean>

<!-- Hibernate annotated classes for ORM -->
<bean id="hibernateAnnotatedClasses" class="org.springframework.beans.factory.config.ListFactoryBean">
<property name="sourceList">
<list>
<value>com.myapp.domain.model.Account</value>
<
</list>
</property>
</bean>

<!-- STEP 4: define the hibernate session factory that makes use of the dataSourceMyDs & hibernateProperties defined in step 2 & 3 respectively-->
<bean id="hibernateSessionFactoryMpApp"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSourceMyDs" />
<property name="hibernateProperties">
<ref bean="hibernateProperties" />
</property>
<property name="annotatedClasses">
<list>
</list>
</property>
<property name="annotatedPackages">
<list></list>
</property>
</bean>

<!-- STEP 5: DAO Template that uses the hibernateSessionFactoryMpApp for direct JDBC and ORM calls-->
<bean id="daoTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<constructor-arg index="0" ref="hibernateSessionFactoryMpApp" />
<constructor-arg index="1" value="true" />
</bean>

<!-- STEP 6: DAO Template gets injected into a DAO class -->

<bean id="accountDao" class="com.myapp.dao.impl.AccountDaoImpl">
<property name="dataSource" ref="dataSourceMyDs" />
</bean>

<!-- If you want to use HibernateTemplate -->
<bean id="accountHibDao" class="com.myapp.dao.impl.AccountHibDaoImpl">
<constructor-arg ref="daoTemplate" />
</bean>

</beans>


The above config shows HibernateTemplate configuration as well, but the ensuing steps focuses on using the data source and the JdbcTemplate.

STEP 3: Define the interface for AccountDaoImpl.

package com.myapp.dao.impl;

public interface AccountDao {

Account getAccount(String accountCode);

}

STEP 4: Define the implementations. The value object (i.e. POJO - Plain Old Java Object) class to map the relational data.

public class Account {

private String accountCode;
private String accountName;

//getters & setters
....
}

The row mapper class that maps relational data to the value object (i.e a POJO)

import java.sql.ResultSet;
import java.sql.SQLException;

public class AccountRowMapper implements RowMapper {

public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
Account account = new Account();
account.setAccountCode(rs.getString("account_code"));
account.setAccountName(rs.getString(account_name"));
return account;
}

}

STEP 5: The data access object implementation that makes use of the POJO and the row mapper classes.

package com.myapp.dao.impl;

public class AccountDaoImpl implements AccountDao {

private JdbcTemplate jdbcTemplate;

public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}



public Account getAccount(String accountCode) {

String sql = "Select account_code, account_name from account where account_code = ?"
Account account = jdbcTemplate.queryForObject(sql, new Object[]{accountCode}, new AccountRowMapper());
return account;
}

}

STEP 6: Finally, you can invoke the data access object from your service or processor classes. Here is a simple class
for demo.

public class MyService {

public static void main(String[] args) throws ClassNotFoundException {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("myAppContext.xml");
AccountDao dao = applicationContext.getBean("accountDao", AccountDao.class);
Account account = dao.getAccount("1234");
//do something with the account
}
}

The JdbcTemplate class comes with many useful overloaded query methods and options to map data.

Q. If you are running your application on an application server, how would you define your datasource properties?
A. The data source will be configured via the application server and the spring config file myAppContext.xml will look up via JNDI as shown below

  <bean id="dataSourceMyDs" class="org.springframework.jndi.JndiObjectFactoryBean" scope="singleton">
<property name="jndiName">
<value>jdbc.dataSource.my_app</value>
</property>
</bean>

Q. How will you go about defining the dependency jars?
A. You need the following framework libraries (Spring and Hibernate) in addition to Java, and the
dependency can be configured via maven pom.xml file.

 <!-- Spring framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>

<!-- Spring AOP dependency -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2</version>
</dependency>

<!-- Sybase database driver -->
<dependency>
<groupId>com.sybase</groupId>
<artifactId>jconn3</artifactId>
<version>6.0</version>
</dependency>

<!-- Hibernate framework -->
<dependency>
<groupId>hibernate</groupId>
<artifactId>hibernate3</artifactId>
<version>3.2.3.GA</version>
</dependency>


<!-- Hibernate library dependecy start -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>

<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>

<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>

<dependency>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
<version>2.7.7</version>
</dependency>

Spring Hibernate Difference between get and load in Hibernate

get vs load in Hibernate
Difference between get and load method in Hibernate is a one of the most popular question asked in Hibernate and spring interviews. Hibernate Session  class provides two method to access object e.g. session.get() and session.load() both looked quite similar to each other but there are subtle difference between load and get method which can affect performance of application. Main difference between get() vs load method is that get() involves database hit if object doesn't exists in Session Cache and returns a fully initialized object which may involve several database call while load method can return proxy in place and only initialize the object or hit the database if any method other than getId() is called on persistent or entity object. This lazy initialization can save couple of database round-trip which result in better performance. By the way there are many articles on interview questions in Java, you can use search button on top left to find them. Some of them like 20 design pattern interview questions and 10 Singleton pattern questions are my favorites, you may also like. Coming back to article, you can find more difference between load and get in rest of this article in point format but this is the one which really makes difference while comparing both of them. If you look at how get and load gets called its pretty identical.
Read more »

Java J2EE Spring Disadvantages of Hibernate

1) Steep learning curve.

2) Use of Hibernate is an overhead for the applications which are :

• simple and use one database that never change
• need to put data to database tables, no further SQL queries
• there are no objects which are mapped to two different tables
Hibernate increases extra layers and complexity. So for these types of applications JDBC is the best choice.

3) Support for Hibernate on Internet is not sufficient.

4) Anybody wanting to maintain application using Hibernate will need to know Hibernate.

5) For complex data, mapping from Object-to-tables and vise versa reduces performance and increases time of conversion.

6) Hibernate does not allow some type of queries which are supported by JDBC. For example It does not allow to insert multiple objects (persistent data) to same table using single query. Developer has to write separate query to insert each object.

Java J2EE Spring JDBC Vs Hibernate


7.1 Why is Hibernate better than JDBC

1)   Relational Persistence for JAVA

Working with both Object-Oriented software and Relational Database is complicated task with JDBC because there is mismatch between how data is represented in objects versus relational database. So with JDBC, developer has to write code to map an object model's data representation to a relational data model and its corresponding database schema. Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this.

2)   Transparent Persistence

The automatic mapping of Java objects with database tables and vice versa is called Transparent Persistence. Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS. With JDBC this conversion is to be taken care of by the developer manually with lines of code.

3)   Support for Query Language

JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database, i.e to select effective query from a number of queries to perform same task. Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application.

4)   Database Dependent Code

Application using JDBC to handle persistent data (database tables) having database specific code in large amount. The code written to map table data to application objects and vice versa is actually to map table fields to object properties. As table changed or database changed then it’s essential to change object structure as well as to change code written to map table-to-object/object-to-table. Hibernate provides this mapping itself. The actual mapping between tables and application objects is done in XML files. If there is change in Database or in any table then the only need to change XML file properties.

5)   Maintenance Cost

With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually. Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java objects. It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost.

6)   Optimize Performance

Caching is retention of data, usually in application to reduce disk access. Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are moved to this cache as a result of query. It improves performance if client application reads same data many


times for same write. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code. With JDBC, caching is maintained by hand-coding.

7)   Automatic Versioning and Time Stamping

By database versioning one can be assured that the changes done by one person is not being roll backed by another one unintentionally. Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates version field of database table every time relational tuple is updated in form of Java class object to that table. So if two users retrieve same tuple and then modify it and one user save this modified tuple to database, version is automatically updated for this tuple by Hibernate. When other user tries to save updated tuple to database then it does not allow to save it because this user does not has updated data. In JDBC there is no check that always every user has updated data. This check has to be added by the developer.

8)   Open-Source, Zero-Cost Product License

Hibernate is an open source and free to use for both development and production deployments.

9)   Enterprise-Class Reliability and Scalability

Hibernate scales well in any environment, no matter if use it in-house Intranet that serves hundreds of users or for mission-critical applications that serve hundreds of thousands. JDBC can not be scaled easily.

Java J2EE Spring Hibernate communication with RDBMS

General steps:

1. Load the Hibernate configuration file and create configuration object. It will automatically load all hbm           mapping files.
2. Create session factory from configuration object
3. Get one session from this session factory.
4. Create HQL query.
5. Execute query to get list containing Java objects.

Example: Retrieve list of employees from Employee table using Hibernate. /* Load the hibernate configuration file */

Configuration cfg = new Configuration(); cfg.configure(CONFIG_FILE_LOCATION);

/* Create the session factory */

SessionFactory sessionFactory = cfg.buildSessionFactory();

/* Retrieve the session */

Session session = sessionFactory.openSession();

/* create query */

Query query = session.createQuery("from  EmployeeBean”);

/* execute query and get result in form of Java objects */ List finalList = query.list();

EmployeeBean.hbm.xml File


"-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">




















Labels

.equals = operator abstract class abstract method abstract window toolkit Access Modifiers accessing java beans accessing javabeans action events actionperformed active addition Advanced Advanced Overloading AdvJavaBooks Agile development ajax alive AMQP and Android anonymous class anonymous inner class Ant ant tutorials anti patterns antipatterns Apache Camel api for jsp api for servlet api for servlets api jsp application context application scope application session Apps Architecture are you eligible for the ocmjd certificaiton are you eligible for the scjd certification arithmetic operator arpanet array construction array declaration array initialization array list array to list conversion arraylist arraylist of strings arraylist of types arraylist questions arraylists Arrays arrays in java ask for help assert assert in java assertions assertions in java assignment assignment operator Atlassian attribute visibility authentication authorization autoboxing autounboxing awt AWT Event Handling awt interview questions AWT Layouts awt questions awt questions and answers backed collection backed collections Basic Basics of event handling bean attributes bean properties bean scope Beginner best practices BigData blocked books boxing buffer size bufferedreader bufferedwriter business delegate business delegate pattern calendar case statement casting in java casting interview questions chapter review choosing a java locking mechanism choosing a locking mechanism choosing a thread locking mechanism class inside a method class questions class with no name class without a name classes interview questions Clipboard closing jsp tags code snap coding cohesion collection generics collection interview questions collection methods collection of types collection questions collection searching collection types Collections Collections Framework collections interview questions collections sorting colors in java swings colors in swing command line arguments communication between threads comparable comparator comparison operators compiling java classes computers concurrency example and tutorial config Configuration ConnectionPooling constructor creation constructor interview questions constructor overloading constructors in java containers contents of deployment descriptor contents of web.xml context context scope converting array to list converting list to array core java core java interview core java interview question core java interview questions core java questions core java; core java; object oriented programming CoreJava CoreJavaBooks CORS coupling create threads creating 2 dimensional shapes creating 2D shapes creating a frame creating a jframe creating a thread creating an arraylist creating an inner class creating an interface creating java beans creating java threads creating javabeans creating threads creating threads in java CSS cURL currency current thread determination custom tag library custom taglib custom taglibs custom tags CVS dao dao design pattern dao factory pattern dao pattern data access object data access object pattern data structure and algorithm database date and time tutorial date format dateformat dates deadlock deadlocks debugging Declarations decorator pattern decrement default deleting sessions deploy web app deployment deployment descriptor deployment descriptor contents deployment of web application deserialization deserialize design pattern design pattern interview questions design patterns Designpatterns destory method destroy destroying sessions determining current thread determining the current thread Developer Differences different types of collections display stuff in a frame displaying images displaying images in java swings displaying images in swings displaying text in a component division do while loop doget dohead dopost doput DOS Downloads drawing a line drawing an ellipse drawing circles drawing ellipses drawing lines Drools tutorial eBooks Eclipse Eclipse Tutorial Encapsulation encapsulation in java enhanced for loop entity facade pattern enumerations enumerations in java enums equal to equals equals comparison error and exception error codes error handling in servlets error page event handling in swings event listeners exam prep tips example servlet Examples exception exception handling exception handling in servlets exception handling interview questions exception handling questions Exceptions exceptions in java exceptions in web applications explicit locking explicit locking of objects file file navigation filereader filewriter final class final method FireBug first servlet FIX protocol FIX Protocol interview questions FIX protocol tutorial font fonts for each loop for loop form parameters form values formatting forwarding requests frame frame creation frame positioning frame swings front controller front controller design pattern front controller pattern fundamental.Java FXML Games garbage collection garbage collection interview questions garbage collection questions garbage collector gc gc questions general generic Generics generics collections Geo get get set methods getattribute getting bean property getting form values getting form values in servlet getting scwcd certified getting servlet initialization parameters getting sun certified Google Graphics2D gregorian calendar handling strings in java hash hash map hash table hashcode hashmap hashset hashtable head head request HeadFirst heap heaps hibernate hibernate interview questions hibernate interview questions and answers hibernate questions hibernate questions and answers Hibernate Tutorial HibernateBooks homework How To HTML HTML and JavaScript html form http request http request handling http request header http request methods http request servlet http request type http session httprequest httprequest methods httpservlet httpservlet interview questions httpservlet interview questions with answers httpsession httpsession interview questions httpsession questions HttpSessionActivationListener HttpSessionAttributeListener HttpSessionBindingListener if if else if else block if else statement Image IO implementing an interface Implicit objects increment info inheritance inheritance in java init init method Initialization Blocks inner class inner class inside a method inner classes innerclass installation instanceof instanceof operator IntelliJ interaction between threads interface interface interview interface questions interfaces interfaces in java interfaces interview questions internet history interrupting a thread interrupting threads Interview interview questions interview questions on design patterns interview questions on exception handling interview questions on java collections interview questions on serialization introduction to java threads introduction to jsps introduction to threading introduction to threads invalidating session Investment Banking IO Package iscurrentthread iterator J2EE j2ee api j2ee design pattern j2ee design pattern interview questions j2ee design patterns j2ee hibernate interview questions j2ee history j2ee interview j2ee interview questions j2ee mvc j2ee mvc pattern j2ee programmer j2ee questions j2ee servlet api j2ee session j2ee struts interview questions java java 5 tutorial Java 8 java arrays java assertions java assignments java awt questions java bean java bean scope java beans java beginners tutorial Java career java certification Java Class java collection interview questions and answers java collection tutorial java collections java collections interview questions java constructors java currency Java CV java data base connectivity java database connectivity java database connectivity interview questions and answers java dates java design pattern java design patterns java developer certification Java EE java encapsulation java enums java event listeners java exceptions java formatting java garbage collection java garbage collector java gc java heap Java I/O java inheritance java input output Java Interface Java Interview Java Interview Answers Java Interview Questions Java Introduction java io java IO tutorial java iterator java jdbc Java JSON tutorial Java Key Areas java lists java literals java locks nested Java Media Framework java methods java multithreading Java multithreading Tutorials java nested locks java networking tutorial java numbers Java Objects java operators java overloading java parsing Java Programming Tutorials java race conditions java regex java regular expressions Java resume java scjp java searching java serialization java server pages java server pages api java server pages questions java spring interview questions. j2ee spring interview questions java stack java strings java swing java swing event listeners java swing frame java swing images java swings java swings images java thread explicit locking java thread lock scope java thread locking java thread locking mechanism java thread locking objects java threads java threads race condition java tips java tokenizing Java Tools Java Tutorial java ui questions Java Utilities java variables java wrappers Java xml tutorial java.lang java8 javabean javabean accessing javabean scope JavaBeans javac JavaEE JavaFX JavaFX 3D JavaFX 8 JavaOne JavaScript JavaTips JDBC jdbc driver jdbc example jdbc interview questions jdbc interview questions and answers jdbc interview questions with answers jdbc sample code JDBC Tutorial jdbc type 1 driver jdbc type 2 driver jdbc type 3 driver jdbc type 4 driver Jdeveloper JDK JDK8 JEE Tutorial jframe jframe creation jframe position jframe positioning JIRA JMeter JMS JMX join() joining threads JPA JQuery JS JSF JSF Tutorial JSONP JSP jsp and java beans jsp and servlets jsp and xml jsp api jsp code jsp compilation jsp conversion jsp directives jsp error page jsp error page directive jsp implicit objects jsp interview jsp interview questions jsp introduction jsp intvw questions jsp life jsp life cycle jsp life-cycle jsp lifecycle jsp page directive jsp questions jsp sample jsp scripting jsp scriptlets jsp servlets jsp summary jsp synopsis jsp tag libraries jsp tag library jsp taglib jsp tags jsp technology jsp to servlet jsp to servlet conversion jsp translation jsp usage jsp usebean jsp xml tags jsp xml tags usage jsp-servlet jsp:getProperty jsp:setProperty jsp:usebean jsps JSTL JUnit testing keyword synchronized keyword volatile Keywords Lambda Expressions Learning libraries life cycle life cycle of a jsp life cycle of a servlet life cycle of a thread life cycle of jsp life cycle of threads lifecycle of a thread linked list linkedhashmap linkedhashset linkedlist linux List listeners lists Literals locale lock manager pattern lock scope locking objects using threads log Logging logging errors logical and logical operators logical or loops loosely coupled making an arraylist making threads sleep making threads sleep for time MapReduce maps maps usage Maven Maven Tutorial max priority member access method arguments method local inner class method overloading method overriding method return types methods creating classes min priority Miscellaneous mobile mock exam model view controller model view controller design pattern model view controller pattern Multi Threading Multi-threading multiple threads multiplication multithreading multithreading in java multithreading interview questions multithreading questions mvc mvc design pattern mvc pattern MyEclipse mysql nested java lock nested java locks nested java thread locks nested locks nested thread locks NetBeans Networking new news nio NonAccess Modifiers norm priority normal inner class Normalization not equal to Notepad notify notifyall number format numberformat numbers object comparison object notify object orientation object oriented object oriented programming Object Oriented Programming in java objects interview questions ocmjd certification ocmjd certification eligibility OO OO Java oops OpenCSV OpenCV opening jsp tags OpenJDK OpenJFX Operators or Oracle Oracle ADF Mobile Oracle Certified Exams oracle certified master java developer oracle database ORM other topics out overloading overloading constructors overloading in java overriding page page directive page scope parsing passing variables passing variables to methods performance Platform Playing with Numbers points to remember polymorphism positioning a frame post practice exam Primitive Casting primitive variables printwriter priority queue priority queues priorityqueue priorityqueues private processing form values Products programming Projects protected public put questions questions on garbage collection questions on java strings queue quick recap quick review race conditions read objects from stream reading http request header RealTime_Tips redirecting to another servlet redirection reference reference variable casting reference variables Refreshing Java regex Regular Expressions regular inner class relational operators reminder request request dispatcher request forwarding request header request object. httpservletrequest request scope requestdispatcher response RESTClient RESTful retrieving values from session return error codes return types returning values runnable runnable interface running running java programs RUP sample jsp sample questions sample questions scwcd sample servlet scanner Scene Builder scjd certification scjd certification eligibility requirements scjp SCJP Certification scjp exam scjp exam questions scjp exam sample questions scjp questions scjp test scjp test questions scope scope of java locks scope of java thread locks scope of locks scripting in jsp scriptlet tags scriptlets scriptlets in jsp pages scwcd scwcd certification scwcd certification practice exam scwcd exam scwcd exam questions scwcd jsp summary scwcd mock exam scwcd mock exam answers scwcd practice exam scwcd practice test scwcd questions scwcd test SDLC searching searching arrays searching collections searching in java searching treemap searching treesets security self assement self assement scwcd self assessment scjp self test self test scjp self test scwcd send error method senderror method sending error code to browser serialization serialization in java serialization interview questions Serialization on Swing serialization questions service service method servlet servlet and forms servlet and jsp servlet api servlet attributes servlet code servlet container servlet context servlet error handling servlet exception handling servlet handling http request servlet initialization servlet initialization parameters servlet interview servlet interview questions servlet interview questions with answers servlet intvw questions servlet life cycle servlet lifecycle servlet questions servlet questions with answers servlet request servlet request dispatcher servlet request type servlet skeleton servletcontext servletcontextevent servletrequest Servlets servlets and jsps servlets api servlets details servlets request handling session session clean up session event listeners session facade pattern session interview questions session invalidation session listeners session management session questions session scope session timeout session tracking through url rewriting set collections set status method setattribute sets setstatus method setting bean property setting request type short circuit operators Singleton sleep sleeping threads soapUI Software Installation sorting sorting arraylist sorting arrays sorting collections special collections special inner classes split spring spring and hibernate interview questions spring batch Spring Core Spring Framework Spring Integration spring interview questions Spring JDBC Spring MVC Spring security Spring tutorial SQL SQL and database tutorial examples SQL Tutorial SSL stack stacks stacks and heaps static static class static declaration static imports static inner static inner class static method Static variable stopped stopping a thread stopping thread stopping threads Stored Procedure storing values in session Streams strictfp StrictMath string string buffer string builder string class string formatting String Handling string interview questions string manupulation string questions string tokenizer stringbuffer stringbuffer questions stringbuilder Strings strings in java struts Struts 1 Struts 1.2 Struts 2 struts framework interview questions struts interview questions struts interview questions with answers struts mvc interview questions struts questions Struts2 StrutsBooks submitting request subtraction Sun Certification sun certified java developer Sun Certified Java Programmer swing swing action performed swing and colors Swing Components swing event handling swing event listeners swing events Swing Hacks swing images Swing Look And Feels swings swings frame switch block switch case block switch case statement Sybase Sybase and SQL Server synchronization synchronized code synchronized keyword synchronized method System Properties tag lib tag library tag-lib taglibs tags TDD Technical Blogging ternary operator Test Driven Development test scjp Testing the context the session the volatile keyword thread thread class thread deadlocks thread interaction thread interruption thread life cycle thread lifecycle thread lock scope thread locks thread notify thread priorities thread race conditions race conditions in threads thread sleep thread states thread stoppage thread stopping thread synchronization thread syncing thread yield Threads threads in java threads interview questions threads life cycle threads questions tibco tightly coupled tips tips and tricks tips.FXML tokenizing Tomcat Tools toString transitions treemap treeset tricks Tricks Bag try catch try catch finally. finally block Tutorial type casting in java ui programming with java swings UML unboxing unit testing unix url rewriting use bean usebean using a arraylist using collections using colors using colours using command line arguments using different fonts using expressions using font using fonts using fonts in swings using hashmap using http session using httpsession using iterator using java beans in jsp using javabean in jsp using javabeans in jsp using javac using lists using maps using request dispatcher using scriptlets using session persistense using sets using special fonts using system properties using the jsp use bean using treeset using use bean Using Variables using volatile Using Wrappers using xml in jsp Util pack value object value object design pattern value object pattern var-args varargs Variable Arguments Variables vector vector questions vectors visibility vo pattern volatile volatile keyword volatile variables wait method waiting web app exception handling web app interview web application deployment web application exceptions web application scope web application security web component developer web component developer certification web context web context interfaces web context listeners web interview questions web security web server web servers Web services web.xml web.xml deployment webapp log weblogic website hacking website security what are threads what is a java thread what is a thread what is thread while loop windows windows 8 wrapper classes wrappers write objects to stream WSAD xml xml and jsp xml tags xslt yield()