User:Saatwik Katiha/personal sandbox
User
package com.saatwik.domain;
import java.io.Serializable;
import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id;
@Entity public class User implements Serializable {
private static final long serialVersionUID = 1L; @Id @GeneratedValue private long id; private String username;
public long getId() { return id; }
public void setId(long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
AbstractRepository
package com.saatwik.repository;
import javax.persistence.EntityManager; import javax.persistence.PersistenceContext;
public class AbstractRepository<T> {
@PersistenceContext
protected EntityManager entityManager; public T persist(T t) { entityManager.persist(t); return t; } public T merge(T t) { return entityManager.merge(t); } public void remove(T t) { entityManager.remove(t); }
}
UserRepository
package com.saatwik.repository;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.saatwik.domain.User;
@Repository("userRepository") public class UserRepository extends AbstractRepository<User> {
@SuppressWarnings("unchecked") public List<User> getAll() {
return entityManager.createQuery( "SELECT u FROM User u ORDER BY u.username").getResultList();
}
}
UserService
package com.saatwik.service;
import java.util.List;
import com.saatwik.domain.User;
public interface UserService {
List<User> getAll() throws Exception;
User create(User user) throws Exception;
}
UserServiceImpl
package com.saatwik.service;
import java.text.ParseException; import java.util.List;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional;
import com.saatwik.domain.User; import com.saatwik.repository.UserRepository;
/**
* provides services for user. * */
@Service("userService") @Transactional(readOnly = true) public class UserServiceImpl implements UserService {
@Autowired private UserRepository userRepository;
public List<User> getAll() {
return userRepository.getAll(); }
@Transactional(readOnly = false) public User create(User user) throws ParseException {
return userRepository.merge(user);
}
}
HomeController
package com.saatwik.web;
import java.util.HashMap; import java.util.List; import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView;
import com.saatwik.domain.User; import com.saatwik.service.UserService;
@Controller @RequestMapping(value = { "" }) public class HomeController {
@Autowired private UserService userService;
@RequestMapping(value = { "", "/" }) public ModelAndView home() throws Exception {
Map<String, Object> params = new HashMap<String, Object>();
List<User> users = userService.getAll();
params.put("users", users);
params.put("user", new User());
return new ModelAndView("home", params); }
@RequestMapping("/save") public ModelAndView save(@ModelAttribute("user") User user) throws Exception {
Map<String, Object> params = new HashMap<String, Object>();
if (!StringUtils.hasText(user.getUsername())) {
params.put("usernameMessage", "Input required");
return new ModelAndView("home", params);
}
userService.create(user);
return new ModelAndView("redirect:/"); } }
src/META-INF/persistence.xml
<?xml version="1.0" encoding="UTF-8"?> <persistence version="1.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_1_0.xsd">
<persistence-unit name="jpa-example-PU" transaction-type="RESOURCE_LOCAL">
<class>com.saatwik.domain.User</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes> </persistence-unit>
</persistence>
src/jdbc.properties
- LOCAL
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://10.1.55.55:3306/demodb jdbc.username=root jdbc.password=root123
web-inf/jpa-example-servlet
<?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:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:property-placeholder location="classpath:jdbc.properties" /> <import resource="persistenceContext.xml" />
<context:annotation-config />
<context:component-scan base-package="com.saatwik" />
<mvc:annotation-driven />
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/view/" p:suffix=".jsp" p:order="1"/>
</beans>
web-inf/persistenceContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> <tx:annotation-driven transaction-manager="transactionManager"/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> <bean id="jpaTemplate" class="org.springframework.orm.jpa.JpaTemplate"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="jpaVendorAdapter" ref="jpaAdapter" /> <property name="persistenceUnitName" value="jpa-example-PU" /> <property name="loadTimeWeaver"> <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" /> </property> </bean>
<bean id="jpaAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect" /> <property name="generateDdl" value="true" /> <property name="showSql" value="false" /> </bean>
</beans>
web-inf/view/home.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/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>JPA - Hibernate Example</title> </head>
<body>
JPA - Hibernate Example
Add User:
<form:form method="post" modelAttribute="user" action="save">
<label>Username: </label> <form:input class="input-small" path="username" /> <label>${usernameMessage}</label>
<input class="button" type="submit" name="submit" value="Add" />
</form:form>
List of Users
ID | Username |
---|---|
${userVar.id} | ${userVar.username} |
</body> </html>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:javaee="http://xmlns.jcp.org/xml/ns/javaee" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd http://xmlns.jcp.org/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.4">
<display-name>jpa-example</display-name> <servlet> <servlet-name>jpa-example</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>jpa-example</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
</web-app>