Introduction
Stand-alone Spring application sample, Spring framework supports the persistence layer to be fully implemented through JPA. Simple example of configure the Spring needed components to perform persistence over standard JPA i.e. Persistence Unit, the Entity Manager factory and the Transaction Manager.
Sample Implementation project folder structure :
implementation as DAO layer, Service layer and hibernate model.
Build POM.xml details.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.uttesh.spring.entitymanager</groupId> <artifactId>SpringEntityManager</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <name>SpringEntityManager</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>3.2.5.RELEASE</spring.version> <hibernate.version>4.1.9.Final</hibernate.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> </dependencies> </project>
JPA Entity model class
package com.uttesh.spring.entitymanager.model; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "USER") public class User { @Id @Column(name = "ID", nullable = false) private int id; @Column(name = "NAME", nullable = false) private String name; @Column(name = "PASSWORD", nullable = false) private String password; @Column(name = "EMAIL", nullable = false) private String email; @Column(name = "SEX", nullable = false) private String sex; @Column(name = "DOB", nullable = false) private Date dob; @Column(name = "MOBILE", nullable = false) private String mobile; 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; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getDob() { return dob; } public void setDob(Date dob) { this.dob = dob; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } }
Spring service and DAO layers
DAO layerpackage com.uttesh.spring.entitymanager.dao; import java.util.List; import com.uttesh.spring.entitymanager.model.User; public interface IUserDAO { public void save(User user); List<User> findAllUsers(); }
The Entity Manager is injected through the regular JPA @PersistenceContext annotation.
package com.uttesh.spring.entitymanager.dao.impl; import com.uttesh.spring.entitymanager.dao.IUserDAO; import com.uttesh.spring.entitymanager.model.User; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import org.springframework.stereotype.Repository; @Repository //@Transactional(propagation = Propagation.MANDATORY, rollbackFor = {Exception.class}) public class UserDAOImpl implements IUserDAO { @PersistenceContext private EntityManager entityManager; @Override public void save(User user) { entityManager.persist(user); System.out.println("saved record : " + user.getId()); } @Override public List<User> findAllUsers() { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<User> cq = builder.createQuery(User.class); Root<User> root = cq.from(User.class); cq.select(root); return entityManager.createQuery(cq).getResultList(); } }
service layer
package com.uttesh.spring.entitymanager.user; import java.util.List; import com.uttesh.spring.entitymanager.model.User; public interface IUserService { void save(User user); List<User> findAllUsers(); }
package com.uttesh.spring.entitymanager.user.impl; import com.uttesh.spring.entitymanager.dao.IUserDAO; import com.uttesh.spring.entitymanager.model.User; import com.uttesh.spring.entitymanager.user.IUserService; import java.util.List; import java.lang.UnknownError; import java.util.logging.Level; import java.util.logging.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @Service //@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED) public class UserServiceImpl implements IUserService { @Autowired private IUserDAO userDAO; //@Transactional(readOnly = false) public void save(User user) { try { userDAO.save(user); save1(); // save2(); } catch (InterruptedException ex) { Logger.getLogger(UserServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } } public void save1() throws InterruptedException { User user = new User(); user.setId(1008); user.setName("Uttesh kumar"); user.setEmail("uttesh@gmail.com"); user.setMobile("0123456789"); user.setPassword("password"); userDAO.save(user); } public void save2() { throw new UnknownError("INVALID"); } @Transactional(readOnly = false) public List<User> findAllUsers() { return userDAO.findAllUsers(); } }
persistence.xml
<?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="springEntitypersistenceUnit" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <class>com.uttesh.spring.entitymanager.model.User</class> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/> </properties> </persistence-unit> </persistence>
spring.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" 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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <tx:annotation-driven /> <context:component-scan base-package="com.uttesh.spring.entitymanager.dao.impl" /> <context:component-scan base-package="com.uttesh.spring.entitymanager.user.impl" /> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/lab" /> <property name="username" value="user" /> <property name="password" value="password" /> </bean> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="persistenceUnitName" value="springEntitypersistenceUnit" /> <property name="dataSource" ref="dataSource" /> </bean> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> </beans>
Testing
execute the sample.java class.package com.uttesh.spring.entitymanager; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.uttesh.spring.entitymanager.model.User; import com.uttesh.spring.entitymanager.user.IUserService; public class Sample { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml"); IUserService userManager = (IUserService) ctx.getBean("userServiceImpl"); List<User> list = userManager.findAllUsers(); User user = new User(); user.setId(1006); user.setName("Uttesh kumar"); user.setEmail("uttesh@gmail.com"); user.setMobile("0123456789"); user.setPassword("password"); userManager.save(user); System.out.println("User Saved"); list = userManager.findAllUsers(); System.out.println("User count: " + list.size()); } }
Download source code from github Click here.
0 comments:
Post a Comment