Wednesday, June 12, 2013

Apache CXF with Spring RestFull and SOAP based webapplication

Spring provides Apache CXF Integration related jar Files.Just you configured CXF related xml files in your project.

Web.xml:
---------

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
         http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
    <display-name>DiaMeter Rest Application</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
        WEB-INF/cxf.xml
WEB-INF/signup-security.xml
        </param-value>
    </context-param>

    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
            <!--                     CXF related Configurations               -->
    <servlet>
        <display-name>DiaMeter</display-name>
        <servlet-name>CXFServlet</servlet-name>
        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

<servlet>
<servlet-name>signupmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>spring.profiles.active</param-name>
<param-value>test-profile</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>

    <servlet-mapping>
        <servlet-name>CXFServlet</servlet-name>
        <url-pattern>/app/*</url-pattern>
    </servlet-mapping>

<servlet-mapping>
<servlet-name>signupmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<welcome-file-list>
   
   <welcome-file>register.html</welcome-file>
   
</welcome-file-list>
</web-app>


cxf.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:jaxrs="http://cxf.apache.org/jaxrs"
xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util" xmlns:cxf="http://cxf.apache.org/core"
xsi:schemaLocation="
http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd">


<!-- REST -->
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/osgi/cxf-extension-osgi.xml" />

<!-- SOAP -->
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />


<context:component-scan base-package="com.signup" />

<!--PROVIDERS -->

<bean id="wadlProvider" class="org.apache.cxf.jaxrs.model.wadl.WadlGenerator">
<property name="applicationTitle" value="CXF Test sample application" />
</bean>

<bean id="jaxbProvider" class="org.apache.cxf.jaxrs.provider.JAXBElementProvider">
<property name="marshallerProperties" ref="propertiesMap" />
</bean>

<util:map id="propertiesMap">
<entry key="jaxb.formatted.output">
<value type="java.lang.Boolean">true</value>
</entry>
</util:map>

<bean id="jsonProvider" class="org.apache.cxf.jaxrs.provider.JSONProvider">
<property name="namespaceMap" ref="jsonNamespaceMap" />
</bean>

<util:map id="jsonNamespaceMap" map-class="java.util.Hashtable">
<entry key="http://www.example.org/books" value="b" />
</util:map>

<!-- REST SERVER -->

<jaxrs:server id="restContainer" address="/rest">

<jaxrs:providers>
<bean class="org.apache.cxf.jaxrs.cors.CrossOriginResourceSharingFilter" /> 
<ref bean="jaxbProvider" />
<ref bean="jsonProvider" />
<ref bean="wadlProvider" />
</jaxrs:providers>
<jaxrs:serviceBeans>
<ref bean="orgService" /><!-- Here you mention your Service bean name-->
</jaxrs:serviceBeans>

<jaxrs:extensionMappings>
<entry key="xml" value="application/xml" />
<entry key="json" value="application/json" />
</jaxrs:extensionMappings>
</jaxrs:server>

<!-- SOAP SERVER -->


<jaxws:endpoint id="org" implementor="#orgService"
address="/orgSoap" />  <!-- Here you mention your Service bean name-->

<!-- CXF Message logging -->

<cxf:bus>
<cxf:features>
<cxf:logging />
</cxf:features>
</cxf:bus>
<!-- CLIENT -->
<!-- <jaxrs:client id="locationClient" address="http://localhost:8080/rest/" 
serviceClass="org.exampledriven.cxfexample.LocationService" inheritHeaders="true"> 
<jaxrs:headers> <entry key="Accept" value="application/xml"/> </jaxrs:headers> 
</jaxrs:client> -->

<!-- Spring Validation -->
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />

</beans>



signup-security.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:security="http://www.springframework.org/schema/security"
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.xsd
       http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">

<context:component-scan base-package="com.asman.diameter" />


<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.asman.diameter.to.AccuteComplications</value>
<value>com.asman.diameter.to.Contact</value>
<value>com.asman.diameter.to.DiaUsers</value>
<value>com.asman.diameter.to.EyeStatus</value>
<value>com.asman.diameter.to.EyeStatusFor</value>
<value>com.asman.diameter.to.FootStatus</value>
<value>com.asman.diameter.to.FootStatusFor</value>
<value>com.asman.diameter.to.Insulin</value>
<value>com.asman.diameter.to.InsulinType</value>
<value>com.asman.diameter.to.Treatment</value>
<value>com.asman.diameter.to.LabResults</value>
<value>com.asman.diameter.to.LabResultType</value>
<value>com.asman.diameter.to.Oha</value>
<value>com.asman.diameter.to.Organization</value>
<value>com.asman.diameter.to.OtherComplications</value>
<value>com.asman.diameter.to.OtherTreatment</value>
<value>com.asman.diameter.to.Patient</value>
<value>com.asman.diameter.to.PatientNotes</value>
<value>com.asman.diameter.to.SelfCare</value>
<value>com.asman.diameter.to.UserTypes</value>
<value>com.asman.diameter.to.Vitals</value>
<value>com.asman.diameter.to.VitalsMore</value>
<value>com.asman.diameter.to.VitalType</value>
<value>com.asman.diameter.to.ContactTypes</value>
<value>com.asman.diameter.to.Responsible</value>

</list>
</property>
<property name="hibernateProperties">
<props>
   <prop key="show_sql">true</prop>
</props>
</property>
</bean>

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://XXXXXX:XXX/diabase" />
<property name="username" value="XXX" />
<property name="password" value="XXX" />
</bean>


<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
<property name="fetchSize" value="1000" />
</bean>

</beans>


spring-servlet.xml
------------------

<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:mvc="http://www.springframework.org/schema/mvc"
       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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <mvc:annotation-driven/>
    <context:annotation-config/>
    <context:component-scan base-package="demo.oauth.server.controllers"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".html"/>
    </bean>

</beans>


Here defined all organization related methods in OrgnizationService Interface

OrgnizationService.java:
------------------------


package com.asman.diameter.service;

import java.util.List;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.apache.cxf.jaxrs.model.wadl.Description;
import org.apache.cxf.jaxrs.model.wadl.Descriptions;
import org.apache.cxf.jaxrs.model.wadl.DocTarget;

import com.asman.diameter.to.Organization;
import com.asman.diameter.views.OrganizationView;

/**
 * Provides the base restful interface for the Organization service.
 * 
 * <p>
 * Provides the ORG specific service for accessing, adding, deleting and
 * updating ORG profile extension and other ORG specific details. All clients
 * (Web / Mobile) should interact through this class, rather than through the
 * individual ORG manager classes.
 * 
 * <p>
 * 
 * 
 * @author asman
 * 
 */
@Path("/orgnizations/")
@WebService
public interface OrgnizationService {

@WebMethod
@GET
@Path("{org}")
@Descriptions({
@Description(value = "returns a organization data ", target = DocTarget.METHOD),
@Description(value = "the organization data", target = DocTarget.RETURN) })
public OrganizationView getOrganization(
@Description(value = "the string representation of the organization") @PathParam("org") @NotNull @Size(max = 10, min = 3) int organization)
throws Exception;

@WebMethod
@POST
@Descriptions({
@Description(value = "stores a new organization data", target = DocTarget.METHOD),
@Description(value = "the newly created organization data", target = DocTarget.RETURN) })
public void createOrganization(@Valid OrganizationView organizationView)
throws Exception;

@WebMethod
@PUT
@Descriptions({
@Description(value = "updates or creates a new organization data", target = DocTarget.METHOD),
@Description(value = "the newly created organization data", target = DocTarget.RETURN) })
public Integer updateOrganization(@Valid OrganizationView organization);

@WebMethod
@GET
@Path("{orgId}")
@Descriptions({ @Description(value = "delete data ", target = DocTarget.METHOD), })
public Organization deleteOrganization(
@Description(value = "the string representation of the organization") @PathParam("orgId") @NotNull @Size(max = 10, min = 3) int organizationId)
throws Exception;

@WebMethod
@GET
@Descriptions(@Description(value = "Gets All Organizations Data", target = "method"))
@Produces(MediaType.APPLICATION_JSON)
public OrganizationView searchAllOrganization() throws Exception;

}


here i implemented Oraganization related implementation class

OrgnizationServiceImpl.java:
-----------------------------
package com.asman.diameter.service.impl;

import java.util.List;

import javax.jws.WebMethod;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.annotation.XmlElement;

import org.apache.cxf.jaxrs.model.wadl.Description;
import org.apache.cxf.jaxrs.model.wadl.Descriptions;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.asman.diameter.manager.OrganizationManager;
import com.asman.diameter.service.OrgnizationService;
import com.asman.diameter.to.Organization;
import com.asman.diameter.views.OrganizationView;

/**
 * Provides the ORG specific service for accessing, adding, deleting and
 * updating ORG profile extension and other ORG specific details. All clients
 * (Web / Mobile) should interact through this class, rather than through the
 * individual ORG manager classes.
 * 
 * This class is given access to outside world in the form of a restful service.
 * All clients need to interact with this service in restful manner.
 * 
 * 
 * 
 * <p>
 * The documentation for each method in this class describes its implementation
 * in detail.
 * 
 * @author asman
 */
@Service("orgService")  //this Service name used in cxf.xml file
public class OrgnizationServiceImpl implements OrgnizationService {

/*
* @Autowired private OrgProfileManager orgProfileManager;
*/

private SessionFactory sessionFactory;

@Autowired
private OrganizationManager organizationManager;

@XmlElement
List<Organization> organization;

/**
* @return the organization
*/
public List<Organization> getOrganization() {
return organization;
}

/**
* @param organization
*            the organization to set
*/
public void setOrganization(List<Organization> organization) {
this.organization = organization;
}

/**
* @param organizationManager
*            the organizationManager to set
*/
public void setOrganizationManager(OrganizationManager organizationManager) {
this.organizationManager = organizationManager;
}

@Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}

/**
* Updates organization details This method is accessed by restful client as
* web service method.
* @param organization
*            the Organization bean with all details related to organization
* @return organization id for the organization for which the organization
*         details are updated
*/
@Override
@WebMethod
@PUT
@Descriptions({
@Description(value = "updates or creates a new organization data", target = "method"),
@Description(value = "the newly created organization data", target = "return") })
public Integer updateOrganization(@Valid OrganizationView organizationView) {
organizationManager
.updateOrganization(organizationView, sessionFactory);
return null;

}

/**
* Fetch organization details for a given id This method is accessed by
* restful client as web service method.
* @param orgId
*            the organization id of the organization for which details need
*            to be fetched
* @return {@link OrganizationView} organizationView containing organization
*         details for a given org id.
*/
@Override
@WebMethod
@GET
@Path("{org}")
@Descriptions({
@Description(value = "returns a organization data ", target = "method"),
@Description(value = "the organization data", target = "return") })
@Produces(MediaType.APPLICATION_JSON)
// @Audit(auditType="getOrg")
public OrganizationView getOrganization(
@Description("the string representation of the organization") @PathParam("org") @NotNull @Size(max = 10, min = 3) int organizationId)
throws Exception {

Organization organization = organizationManager.getOrganizationDetails(
organizationId, sessionFactory);
OrganizationView organizationView = new OrganizationView();
organizationView.setOrganization(organization);
return organizationView;

}

/**
* Creates a new organization from the details published by restful client
* This method is accessed by restful client in the form of restful service
* method.
* @exception DuplicateRegistrationException
*                might throw an exceptin if same organization exists with
*                same name.
* @param organization
*            the view containing organization details that need to be saved
* @return Integer organization id of newly created organization
*/
@Override
@WebMethod
@POST
@Descriptions({
@Description(value = "stores a new organization data", target = "method"),
@Description(value = "the newly created organization data", target = "return") })
public void createOrganization(OrganizationView organizationView)
throws Exception {

organizationManager
.createOrganization(organizationView, sessionFactory);

}

@Override
@WebMethod
@GET
@Path("{orgId}")
@Descriptions(@Description(value = "delete data ", target = "method"))
public Organization deleteOrganization(
@Description("the string representation of the organization") @PathParam("orgId") @NotNull @Size(max = 10, min = 3) int organizationId)
throws Exception {

organizationManager.deleteOrganization(organizationId, sessionFactory);

return null;
}

@Override
@WebMethod
@GET
@Descriptions(@Description(value = "Gets All Organizations Data ", target = "method"))
@Produces("application/json")
public OrganizationView searchAllOrganization() throws Exception {

organization = organizationManager.searchOrganization(sessionFactory);
OrganizationView oraganizationView = new OrganizationView();
oraganizationView.setOrganizationslist(organization);
return oraganizationView;
}

}

OrganizationManager.java
----------------------------
package com.asman.diameter.manager;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.asman.diameter.dao.impl.DiameterpDaoImpl;
import com.asman.diameter.to.Organization;
import com.asman.diameter.views.OrganizationView;

/**
 * 
 * 
 * @author Laxman
 * 
 */
@Repository
@Transactional
public class OrganizationManager {

private Session session;

@Autowired
private DiameterpDaoImpl diameterDao;

/*
* @Autowired private OrganizationDao organizationDao;
*/

/**
* @param organizationDao
*            the organizationDao to set
*/
/*
* public void setOrganizationDao(OrganizationDao organizationDao) {
* this.organizationDao = organizationDao; }
*/

/**
* @param diameterpDao
*            the diameterpDao to set
*/
public void setDiameterpDao(DiameterpDaoImpl diameterpDao) {
this.diameterDao = diameterpDao;
}

/**
* Store the Organization data to Database.
* @param organizationView
* @param sessionFactory
*/
public void createOrganization(OrganizationView organizationView,
SessionFactory sessionFactory) {
try {
session = sessionFactory.openSession();
Organization organization = new Organization();
organization.setOrgAddress(organizationView.getOrgAddress());
organization.setOrgCity(organizationView.getOrgCity());
organization.setOrgCountry(organizationView.getOrgCountry());
organization.setOrgMail(organizationView.getOrgMail());
organization.setOrgName(organizationView.getOrgName());
organization.setOrgPrimaryContact(organizationView
.getOrgPrimaryContact());
organization.setOrgSecondaryContact(organizationView
.getOrgSecondaryContact());

diameterDao.persist(session, organization);
session.close();
} catch (Exception exception) {
exception.printStackTrace();
}
}

/**
* Fetch Organization Details.
* @param organizationId
* @param sessionFactory
* @return Organization
*/
public Organization getOrganizationDetails(Integer organizationId,
SessionFactory sessionFactory) {
session = sessionFactory.openSession();
Organization organization = (Organization) diameterDao.findById(
session, organizationId, Organization.class);
return organization;
}

/**
* Update Organization Details.
* @param organizationView
* @param sessionFactory
*/
public void updateOrganization(OrganizationView organizationView,
SessionFactory sessionFactory) {
session = sessionFactory.openSession();
Organization organization = new Organization();
organization.setId(organizationView.getOrganizationId());
organization.setOrgAddress(organizationView.getOrgAddress());
organization.setOrgCity(organizationView.getOrgCity());
organization.setOrgCountry(organizationView.getOrgCountry());
organization.setOrgMail(organizationView.getOrgMail());
organization.setOrgName(organizationView.getOrgName());
organization.setOrgPrimaryContact(organizationView
.getOrgPrimaryContact());
organization.setOrgSecondaryContact(organizationView
.getOrgSecondaryContact());
diameterDao.attachDirty(session, organization);
session.close();
}

/**
* @param organizationId
* @param sessionFactory
*/
public void deleteOrganization(Integer organizationId,
SessionFactory sessionFactory) {

session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
String delete_query = "delete from Organization where  id="
+ organizationId;
diameterDao.delete_single_record(session, delete_query);
transaction.commit();
}

/**
* @param organizationId
* @param sessionFactory
* @return
*/
public List<Organization> searchOrganization(SessionFactory sessionFactory) {

session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
String query = "from Organization";
List<Organization> orghanizationList = diameterDao.findBy_Query(
session, query);
transaction.commit();
return orghanizationList;
}

}


Dao Related Interface

DiameterDao.java
------------------

package com.asman.diameter.dao;

import java.math.BigDecimal;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;

/**
 * Base DAO interface that provide interface to basic database operations.
 * This class contains generic methods signatures that operate on tables
 * 
 * @author ASMAN
 *
 * @param <T>
 */
public interface DiameterDao<T> {

public Integer persist(Session session, T dataObject)
throws HibernateException;

public void attachDirty(Session session, T dataObject)
throws HibernateException;

public void attachClean(Session session, T dataObject)
throws HibernateException;

public void delete(Session session, T dataObject)
throws HibernateException;

public T merge(Session session, T dataObject)
throws HibernateException;

public T findById(Session session, Integer id, Class instanceType)
throws HibernateException;

public List<T> findByExample(Session session, T dataObject)
throws HibernateException;

public T findById(Session session, Long id, Class instanceType)
throws HibernateException;

public T findById(Session session, String id, Class instanceType)
throws HibernateException;

public T findById(Session session, Double id, Class instanceType)
throws HibernateException;

public T findById(Session session, BigDecimal id,
Class instanceType) throws HibernateException;
public List<Object> findByQuery(Session session,String query)throws HibernateException;
public List<T> findBy_Query(Session session,String query)throws HibernateException;
public Class<T> getType();


}


Here i implemented Generic Dao class

DiameterpDaoImpl.java
-------------------------

/**
 * 
 */
package com.asman.diameter.dao.impl;

import static org.hibernate.criterion.Example.create;

import java.math.BigDecimal;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.asman.diameter.dao.DiameterDao;



/**
 * 
 * Useful class for creating a basic DAO. Typically you would extend this class and register your entities/pojos, 
 * then provide higher-level data manipulation methods as desired.
 * <p>
 * This class contains generic methods to operate on entities.All methods are generic in nature that they are not tied to specific entity.
 * Handles all generic database operations (CURD) on provided entity
 *  
 * <p>
 * Each DAO that extends from this base DAO should tie by with specific entity.
 * Each DAO should implement getType() method to make use of generic operations in this base DAO. 
 * Each entity/POJO should extend {@link DomainObject} to be part of these methods.
 *  
 * @author ASMAN
 * 
 */
@Repository("diameterDao")
@Transactional
public class DiameterpDaoImpl<T> implements DiameterDao<T> {

private HibernateTemplate hibernateTemplate;
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
private SessionFactory sessionFactory;

@Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
hibernateTemplate = new HibernateTemplate(sessionFactory);
}

private static final Log log = LogFactory.getLog(DiameterpDaoImpl.class);
/**
* Persist/save a POJO or an entity
* @param session Hibernate session
* @param dataObject an entity that is subclass of {@link DomainObject} 
*/
@Override
public Integer persist(Session session, T dataObject)
throws HibernateException {
log.debug("persisting Specific instance");
Transaction transaction=session.beginTransaction();
try {
Integer Id=(Integer) session.save(dataObject);
transaction.commit();
log.debug("persist successful");
return Id;
} catch (HibernateException re) {
log.error("persist failed", re);
throw re;
}
}
/**
* Merge entity and persist them in database
* @param session Hibernate session
* @param dataObject an entity that is subclass of {@link DomainObject}
*/
@Override
public T merge(Session session, T dataObject)
throws HibernateException {
log.debug("merging data instance");
try {
T result = (T) session.merge(dataObject);
log.debug("merge successful");
return result;
} catch (HibernateException re) {
log.error("merge failed", re);
throw re;
}
}
/**
* Attach a clean Entity
* @param session Hibernate session
* @param dataObject an entity that is subclass of {@link DomainObject}
*/
@Override
public void attachClean(Session session, T dataObject)
throws HibernateException {
log.debug("attaching clean dataObject instance");
try {
session.lock(dataObject, LockMode.NONE);
log.debug("attach successful");
} catch (HibernateException re) {
log.error("attach failed", re);
throw re;
}
}

/**
* Attach modified entity and update Details in database
* @param session Hibernate session
* @param dataObject an entity that is subclass of {@link DomainObject}
*/
@Override
public void attachDirty(Session session, T dataObject)
throws HibernateException {
log.debug("attaching dirty dataObject instance");
try {
Transaction transaction=session.beginTransaction();
session.saveOrUpdate(dataObject);
transaction.commit();
log.debug("attach successful");
} catch (HibernateException re) {
log.error("attach failed", re);
System.out.println("exception::::::"+re);
throw re;
}
}

/**
* Delete specific entity from database
* @param session Hibernate session
* @param dataObject an entity that is subclass of {@link DomainObject}
*/
@Override
public void delete(Session session, T dataObject)
throws HibernateException {
log.debug("deleting dataObject instance");
try {
session.delete(dataObject);
log.debug("delete successful");
} catch (HibernateException re) {
log.error("delete failed", re);
throw re;
}
}

/**
* Delete specific entity from database
* @param session Hibernate session
* @param dataObject an entity that is subclass of {@link DomainObject}
*/
public Integer delete_single_record(Session session, String queryString)
throws HibernateException {
log.debug("deleting dataObject instance");
try {
Query query =  session.createQuery(queryString);
return query.executeUpdate();
} catch (HibernateException re) {
log.error("get failed", re);
System.out.println("exceptionnnnnnnnnnn"+re);
throw re;
}
}
/**
* Fetch List of entity based on Example criteria
* @param session Hibernate session
* @param dataObject an entity that is subclass of {@link DomainObject}
*/
@Override
public List<T> findByExample(Session session, T dataObject)
throws HibernateException {
log.debug("finding data instance by example");

try {
List<T> results = (List<T>) session
.createCriteria(dataObject.getClass())
.add(create(dataObject)).list();
log.debug("find by example successful, result size: "
+ results.size());
return results;
} catch (HibernateException re) {
log.error("find by example failed", re);
throw re;
}
}

/**
* Find an entity by its primary key
* @param session Hibernate session
* @param id the primary key of type Integer
* @param instanceType the Class of specific entity
*/
@Override
public T findById(Session session, Integer id, Class instanceType)
throws HibernateException {
log.debug("getting T instance with id: " + id);
Integer i = id;
try {
T instance = (T) session.get(instanceType,i);
if (instance == null) {
log.debug("get successful, no instance found");
} else {
log.debug("get successful, instance found");
return instance;
}
return null;
} catch (HibernateException re) {
log.error("get failed", re);
System.out.println("exceptionnnnnnnnnnnnnnn"+re);
throw re;
}
}

/**
* Find an entity by its primary key
* @param session Hibernate session
* @param id the primary key of type Long
* @param instanceType the Class of specific entity
*/
@Override
public T findById(Session session, Long id, Class instanceType)
throws HibernateException {
log.debug("getting T instance with id: " + id);
try {
T instance = (T) session.get(instanceType, id);
if (instance == null) {
log.debug("get successful, no instance found");
} else {
log.debug("get successful, instance found");
return instance;
}
return null;
} catch (HibernateException re) {
log.error("get failed", re);
throw re;
}
}

/**
* Find an entity by its primary key
* @param session Hibernate session
* @param id the primary key of type string
* @param instanceType the Class of specific entity
*/
@Override
public T findById(Session session, String id, Class instanceType)
throws HibernateException {
log.debug("getting T instance with id: " + id);
try {
T instance = (T) session.get(instanceType, id);
if (instance == null) {
log.debug("get successful, no instance found");
} else {
log.debug("get successful, instance found");
return instance;
}
return null;
} catch (HibernateException re) {
log.error("get failed", re);
throw re;
}
}

/**
* Find an entity by its primary key
* @param session Hibernate session
* @param id the primary key of type double
* @param instanceType the Class of specific entity
*/
@Override
public T findById(Session session, Double id, Class instanceType)
throws HibernateException {
log.debug("getting T instance with id: " + id);
try {
T instance = (T) session.get(instanceType, id);
if (instance == null) {
log.debug("get successful, no instance found");
} else {
log.debug("get successful, instance found");
return instance;
}
return null;
} catch (HibernateException re) {
log.error("get failed", re);
throw re;
}
}

/**
* Find an entity by its primary key
* @param session Hibernate session
* @param id the primary key of type Bigdecimal
* @param instanceType the Class of specific entity
*/
@Override
public T findById(Session session, BigDecimal id,
Class instanceType) throws HibernateException {
log.debug("getting T instance with id: " + id);
try {
T instance = (T) session.get(instanceType, id);
if (instance == null) {
log.debug("get successful, no instance found");
} else {
log.debug("get successful, instance found");
return instance;
}
return null;
} catch (HibernateException re) {
log.error("get failed", re);
throw re;
}
}

/**
* Save an entity to Database
* @param pojo a generic POJO that extends {@link DomainObject}
*/
public void save(T pojo){
getHibernateTemplate().save(pojo);
}

/**
* Save or Update an entity to Database
* @param pojo a generic POJO that extends {@link DomainObject}
*/
public void saveOrUpdate(T pojo){
getHibernateTemplate().saveOrUpdate(pojo);
}
/**
* Find list of entity that matches the query string 
* @param session Hibernate session
* @param queryString condition to fetch entites
*/
@Override
public List<Object> findByQuery(Session session, String queryString)
throws HibernateException {
try {
Query query =  session.createQuery(queryString);
return query.list();
} catch (HibernateException re) {
log.error("get failed", re);
System.out.println("exceptionnnnnnnnnnn"+re);
throw re;
}
}

/**
* This method provides the type of the entity passed to base class
* All sub classes that extends the base DAO should override it and return specific entity type.
*/
public Class<T> getType(){
return null;
}
@Override
public List<T> findBy_Query(Session session, String queryString)
throws HibernateException {
try {
Query query =  session.createQuery(queryString);
return query.list();
} catch (HibernateException re) {
log.error("get failed", re);
throw re;
}
}

}

No comments:

Post a Comment