Archive

Posts Tagged ‘Spring Hibernate Integration’

Struts2 CRUD Tutorial

May 8, 2017 Leave a comment

In this tutorial I will show you how to perform create, retrieve, update and delete operation using struts2 framework. In this tutorial I have used Spring as DI, Hibernate as ORM and Maven as build tool also. Below are tutorial screen shoot,

Add View

 

Update View

 

 

Lets get started,

Structure Directory Project

  • Entity class (Student.java)
package strutshelloworld.net.ren.struts2.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

// TODO: Auto-generated Javadoc
/**
 * The Class Student.
 */
@Entity
@Table(name="student")
public class Student {
    
    /** The id. */
	@Id
	@GeneratedValue
	@Column(name="id")
    private int id;
    
    /** The first name. */
	@Column(name="first_name")
    private String firstName;
    
    /** The last name. */
	@Column(name="last_name")
    private String lastName;
    
    /**
     * Instantiates a new student.
     */
    public Student() {
	
    }
    
    /**
     * Instantiates a new student.
     *
     * @param id the id
     * @param firstName the first name
     * @param lastName the last name
     */
    public Student(int id, String firstName, String lastName) {
	super();
	this.id = id;
	this.firstName = firstName;
	this.lastName = lastName;
    }
    
    /**
     * Gets the id.
     *
     * @return the id
     */
    public int getId() {
	return id;
    }
    
    /**
     * Sets the id.
     *
     * @param id the new id
     */
    public void setId(int id) {
	this.id = id;
    }
    
    /**
     * Gets the first name.
     *
     * @return the first name
     */
    public String getFirstName() {
	return firstName;
    }
    
    /**
     * Sets the first name.
     *
     * @param firstName the new first name
     */
    public void setFirstName(String firstName) {
	this.firstName = firstName;
    }
    
    /**
     * Gets the last name.
     *
     * @return the last name
     */
    public String getLastName() {
	return lastName;
    }
    
    /**
     * Sets the last name.
     *
     * @param lastName the new last name
     */
    public void setLastName(String lastName) {
	this.lastName = lastName;
    }
    
}
  • Repository class (AbstractBaseRepository.java)
package strutshelloworld.net.ren.struts2.repository;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import javax.persistence.Query;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * The Class AbstractBaseRepository.
 *
 * @param <T>
 *            the generic type
 */
public abstract class AbstractBaseRepository<T> implements BaseRepository<T> {

	/** The entity class. */
	private Class<T> entityClass;

	/** The session factory. */
	@Autowired
	private SessionFactory sessionFactory;

	/** The hql. */
	private String hql;

	/** The entities. */
	private List<T> entities;
	/**
	 * Instantiates a new abstract base repository.
	 */
	public AbstractBaseRepository() {
		Type t = getClass().getGenericSuperclass();
		ParameterizedType pt = (ParameterizedType) t;
		entityClass = (Class) pt.getActualTypeArguments()[0];
	}

	/**
	 * Sets the session factory.
	 *
	 * @param sessionFactory
	 *            the new session factory
	 */
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	/**
	 * Gets the current session.
	 *
	 * @return the current session
	 */
	protected Session getCurrentSession() {
		try {
			return sessionFactory.getCurrentSession();
		} catch (HibernateException e) {
			return sessionFactory.openSession();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * strutshelloworld.net.ren.struts2.repository.BaseRepository#add(java.lang.
	 * Object)
	 */
	public void add(T entity) {
		getCurrentSession().saveOrUpdate(entity); // .save(entity);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * strutshelloworld.net.ren.struts2.repository.BaseRepository#deleteById(
	 * int)
	 */
	@SuppressWarnings("unchecked")
	public void deleteById(int id) {
		hql = "delete " + entityClass.getName() + " where id = :id";
		Query q = getCurrentSession().createQuery(hql).setParameter("id", id);
		q.executeUpdate();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * strutshelloworld.net.ren.struts2.repository.BaseRepository#getById(int)
	 */
	@SuppressWarnings("unchecked")
	public T getById(int id) {
		return (T) getCurrentSession().get(entityClass.getName(), id);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see strutshelloworld.net.ren.struts2.repository.BaseRepository#getAll()
	 */
	@SuppressWarnings({ "deprecation", "unchecked" })
	public List<T> getAll() {
		return getCurrentSession().createCriteria(entityClass).list();
	}
	
	/**
	 * Delete all.
	 */
	public void deleteAll(){
		entities = getAll();
		for(T entity : entities){
			getCurrentSession().delete(entity);
		}
	}
	
	/**
	 * Delete.
	 *
	 * @param entity the entity
	 */
	public void delete(T entity){
		getCurrentSession().delete(entity);
	}
}
  • Repository interface (BaseRepository.java)
package strutshelloworld.net.ren.struts2.repository;

import java.util.List;


/**
 * The Interface BaseRepository.
 *
 * @param <T> the generic type
 */
public interface BaseRepository<T> {

	/**
	 * Adds the.
	 *
	 * @param entity the entity
	 */
	public  void add(T entity);

	/**
	 * Delete by id.
	 *
	 * @param id the id
	 */
	public void deleteById(int id);

	/**
	 * Gets the by id.
	 *
	 * @param id the id
	 * @return the by id
	 */
	public  T getById(int id);

	/**
	 * Gets the all.
	 *
	 * @return the all
	 */
	public  List<T> getAll();
	
	/**
	 * Delete all.
	 */
	public void deleteAll();
	
	/**
	 * Delete.
	 *
	 * @param entity the entity
	 */
	public void delete(T entity);

}
  • Repository interface(StudentRepository.java)
package strutshelloworld.net.ren.struts2.repository;

import strutshelloworld.net.ren.struts2.domain.Student;

/**
 * The Interface StudentRepository.
 */
public interface StudentRepository extends BaseRepository<Student> {

}
  • Repository class (StudentRepositoryImpl.java)
package strutshelloworld.net.ren.struts2.repository.impl;

import org.springframework.stereotype.Repository;

import strutshelloworld.net.ren.struts2.domain.Student;
import strutshelloworld.net.ren.struts2.repository.AbstractBaseRepository;
import strutshelloworld.net.ren.struts2.repository.StudentRepository;

/**
 * The Class StudentRepositoryImpl.
 */
@Repository("studentRepository")
public class StudentRepositoryImpl extends AbstractBaseRepository<Student> implements StudentRepository {

}
  • Service Interface (StudentService.java)
package strutshelloworld.net.ren.struts2.service;

import java.util.List;

import strutshelloworld.net.ren.struts2.domain.Student;

// TODO: Auto-generated Javadoc
/**
 * The Interface StudentService.
 */
public interface StudentService {

	/**
	 * Adds the student.
	 *
	 * @param student
	 *            the student
	 */
	public void addStudent(Student student);

	/**
	 * Delete student by id.
	 *
	 * @param id
	 *            the id
	 */
	public void deleteStudentById(int id);

	/**
	 * Find student by id.
	 *
	 * @param id
	 *            the id
	 * @return the student
	 */
	public Student findStudentById(int id);

	/**
	 * Find all.
	 *
	 * @return the list
	 */
	public List<Student> findAll();
	
	/**
	 * Delete all.
	 */
	public void deleteAll();
	
	/**
	 * Delete.
	 *
	 * @param entity the entity
	 */
	public void delete(Student entity);
}
  • Service class (StudentServiceImpl.java)
package strutshelloworld.net.ren.struts2.service.impl;

import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import strutshelloworld.net.ren.struts2.domain.Student;
import strutshelloworld.net.ren.struts2.repository.StudentRepository;
import strutshelloworld.net.ren.struts2.service.StudentService;

// TODO: Auto-generated Javadoc
/**
 * The Class StudentServiceImpl.
 */
@Service
@Transactional
public class StudentServiceImpl implements StudentService {

	/** The student repository. */
	@Autowired
	private StudentRepository studentRepository;

	/*
	 * (non-Javadoc)
	 * 
	 * @see strutshelloworld.net.ren.struts2.service.StudentService#addStudent(
	 * strutshelloworld.net.ren.struts2.domain.Student)
	 */
	public void addStudent(Student student) {
		studentRepository.add(student);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * strutshelloworld.net.ren.struts2.service.StudentService#deleteStudentById
	 * (int)
	 */
	public void deleteStudentById(int id) {
		studentRepository.deleteById(id);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * strutshelloworld.net.ren.struts2.service.StudentService#findStudentById(
	 * int)
	 */
	public Student findStudentById(int id) {
		return studentRepository.getById(id);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see strutshelloworld.net.ren.struts2.service.StudentService#findAll()
	 */
	public List<Student> findAll() {
		return studentRepository.getAll();
	}

	/* (non-Javadoc)
	 * @see strutshelloworld.net.ren.struts2.service.StudentService#deleteAll()
	 */
	public void deleteAll() {
		studentRepository.deleteAll();
	}

	/* (non-Javadoc)
	 * @see strutshelloworld.net.ren.struts2.service.StudentService#delete(strutshelloworld.net.ren.struts2.domain.Student)
	 */
	public void delete(Student entity) {
		studentRepository.delete(entity);
	}
}
  • Action class (StudentAction.java)
package strutshelloworld.net.ren.struts2.actions;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

import strutshelloworld.net.ren.struts2.domain.Student;
import strutshelloworld.net.ren.struts2.service.StudentService;

// TODO: Auto-generated Javadoc
/**
 * The Class StudentAction.
 */
public class StudentAction extends ActionSupport implements ModelDriven, Preparable {

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 3064301885095539523L;

	/** The student service. */
	@Autowired
	private StudentService studentService;

	/** The list student. */
	private List<Student> listStudent = new ArrayList<Student>();

	/** The student. */
	private Student student = new Student();
	
	/** The request. */
	private HttpServletRequest request;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.opensymphony.xwork2.ModelDriven#getModel()
	 */
	public Object getModel() {
		return student;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.opensymphony.xwork2.Preparable#prepare()
	 */
	public void prepare() throws Exception {
		
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.opensymphony.xwork2.ActionSupport#execute()
	 */
	public String execute() throws Exception {
		return SUCCESS;
	}

	/**
	 * Adds the student.
	 *
	 * @return the string
	 */
	public String addStudent() {
		studentService.addStudent(student);
		return SUCCESS;
	}
	
	/**
	 * Update student.
	 *
	 * @return the string
	 */
	public String updateStudent() {
		studentService.addStudent(student);
		return SUCCESS;
	}

	/**
	 * Delete student.
	 *
	 * @return the string
	 */
	public String deleteStudent() {
        request = (HttpServletRequest) ActionContext.getContext().get( ServletActionContext.HTTP_REQUEST);
		studentService.deleteStudentById((Integer.parseInt(request. getParameter("id"))));
		return SUCCESS;
	}

	/**
	 * Gets the all student.
	 *
	 * @return the all student
	 */
	public String getAllStudent() {
		listStudent = studentService.findAll();
		return SUCCESS;
	}

	/**
	 * Update student.
	 *
	 * @return the string
	 */
	public String getStudentById(){
		request = (HttpServletRequest) ActionContext.getContext().get( ServletActionContext.HTTP_REQUEST);
		student = studentService.findStudentById(Integer.parseInt(request. getParameter("id")));
		return SUCCESS;
	}
	
	/**
	 * Delete all.
	 *
	 * @return the string
	 */
	public String deleteAll(){
		studentService.deleteAll();
		return SUCCESS;
	}
	
	/**
	 * Gets the list student.
	 *
	 * @return the list student
	 */
	public List<Student> getListStudent() {
		return listStudent;
	}

}
  • struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
	<constant name="struts.enable.DynamicMethodInvocation" value="false" />
	<constant name="struts.devMode" value="false" />
	<constant name="struts.custom.i18n.resources" value="app-resources" />
	<constant name="struts.action.extension" value="html" />
    <constant name="struts.mapper.action.prefix.enabled" value="true"/>

	<package name="default" namespace="/" extends="struts-default">

		<action name="index">
			<result type="redirect">/login.html</result>
		</action>

	  <action name="showAddStudent" class="strutshelloworld.net.ren.struts2.actions.StudentAction" method="execute">
			<result name="success">/WEB-INF/jsp/AddStudent.jsp</result>
		</action>

		<action name="addStudent" class="strutshelloworld.net.ren.struts2.actions.StudentAction" method="addStudent">
			<result name="success" type="redirect">listStudent.html</result>
		</action>
		
		<action name="updateStudent" class="strutshelloworld.net.ren.struts2.actions.StudentAction" method="updateStudent">
			<result name="success" type="redirect">listStudent.html</result>
		</action>
		
		<action name="deleteStudent" class="strutshelloworld.net.ren.struts2.actions.StudentAction" method="deleteStudent">
			<result name="success" type="redirect">listStudent.html</result>
		</action> 
        
        <action name="deleteAll" class="strutshelloworld.net.ren.struts2.actions.StudentAction" method="deleteAll">
              <result name="success" type="redirect">listStudent.html</result>
        </action>
	
		<action name="getStudentById" class="strutshelloworld.net.ren.struts2.actions.StudentAction" method="getStudentById">
				<result name="success">/WEB-INF/jsp/AddStudent.jsp</result>
		</action> 
		  
	   <action name="listStudent" class="strutshelloworld.net.ren.struts2.actions.StudentAction" method="getAllStudent">
			<result name="success">/WEB-INF/jsp/ListStudent.jsp</result>
		</action>
		
		<action name="login" class="strutshelloworld.net.ren.struts2.actions.LoginAction">
			<result name="success">/WEB-INF/jsp/Welcome.jsp</result>
			<result name="error">/WEB-INF/jsp/Login.jsp</result>
			<result name="input">/WEB-INF/jsp/Login.jsp</result>
		</action>
	</package>

</struts>
  • application-context.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-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

	<context:property-placeholder location="classpath:hibernate.properties" />
	
    <context:annotation-config/>
    
    <context:component-scan base-package="strutshelloworld.net.ren.struts2"></context:component-scan>
    
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
	</bean>

	<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="packagesToScan" value="strutshelloworld.net.ren.struts2.domain" />
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
			</props>
		</property>
	</bean>

	<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
		
	<tx:annotation-driven transaction-manager="transactionManager" />

</beans>
  • application-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="struts_blank" version="2.4" 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">
  <display-name>Struts Blank</display-name>
  
   <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/application-context.xml</param-value>
    </context-param>
     
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>
      org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
    </filter-class>
  </filter>

  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
</web-app>
  • AddStudent.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add Student</title>
</head>
<body>
	<h1>Struts 2 ModelDriven example</h1>
	<s:if test="%{model.id == 0}">
		<h2>Add Student</h2>
	</s:if>
	<s:else>
		<h2>Update Student</h2>
	</s:else>
	<s:form action="addStudent">
		<s:if test="%{model.id != 0}">
            <s:textfield name="id" key="label.id" value="%{model.id}" />
	   </s:if>
		<s:textfield name="firstName" key="label.fname"
			value="%{model.firstName}" />
		<s:textfield name="lastName" key="label.lname"
			value="%{model.lastName}" />
		<s:if test="%{model.id == 0}">
			<s:submit key="label.submit" align="center"/>
		</s:if>
		<s:else>
			<s:submit key="label.update" align="center" action="updateStudent"/>
		</s:else>
	</s:form>
	
</body>
</html>
  • ListStudent.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>List of Student</title>
</head>
<body>
     <table cellpadding="5px">
		<tr class="even">
			<th>Id</th>
			<th>Fist Name</th>
			<th>Last Name</th>
			<th>Edit </th>
			<th>Delete </th>
		</tr>
        <c:forEach items="${listStudent}" var="student">
			<tr>
				<td><c:out value="${student.id}"/></td>
				<td><c:out value="${student.firstName}"/></td>
				<td><c:out value="${student.lastName}"/></td>
		    	<td>
               <s:url var="updateUrl" action="getStudentById">
					<s:param name="id">${student.id}</s:param>
				</s:url> 
				<s:a href="%{updateUrl}">Update</s:a>
                </td>
				<td>
                <s:url var="deleteUrl" action="deleteStudent">
					<s:param name="id">${student.id}</s:param>
				</s:url> 
                <s:a href="%{deleteUrl}">Delete</s:a>
                </td> 
			</tr>
		</c:forEach> 
	</table>
	<s:url var="deleteAllUrl" action="deleteAll"/>
	<s:a href="%{deleteAllUrl}">Delete All</s:a>
</body>
</html>

You can get project in here via Github
Thank you.

PS.
Before running this code, you must edit hibernate.properties file to adjust your local and create database with “hibernate” name in mysql.

Spring Auto Component Scanning

February 24, 2014 Leave a comment

Pada umumnya kita mendeklarasikan semua bean di file XML bean configuration, sehingga Spring container dapat mendeteksi bean tersebut. Spring sebenarnya dapat melakukan auto scan bean tersebut menggunakan annotation dan jadi lebih sederhana. Berikut ini example sederhana CRUD satu table ( menggunakan service dan dao layer ).

  • Table books
Book Table

Book Table

  • Model layer ( Book.java )


package com.spring.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="books")
public class Book {
@Id
@Column(name="id")
@GeneratedValue
private int id;

@Column(name="book_name")
private String bookName;

@Column(name="author")
private String author;

@Column(name="price")
private int price;

@Column(name="qty")
private int quantity;

public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getBookName() {
return bookName;
}
public void setAuthor(String author) {
this.author = author;
}
public String getAuthor() {
return author;
}
public void setPrice(int price) {
this.price = price;
}
public int getPrice() {
return price;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getQuantity() {
return quantity;
}
}

  • DAO layer

BookDao interface ( BookDao.java )

package com.spring.dao;

import java.util.List;

import com.spring.model.Book;

public interface BookDao {
public void addBook(Book book);
public void updateBook(Book book);
public List<Book> listBooks();
public Book getBookById(Integer bookId);
public void removeBook(Integer id);
}

BookDaoImpl ( BookDaoImpl.java )

package com.spring.dao;

import java.util.List;

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

import com.spring.model.Book;

@Repository
public class BookDaoImpl implements BookDao{

@Autowired
private SessionFactory sessionFactory;

@Override
public void addBook(Book book) {

sessionFactory.getCurrentSession().save(book);
}

@Override
public void removeBook(Integer id) {
Book book = (Book)sessionFactory.getCurrentSession()
.load(Book.class, id);
if(null != book) {
sessionFactory.getCurrentSession().delete(book);
}
}

@Override
@SuppressWarnings("unchecked")
public List<Book> listBooks() {
return sessionFactory.getCurrentSession()
.createQuery("from Book").list();
}

@Override
public void updateBook(Book book) {
sessionFactory.getCurrentSession().update(book);
}

@Override
@SuppressWarnings("unchecked")
public Book getBookById(Integer bookId) {
Session session = sessionFactory.getCurrentSession();
List<Book> list = session.createQuery("from Book b where b.id = :bookId")
.setParameter("bookId", bookId)
.list();
return list.size() > 0 ?(Book)list.get(0): null;
}
}

  • Service layer

BookService interface ( BookService.java )

package com.spring.service;

import java.util.List;
import com.spring.model.Book;

public interface BookService {
public void addBook(Book book);
public void updateBook(Book book);
public Book getBookById(Integer bookId);
public List<Book> listBooks();
public void removeBook(Integer id);
}

BookServiceImpl ( BookServiceImpl.java )

package com.spring.service;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.spring.dao.BookDao;
import com.spring.model.Book;

@Service
public class BookServiceImpl implements BookService{
@Autowired
private BookDao bookDao;

@Transactional
public void addBook(Book book) {
bookDao.addBook(book);
}

@Transactional
public void removeBook(Integer id) {
bookDao.removeBook(id);
}

@Transactional
public List<Book> listBooks() {
return bookDao.listBooks();
}

@Transactional
public void updateBook(Book book) {
bookDao.updateBook(book);
}

@Transactional
public Book getBookById(Integer bookId) {
return bookDao.getBookById(bookId);
}
}

  • Main class


package com.spring.main;

import java.util.Iterator;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.model.Book;
import com.spring.service.BookService;
import com.spring.service.BookServiceImpl;

public class Main {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("SpringBean.xml");
BookService bsImpl = (BookService) context.getBean("bookServiceImpl");

/*Insert*/
Book book = new Book();
book.setAuthor("JK Rowling");
book.setBookName("Harry Potter");
book.setPrice(100000);
book.setQuantity(100);
bsImpl.addBook(book);

/*Select*/
Book bookDua = bsImpl.getBookById(1);
System.out.println(bookDua.getId());
System.out.println(bookDua.getAuthor());
System.out.println(bookDua.getPrice());
System.out.println(bookDua.getQuantity());
System.out.println(bookDua.getBookName());

/*Update*/
Book bookTiga = bookDua;
bookTiga.setQuantity(11);
bsImpl.updateBook(bookTiga);

/*Select All */
List <Book> bookList = bsImpl.listBooks();
Iterator iter = bookList.iterator();
while(iter.hasNext()){
Book bookEmpat = (Book) iter.next();
System.out.println(bookEmpat.getAuthor());
System.out.println(bookEmpat.getBookName());
}
/*Delete*/
bsImpl.removeBook(1);

}
}

  • Bean configuration xml ( SpringBean.xml )


...
<context:annotation-config />
<context:component-scan base-package="com.spring" />

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>db.properties</value>
</property>
</bean>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.spring.model.Book</value>
</list>
</property>
</bean>
<tx:annotation-driven/>

<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
...

  • db properties


jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springdb
jdbc.username=root
jdbc.password=

  • Project Structure
Project Structure

Project Structure

Pada Spring terdapat 4 type auto components scan annotation.

  1. @Component : Annotation bersifat generic yang dapat digunakan pada semua layer
  2. @Service : Annotation class pada service layer
  3. @Repository : Annotation class pada dao layer
  4. @Controller : Annotation class pada presentation layer ( digunakan biasanya di Spring MVC )

Secara umum 4 annotation hampir tidak ada perbedaan, namun untuk readability penggunaan annotation tersebut disesuaikan layer class.

Referensi : dari berbagai sumber.
Semoga bermanfaat.