User:Saatwik Katiha/personal sandbox: Difference between revisions
No edit summary |
No edit summary |
||
Line 1: | Line 1: | ||
''' |
'''User''' |
||
package com.saatwik. |
package com.saatwik.domain; |
||
import java.io.Serializable; |
|||
import org.springframework.beans.factory.annotation.Autowired; |
|||
import org.springframework.context.annotation.ComponentScan; |
|||
import org.springframework.stereotype.Controller; |
|||
import org.springframework.ui.Model; |
|||
import org.springframework.web.bind.annotation.ModelAttribute; |
|||
import org.springframework.web.bind.annotation.RequestMapping; |
|||
import org.springframework.web.bind.annotation.RequestMethod; |
|||
import com.saatwik.model.Subscriber; |
|||
import com.saatwik.service.SubscriberService; |
|||
@Controller |
|||
@ComponentScan("com.saatwik") |
|||
public class FormController { |
|||
@Autowired |
|||
private SubscriberService subscriberService; |
|||
@RequestMapping(value = "form", method = RequestMethod.GET) |
|||
public String loadFormPage(Model m) { |
|||
m.addAttribute("subscriber", new Subscriber()); |
|||
return "formPage"; |
|||
} |
|||
@RequestMapping(value = "form", method = RequestMethod.POST) |
|||
public String submitForm(@ModelAttribute Subscriber subscriber, Model m) { |
|||
subscriberService.addSubscriber(subscriber); |
|||
m.addAttribute("message", |
|||
"Successfully saved person: " + subscriber.toString()); |
|||
return "formPage"; |
|||
} |
|||
} |
|||
'''Subscriber''' |
|||
package com.saatwik.model; |
|||
import javax.persistence.Column; |
|||
import javax.persistence.Entity; |
import javax.persistence.Entity; |
||
import javax.persistence.GeneratedValue; |
|||
import javax.persistence.Id; |
import javax.persistence.Id; |
||
import javax.persistence.Table; |
|||
@Entity |
@Entity |
||
public class User implements Serializable { |
|||
@Table(name = "subscriber") |
|||
public class Subscriber { |
|||
private static final long serialVersionUID = 1L; |
|||
@Id |
|||
@GeneratedValue |
|||
private long id; |
|||
private String username; |
|||
public long getId() { |
|||
return id; |
|||
} |
|||
private String name; |
|||
private String email; |
|||
private Integer age; |
|||
public void setId(long id) { |
|||
@Column(name = "name") |
|||
this.id = id; |
|||
public String getName() { |
|||
return name; |
|||
} |
} |
||
public void setName(String name) { |
|||
this.name = name; |
|||
} |
|||
public String getUsername() { |
|||
@Id |
|||
return username; |
|||
@Column(name = "email") |
|||
public String getEmail() { |
|||
return email; |
|||
} |
} |
||
public void setEmail(String email) { |
|||
this.email = email; |
|||
} |
|||
public void setUsername(String username) { |
|||
@Column(name = "age") |
|||
this.username = username; |
|||
public Integer getAge() { |
|||
return age; |
|||
} |
} |
||
} |
|||
public void setAge(Integer age) { |
|||
this.age = age; |
|||
} |
|||
'''AbstractRepository''' |
|||
} |
|||
package com.saatwik.repository; |
|||
'''SubscriberDAO''' |
|||
import javax.persistence.EntityManager; |
|||
package com.saatwik.model; |
|||
import javax.persistence.PersistenceContext; |
|||
public |
public class AbstractRepository<T> { |
||
public void save(Subscriber subscriber); |
|||
@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; |
|||
package com.saatwik.model; |
|||
import org.hibernate.Session; |
|||
import org.hibernate.SessionFactory; |
|||
import org.springframework.stereotype.Repository; |
import org.springframework.stereotype.Repository; |
||
import com.saatwik.domain.User; |
|||
@Repository |
|||
public class SubscriberDAOImpl implements SubscriberDAO { |
|||
private SessionFactory sessionfactory; |
|||
@Repository("userRepository") |
|||
public void setSessionfactory(SessionFactory sessionfactory) { |
|||
public class UserRepository extends AbstractRepository<User> { |
|||
this.sessionfactory = sessionfactory; |
|||
} |
|||
@SuppressWarnings("unchecked") |
|||
public void save(Subscriber subscriber) { |
|||
public List<User> getAll() { |
|||
return entityManager.createQuery( |
|||
Session session = sessionfactory.openSession(); |
|||
"SELECT u FROM User u ORDER BY u.username").getResultList(); |
|||
session.saveOrUpdate(subscriber); |
|||
session.flush(); |
|||
sessionfactory.openSession().saveOrUpdate(subscriber); |
|||
} |
} |
||
} |
} |
||
''' |
'''UserService''' |
||
package com.saatwik.service; |
package com.saatwik.service; |
||
import |
import java.util.List; |
||
import com.saatwik.domain.User; |
|||
public interface UserService { |
|||
List<User> getAll() throws Exception; |
|||
User create(User user) throws Exception; |
|||
public interface SubscriberService { |
|||
public void addSubscriber(Subscriber subscriber); |
|||
} |
} |
||
'''SubsServImpl''' |
|||
'''UserServiceImpl''' |
|||
package com.saatwik.service; |
package com.saatwik.service; |
||
import java.text.ParseException; |
|||
import java.util.List; |
|||
import org.springframework.beans.factory.annotation.Autowired; |
import org.springframework.beans.factory.annotation.Autowired; |
||
import org.springframework.stereotype.Service; |
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") |
|||
import com.saatwik.model.Subscriber; |
|||
@Transactional(readOnly = true) |
|||
import com.saatwik.model.SubscriberDAO; |
|||
public class UserServiceImpl implements UserService { |
|||
@Service |
|||
public class SubscriberServiceImpl implements SubscriberService { |
|||
@Autowired |
@Autowired |
||
private UserRepository userRepository; |
|||
SubscriberDAO subscriberDAO; |
|||
public List<User> getAll() { |
|||
@Override |
|||
public void addSubscriber(Subscriber subscriber) { |
|||
return userRepository.getAll(); |
|||
subscriberDAO.save(subscriber); |
|||
} |
} |
||
@Transactional(readOnly = false) |
|||
public User create(User user) throws ParseException { |
|||
return userRepository.merge(user); |
|||
} |
|||
} |
} |
||
''' |
'''HomeController''' |
||
package com.saatwik. |
package com.saatwik.web; |
||
import java.util. |
import java.util.HashMap; |
||
import java.util.List; |
|||
import java.util.Map; |
|||
import org.springframework. |
import org.springframework.beans.factory.annotation.Autowired; |
||
import org.springframework. |
import org.springframework.stereotype.Controller; |
||
import org.springframework. |
import org.springframework.util.StringUtils; |
||
import org.springframework. |
import org.springframework.web.bind.annotation.ModelAttribute; |
||
import org.springframework. |
import org.springframework.web.bind.annotation.RequestMapping; |
||
import org.springframework. |
import org.springframework.web.servlet.ModelAndView; |
||
import org.springframework.web.servlet.config.annotation.EnableWebMvc; |
|||
import org.springframework.web.servlet.view.InternalResourceViewResolver; |
|||
import com.saatwik.domain.User; |
|||
@Configuration |
|||
import com.saatwik.service.UserService; |
|||
@EnableWebMvc |
|||
@ComponentScan(basePackages = "com.saatwik") |
|||
public class WebConfig { |
|||
@Bean |
|||
public InternalResourceViewResolver viewResolver() { |
|||
InternalResourceViewResolver resolver = new InternalResourceViewResolver(); |
|||
resolver.setPrefix("/WEB-INF/view/"); |
|||
resolver.setSuffix(".jsp"); |
|||
return resolver; |
|||
} |
|||
@Controller |
|||
@Bean |
|||
@RequestMapping(value = { "" }) |
|||
public DriverManagerDataSource dataSource() { |
|||
public class HomeController { |
|||
DriverManagerDataSource dataSource = new DriverManagerDataSource(); |
|||
dataSource.setDriverClassName("com.mysql.jdbc.Driver"); |
|||
dataSource.setUrl("jdbc:mysql://localhost:3306/saatwikschema"); |
|||
dataSource.setUsername("root"); |
|||
dataSource.setPassword("dennis"); |
|||
return dataSource; |
|||
} |
|||
@Autowired |
|||
@Bean |
|||
private UserService userService; |
|||
public LocalSessionFactoryBean sessionFactory() { |
|||
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); |
|||
sessionFactory.setDataSource(dataSource()); |
|||
sessionFactory.setAnnotatedClasses(com.saatwik.model.Subscriber.class); |
|||
Properties hibernateProperties = new Properties(); |
|||
hibernateProperties.setProperty("hibernate.dialect", |
|||
"org.hibernate.dialect.MySQLDialect"); |
|||
hibernateProperties.setProperty("hibernate.show_sql", "true"); |
|||
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", |
|||
"create/update"); |
|||
sessionFactory.setHibernateProperties(hibernateProperties); |
|||
@RequestMapping(value = { "", "/" }) |
|||
return sessionFactory; |
|||
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") |
|||
@Bean |
|||
public ModelAndView save(@ModelAttribute("user") User user) throws Exception { |
|||
public HibernateTransactionManager hibernateTransactionManager() { |
|||
HibernateTransactionManager hibernateTransactionManager = new HibernateTransactionManager(); |
|||
Map<String, Object> params = new HashMap<String, Object>(); |
|||
hibernateTransactionManager.setSessionFactory(sessionFactory() |
|||
.getObject()); |
|||
if (!StringUtils.hasText(user.getUsername())) { |
|||
return hibernateTransactionManager; |
|||
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> |
|||
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> |
|||
'''src/jdbc.properties''' |
|||
<!DOCTYPE HTML> |
|||
<html> |
|||
### LOCAL |
|||
<head> |
|||
jdbc.driver=com.mysql.jdbc.Driver |
|||
<title>Sample Form</title> |
|||
jdbc.url=jdbc:mysql://10.1.55.55:3306/demodb |
|||
jdbc.username=root |
|||
</head> |
|||
jdbc.password=root123 |
|||
<body> |
|||
<div id="container"> |
|||
'''web-inf/jpa-example-servlet''' |
|||
<h2>Subscribe to The Newsletter!</h2> |
|||
<?xml version="1.0" encoding="UTF-8"?> |
|||
<div>${message}</div> |
|||
<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" /> |
|||
<!-- Activates various annotations to be detected in bean classes --> |
|||
<form:form modelAttribute="subscriber"> |
|||
<context:annotation-config /> |
|||
<label for="nameInput">Name: </label> |
|||
<form:input path="name" id="nameInput" /> |
|||
<br/> |
|||
<label for="ageInput">Age: </label> |
|||
<form:input path="age" id="ageInput" /> |
|||
<br/> |
|||
<label for="emailInput">Email: </label> |
|||
<form:input path="email" id="emailInput" /> |
|||
<br/> |
|||
<!-- Scans the classpath for annotated components that will be auto-registered as Spring beans. |
|||
<br/> |
|||
For example @Controller and @Service. Make sure to set the correct base-package --> |
|||
<input type="submit" value="Submit" /> |
|||
<context:component-scan base-package="com.saatwik" /> |
|||
</form:form> |
|||
</div> |
|||
</body> |
|||
</html> |
|||
<!-- Configures the annotation-driven Spring MVC Controller programming model. |
|||
Note that, with Spring 3.0, this tag works in Servlet MVC only! --> |
|||
<mvc:annotation-driven /> |
|||
<!-- Declare a view resolver --> |
|||
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" |
|||
p:prefix="/WEB-INF/view/" p:suffix=".jsp" p:order="1"/> |
|||
</beans> |
|||
'''web.xml''' |
'''web-inf/persistenceContext.xml''' |
||
<?xml version="1.0" encoding="UTF-8"?> |
<?xml version="1.0" encoding="UTF-8"?> |
||
< |
<beans xmlns="http://www.springframework.org/schema/beans" |
||
xmlns: |
xmlns:mvc="http://www.springframework.org/schema/mvc" |
||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
|||
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> |
|||
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> |
|||
<h1>JPA - Hibernate Example</h1> |
|||
<h2>Add User: </h2> |
|||
<form:form method="post" modelAttribute="user" action="save"> |
|||
<p> <label>Username: </label> <form:input class="input-small" path="username" /> |
|||
<label>${usernameMessage}</label></p> |
|||
<p><input class="button" type="submit" name="submit" value="Add" /></p> |
|||
</form:form> |
|||
<h2>List of Users</h2> |
|||
<table> |
|||
<tr> |
|||
<th>ID</th> |
|||
<th>Username</th> |
|||
</tr> |
|||
<c:forEach items="${users}" var="userVar" varStatus="status"> |
|||
<tr> |
|||
<td>${userVar.id}</td> |
|||
<td>${userVar.username}</td> |
|||
</tr> |
|||
</c:forEach> |
|||
</table> |
|||
</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> |
||
<servlet-name> |
<servlet-name>jpa-example</servlet-name> |
||
<servlet-class> |
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> |
||
org.springframework.web.servlet.DispatcherServlet |
|||
</servlet-class> |
|||
<init-param> |
|||
<param-name>contextClass</param-name> |
|||
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value> |
|||
</init-param> |
|||
<init-param> |
|||
<param-name>contextConfigLocation</param-name> |
|||
<param-value>com.saatwik.springconfig</param-value> |
|||
</init-param> |
|||
</servlet> |
</servlet> |
||
<servlet-mapping> |
<servlet-mapping> |
||
<servlet-name> |
<servlet-name>jpa-example</servlet-name> |
||
<url-pattern>/</url-pattern> |
<url-pattern>/</url-pattern> |
||
</servlet-mapping> |
</servlet-mapping> |
||
</web-app> |
</web-app> |
Revision as of 20:16, 26 March 2014
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>