Spring Hibernate Integration Simple Example

Here is one example to integrate Spring and Hibernate. Create a java project and add below files and configuration files

Project Structure

image 

1. Create a POJO class (Student.java)

package com.pretech;
public class Student {
	private int id;
	private String name;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

2. Create a DAO class

package com.pretech;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;
public class StudentDao {
	HibernateTemplate template;
	public void setSessionFactory(SessionFactory factory) {
		template = new HibernateTemplate(factory);
	}
	public void saveStudent(Student e) {
		template.save(e);
	}
}

3. Create Spring configuration file (applicationContext.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:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName"  value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql://localhost:3306/hibernateschema"></property>
		<property name="username" value="root"></property>
		<property name="password" value="root"></property>
		
	</bean>
	
	<bean id="mysessionFactory"	class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource"><ref bean="dataSource" /></property>
		
		<property name="mappingResources">
		<list>
		<value>student.hbm.xml</value>
		</list>
		</property>
		
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.hbm2ddl.auto">create</prop>
				<prop key="hibernate.show_sql">true</prop>
				
			</props>
		</property>
	</bean>
	
	<bean id="d" class="com.pretech.StudentDao">
	<property name="sessionFactory" ref="mysessionFactory"></property>
	</bean>
	
	</beans>

4. Create Hibernate Mapping file (student.hbm.xml)

<?xml version='1.0' encoding='UTF-8'?>
<!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.pretech.Student" table="Student" >
        <id name="id" >
            <generator class="assigned" >
            </generator>
        </id>
        <property name="name" >
        </property>
    </class>
</hibernate-mapping>

5. Create a Main class to insert Student details

package com.pretech;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class StudentMain {
	public static void main(String[] args) {
		Resource resource = new ClassPathResource("applicationContext.xml");
		BeanFactory factory = new XmlBeanFactory(resource);
		StudentDao dao = (StudentDao) factory.getBean("d");
		Student student = new Student();
		student.setId(101);
		student.setName("Vinod");
		dao.saveStudent(student);
	}
}

6. Output


image 


Download this example Spring Hibernate Example

Spring Form Validation Example

Here is one simple example to validate form (Student form). Spring API providers Validator interface to implement form validations. To implement validation we have to create a validator class which implements the Validator interface and should override validate() method. In this example i am going to validate two text field for Student form

1. Create a Validator class

Create a dynamic web project in Eclipse and add all spring mvc related jars in the web/lib folder, see this example for more details (Spring MVC Example). Once we created the web application create a Validator class.

package com.pretech;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.pretech.Student;
public class StudentValidator implements Validator {
	
	public boolean supports(Class<?> clazz) {
		return Student.class.isAssignableFrom(clazz);
	}
	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "name.required");
		ValidationUtils.rejectIfEmpty(errors, "address", "address.required");
		Student student = (Student) target;
		
	}
}

2. Add Validator details into dispatcher-servlet.xml

<bean id="StudentValidator" class="com.pretech.StudentValidator" />

3. Message.properties



Create  message.properties and placed in to src folder with below properties

name.required = Student Name should not be blank
address.required = Student Address should not be blank

Add below Message Resources in despatcher-servlet.xml file

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" p:basename="messages" />



4. Add Validator reference to the bean which we are going to validate

<bean name="/studentRegistration.htm" class="com.pretech.StudentController"
  p:formView="StudentDetails" p:successView="SuccessPage" p:validator-ref="StudentValidator" />

5. Add form error details in to JSP page to display

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Student Registration Page</title>
<style>
.error {
color: #ff0000;
font-style: italic;
}
</style>
</head>
<body>
<form:form method="POST" commandName="student">
	<table>
		<tr>
			<td>Enter Student Name :</td>
			<td><form:input path="name" /></td>
			<td><form:errors path="name" cssClass="error" /></td>
		</tr>
		<tr>
			<td>Enter Student Address :</td>
			<td><form:input path="address" /></td>
			<td><form:errors path="address" cssClass="error" /></td>
		</tr>
		
		<tr>
			<td colspan="3"><input type="submit" value="Register"></td>
		</tr>
	</table>
</form:form>
</body>
</html>

6. Deploy and run application


To test the validator click on Register button without any values


image


7. Download Example


Spring MVC Form Validation Example

How to generate Java files using JAXB xjc command


Here is one simple example to generate java class files from xsd file using JAXB xjc command.

Steps

1. Create a Sample xsd file (Example order.xsd)
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Order" type="Order"/>
  <xs:complexType name="Order">
    <xs:sequence>
      <xs:element name="orderNumber" type="xs:long"/>
      <xs:element name="orderItem" type="orderItem" minOccurs="0"/>
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="orderItem">
    <xs:sequence>
      <xs:element name="orderItemNumber" type="xs:long"/>
      <xs:element name="orderItemName" type="xs:string" minOccurs="0"/>
      </xs:sequence>
  </xs:complexType>
</xs:schema>

2. Create a directory which you want to save java files (eg javafiles)

3. Go to command prompt and use following command to generate java classess (Make sure that java class path set up is there to get xjc tool)


xjc -d javafiles order.xsd

 



4. We can see the console like below and all the classes are generated in the javafiles directory


$ xjc -d javafiles order.xsd
parsing a schema...
compiling a schema...
generated/ObjectFactory.java
generated/Order.java
generated/OrderItem.java

 



Reference


http://jaxb.java.net/2.2.4/docs/xjc.html

JAX-WS Web services using Apache CXF

In this example we are using Apache CXF for JAX-WS implementation , see more about Apache CXF

Software Used

  1. Eclipse Kepler Release
  2. Tomcat 6
  3. Java 1.6
  4. CXF 2.7.6

Environment Setup

1. Download apache CXF from http://www.apache.org/dyn/closer.cgi?path=/cxf/2.7.6/apache-cxf-2.7.6.zip
2. Extract CXF zip file
3. Setup CXF run time in eclipse
Go to Eclipse Window->Preference->Web services and select CXF run time
image 

Create Web Service

1. Create a Dynamic web project in eclipse and choose Tomcat 6 as Target run time
image 
2. Create a java class to implement Web service method
 
package com.pretech;

public class MyWebService {

    public String giveWelcome(String name) {
        return "Welcome " + name;
    }

}
 
3. Right click on the dynamic web project and create a new web service
image 
4. Click on next button and we can see the below window
image 
1.Select web service implementation class (MyWebService)
2.Slider should be in Start Service point
3.Service Runtime should be Tomcat 6
4.Web service run time should be Apache CXF
5.Service project should be this project
6.Check Publish the Web service option
5. Click on next and start the server and click on finish .That's all Web service implementation is done now we can see the generated wsdl file.
image 

Test Web Service

1. Go to Eclipse run-> and Launch Web services Explorer
2. Click on WSDL page and enter the WSDL url (Open MyWebService.wsdl file and get the wsdlsoap:address and append ?wsdl) example :http://localhost:8080/JAX-WS-CXF/services/MyWebService?wsdl

image 
image 

3. Click on go button and we can see the web service methods over there in the next screen. Select giveWelcome method and test it.

image 

JMS with ActiveMQ Example

In the previous example we tested JMS Message producer and Message listener in Jboss application server. In this example i am going to use Apache ActiveMQ for messaging.
Goals
  1. Setup ActiveMQ
  2. Create a JMS Message Producer
  3. Create a JMS Message Consumer
Setup ActiveMQ
In this example we are using windows so please follow the below steps to start ActiveMQ messaging system.
1. Download activemq from http://activemq.apache.org/download-archives.html
2. Extract activemq zip file and start ActiveMQ (Click on activemq.bat file)
3. Check activemq console using http://localhost:8161/admin  (Use default credentials admin/admin to login)
image

2. Create a Message Producer
Add below dependency in your pom.xml
<dependency>
            <groupId>javax.jms</groupId>
            <artifactId>javax.jms-api</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-all</artifactId>
            <version>5.7.0</version>
        </dependency>
Message Producer
package com.vinod.jms;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

public class MessageProducerExample {
    public static void main(String[] args) {
        try {
            // Create a ConnectionFactory
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "admin",
                    ActiveMQConnection.DEFAULT_BROKER_URL);
            // Create a Connection
            Connection connection = connectionFactory.createConnection();
            connection.start();
            // Create a Session
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            // Create the destination
            Destination destination = session.createQueue("testQ");
            // Create a MessageProducer from the Session to the Queue
            MessageProducer producer = session.createProducer(destination);
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            // Create a messages
            TextMessage message = session.createTextMessage("Helloworld..by vinod");
            producer.send(message);
            session.close();
            connection.close();
            System.out.println("Message sent");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
  
3. Create a Message Consumer
package com.vinod.jms;

import javax.jms.ConnectionFactory;
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.Message;

public class MessageConsumerExample {
    public static void main(String[] args) {
        try {
            // Create a ConnectionFactory
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "admin",
                    ActiveMQConnection.DEFAULT_BROKER_URL);
            // Create a Connection
            Connection connection = connectionFactory.createConnection();
            connection.start();
            // Create a Session
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            // Create the destination
            Destination destination = session.createQueue("testQ");
            // Create a MessageConsumer from the Session to the Queue
            MessageConsumer consumer = session.createConsumer(destination);
            // Wait for a message
            Message message = consumer.receive(1000);
            if (message instanceof TextMessage) {
                TextMessage textMessage = (TextMessage) message;
                String text = textMessage.getText();
                System.out.println("Text Message is " + text);
            } else {
                System.out.println(message);
            }
            consumer.close();
            session.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
4. Run it
Once activemq started, then start Message producer first and push the messages in the queue after that run the consumer..
image
Console output after running Message consumer
Text Message is Helloworld..by vinod
5. Download example
https://github.com/kkvinodkumaran/myrepository/tree/master/vinod-jms

Confusion Matrix + Precision/Recall (Super Simple, With Examples)

  Confusion Matrix + Precision/Recall (Super Simple, With Examples) 1) Binary Classification Setup Binary classification means the model p...

Featured Posts