Sunday, December 8, 2013

Hibernate JPA

Hibernate Implementation Class
import javax.ejb.Stateless;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Stateless
public class StudentServiceHibernateImpl implements StudentServiceEJBRemoteInt {

public StudentServiceHibernateImpl() {}

public void SaveStudentSurveyFormData(Student postData){
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx=session.getTransaction();
tx.begin();
session.saveOrUpdate(postData.getContact());

DetachedCriteria maxId = DetachedCriteria.forClass(Contact.class)
   .setProjection( Projections.max("id"));
Contact con = (Contact) session.createCriteria(Contact.class)
   .add(Property.forName("id").eq(maxId))
   .uniqueResult();
postData.setContactId(con.getId());
session.saveOrUpdate(postData);
tx.commit();
}

public Student GetStudentSurveyData(Student student){
Surveys surveys = GetSurveys(student);
for(Student survey : surveys.data){
if(survey.getLastName().equalsIgnoreCase(student.getLastName()) && survey.getFirstName().equalsIgnoreCase(student.getFirstName())){
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx = session.beginTransaction();
Contact con = (Contact) session.createCriteria(Contact.class)
   .add(Property.forName("id").eq(survey.getContactId()))
   .uniqueResult();
survey.setContact(con);
tx.commit();
return survey;
}
}
return null;
}

public Surveys GetSurveys(Student searchCriteria){
Surveys surveys = new Surveys();
surveys.data = new ArrayList<Student>();

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx = session.beginTransaction();
Criteria query = session.createCriteria(Student.class);

if(searchCriteria != null){
if(searchCriteria.getFirstName() != null && !searchCriteria.getFirstName().isEmpty()){
String firstName = searchCriteria.getFirstName().replace('*', '%');
query = query.add(Restrictions.like("firstName", firstName).ignoreCase());
}
if(searchCriteria.getLastName() != null && !searchCriteria.getLastName().isEmpty()){
String lastName = searchCriteria.getLastName().replace('*', '%');
query = query.add(Restrictions.like("lastName", lastName).ignoreCase());
}
if(searchCriteria.getCity() != null && !searchCriteria.getCity().isEmpty()){
String city = searchCriteria.getCity().replace('*', '%');
query = query.add(Restrictions.like("city", city).ignoreCase());
}
if(searchCriteria.getState() != null && !searchCriteria.getState().isEmpty()){
String state = searchCriteria.getState().replace('*', '%');
query = query.add(Restrictions.like("state", state).ignoreCase());
}
}
query = query.addOrder(Property.forName("lastName").asc());
query = query.addOrder(Property.forName("firstName").asc());

@SuppressWarnings("unchecked")
List<Student> surveyList = (List<Student>)query.list();
tx.commit();

if(surveyList.size() > 0){
surveys.data = surveyList;
}

return surveys;
}

public List<Student> GetStudents(Student searchCriteria) throws IOException{
Surveys surveys = GetSurveys(searchCriteria);
return surveys.data;
}

public List<String> GetSurveyNames(){
List<String> surveyNames = new ArrayList<String>();
Surveys surveys = GetSurveys(null);
for(Student survey : surveys.data){
surveyNames.add(survey.getFirstName() + " " + survey.getLastName());
}
return surveyNames;
}

public WinningResult ComputeMeanAndStandardDeviation(String raffle){
if(StringUtils.isEmpty(raffle)){
return new WinningResult(0,0);
}
String[] numbers = raffle.split(",");
double sum = 0;

for(int i=0; i < numbers.length; i++){
  sum += Double.valueOf(numbers[i].trim());
}
double mean = Math.round((sum/numbers.length) * 100)/100;

double temp = 0;
for(int i=0; i < numbers.length; i++){
  double num = Double.valueOf(numbers[i].trim());
  temp += (mean - num) * (mean - num);
}
double variance = temp/numbers.length;
double standardDeviation = Math.round(Math.sqrt(variance) * 100)/100 ;

WinningResult data = new WinningResult(mean, standardDeviation);
return data;
}

@Override
public void DeleteStudent(Student postData) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx=session.getTransaction();
tx.begin();
Student student = (Student) session.createCriteria(Student.class)
   .add(Property.forName("id").eq(postData.getId()))
   .uniqueResult();
int contactId = student.getContactId();
Contact con = (Contact) session.createCriteria(Contact.class)
   .add(Property.forName("id").eq(contactId))
   .uniqueResult();
session.delete(student);
session.delete(con);
tx.commit();
}
}

Hibernate Interface
package tutorial.example;

import java.io.IOException;
import java.util.List;

import javax.ejb.Remote;
import javax.jws.WebService;

@WebService(targetNamespace = "http://gmuswe645.edu/wsdl")
@Remote
public interface StudentServiceEJBRemoteInt {
    public List<Student> GetStudents(Student searchCriteria) throws IOException;
    public Student GetStudentSurveyData(Student student);
    public WinningResult ComputeMeanAndStandardDeviation(String raffle);
    public void SaveStudentSurveyFormData(Student postData);
public void DeleteStudent(Student student);
}

Hibernate Util
package tutorial.example;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * Hibernate Utility used to configure Hibernate's Session Factory and retrieve
 * it.
 */
public class HibernateUtil {

private static final SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;

static {
try {
// Create the SessionFactory from hibernate.cfg.xml
// ------ --- -------------- ---- -----------------
Configuration configuration = new Configuration();
   configuration.configure();
   serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = new Configuration().configure().buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
// ---- ---- --- --- --- ---------- -- -- ----- -- ---------
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}

/**
* Get the configured session factory
* @return session factory
*/
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}

Hibernate Configuration
<?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> 
<!-- Oracle Configuration -->
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@...</property>
<property name="hibernate.connection.username">...</property>
<property name="hibernate.connection.password">...</property>
    <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
        
        <!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
        
        <!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>

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

<!--  Load all mapping files -->
<mapping resource="Survey.hbm.xml" />
</session-factory>
</hibernate-configuration>

Survey Configuration
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="tutorial.example.Student" table="SURVEYS">
<id name="id" column="surveyId" type="int">
<generator class="sequence">
<param name="sequence">SURVEY_SEQ</param>
</generator>
</id>
<property name="firstName" column="firstName" type="string" />
<property name="lastName" column="lastName" type="string" />
<property name="streetAddress" column="streetAddress" type="string" />
<property name="city" column="city" type="string" />
<property name="state" column="state" type="string" />
<property name="zip" column="zip" type="string" />
<property name="telephone" column="telephone" type="string"/>
<property name="email" column="email" type="string" />
<property name="surveyDate" column="surveyDate" type="string" />
<property name="likes" column="likes" type="string" />
<property name="interest" column="interest" type="string" />
<property name="recommendation" column="recommendation" type="string" />
<property name="comments" column="comments" type="string" />
<property name="raffle" column="raffle" type="string" />
<property name="contactId" column="contactId" type="java.lang.Integer"/>
<one-to-one name="contact" class="tutorial.example.Contact" property-ref="id" cascade="all" fetch="join" />
</class>
<class name="tutorial.example.Contact" table="CONTACTS">
<id name="id" column="contactId" type="int">
<generator class="sequence">
<param name="sequence">CONTACT_SEQ</param>
</generator>
</id>
<property name="firstName" column="firstName" type="string" />
<property name="lastName" column="lastName" type="string" />
<property name="streetAddress" column="streetAddress" type="string" />
<property name="city" column="city" type="string" />
<property name="state" column="state" type="string" />
<property name="zip" column="zip" type="string" />
<property name="email" column="email" type="string" />
</class>
</hibernate-mapping>

Action Class
package tutorial.example;

import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.commons.lang3.StringUtils;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class SurveyAction extends ActionSupport implements ModelDriven<Student> {
private static final long serialVersionUID = 1L;
private Student student;
private WinningResult winningResult;
private List<Student> surveysList;
private Context context;
private StudentServiceEJBRemoteInt serviceEJB;
public SurveyAction(){
try {
context = new InitialContext();
serviceEJB = (StudentServiceEJBRemoteInt) context.lookup("java:global/surveyapp-tkhuc/surveyapp-tkhuc-ejb/StudentServiceHibernateImpl!tutorial.example.StudentServiceEJBRemoteInt");  
} catch (NamingException e) {
e.printStackTrace();
}
}
public String deletesurvey() throws Exception{
serviceEJB.DeleteStudent(student);
return SUCCESS;
}
public String listsurvey() throws Exception{
surveysList = (List<Student>) serviceEJB.GetStudents(null);
return SUCCESS;
}
public String displaysurvey() throws Exception{
student = (Student) serviceEJB.GetStudentSurveyData(student);
return SUCCESS;
}
public String searchsurvey() throws Exception{
surveysList = (List<Student>) serviceEJB.GetStudents(student);
return SUCCESS;
}
public String execute() throws Exception{
Student studentFound = (Student) serviceEJB.GetStudentSurveyData(student);
if(studentFound != null){
return "input";
}
serviceEJB.SaveStudentSurveyFormData(student);
winningResult = (WinningResult) serviceEJB.ComputeMeanAndStandardDeviation(student.getRaffle());
if(winningResult.getMean() > 90){
return "winner";
}
return "simple";
}
public void validate(){
if(student.getSkipsValidation())
return;
if(StringUtils.isEmpty(student.getFirstName())){
addFieldError("firstName", "First Name cannot be blank.");
}
if(StringUtils.isEmpty(student.getLastName())){
addFieldError("lastName", "Last Name cannot be blank.");
}
if(StringUtils.isEmpty(student.getStreetAddress())){
addFieldError("streetAddress", "Street Address cannot be blank.");
}
if(StringUtils.isEmpty(student.getCity())){
addFieldError("city", "City cannot be blank.");
}
if(StringUtils.isEmpty(student.getState())){
addFieldError("state", "State cannot be blank.");
}
if(StringUtils.isEmpty(student.getZip())){
addFieldError("zip", "Zip cannot be blank.");
}
if(StringUtils.isEmpty(student.getTelephone())){
addFieldError("telephone", "Telephone number cannot be blank.");
}
if(StringUtils.isEmpty(student.getEmail())){
addFieldError("email", "Email cannot be blank.");
}
if(StringUtils.isEmpty(student.getSurveyDate())){
addFieldError("surveyDate", "Survey date cannot be blank.");
}
}
public Student getStudent(){
return student;
}
public void setStudent(Student student){
this.student = student;
}
public WinningResult getWinningResult(){
return winningResult;
}
public void setWinningResult(WinningResult winningResult){
this.winningResult = winningResult;
}
public List<Student> getSurveysList() {
return surveysList;
}

public void setSurveysList(List<Student> surveysList) {
this.surveysList = surveysList;
}

@Override
public Student getModel() {
student = new Student();
return student;
}
}

No comments: