一直觉得JPA很神秘,最近抽空看了下,下面贴出刚才做的Struts2整合Spring、JPA的例子。给自己的编程路留下新的脚印!
1. 打开MyEclipse新建Web project :testJpa
2. 导入相关的Jar包
3. 在src下新建META-INF文件夹
4. 在META-INF下添加persistence.xml文件,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<persistence 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" version="1.0">
<persistence-unit name="punit"></persistence-unit>
</persistence>
5. 在src下新建spring配置文件: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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<!-- 配置Jpa -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="MYSQL" />
<property name="showSql" value="true" />
</bean>
</property>
<!-- 根据实体Bean自动生成表 -->
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<!-- 配置数据源 -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/testjpa" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!-- 配置事务 -->
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory"
ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
6. 修改web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
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">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/classes/applicationContext.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.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
7. 新建实体com.njy.model.Person.java
package com.njy.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Person implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private int age;
private String address;
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
8. 编写Service接口:com.njy. serviceImpl.PersonService.java
package com.njy.service;
import java.util.List;
import com.njy.model.Person;
public interface PersonService {
public void save(Person person);
public void delete(Person person);
public void update(Person person);
public Person getById(Person person);
public List<Person> getAll();
}
9. Service的实现类:com.njy. serviceImpl. PersonServiceImpl.java
package com.njy.serviceImpl;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.transaction.annotation.Transactional;
import com.njy.model.Person;
import com.njy.service.PersonService;
@Transactional
public class PersonServiceImpl implements PersonService {
private EntityManager entityManager;
public void delete(Person person) {
//person = entityManager.find(Person.class, person.getId());
person = entityManager.getReference(Person.class, person.getId());
entityManager.remove(person);
}
@SuppressWarnings("unchecked")
public List<Person> getAll() {
Query query = getEntityManager().createQuery("select p FROM Person p");
return query.getResultList();
}
public Person getById(Person person) {
return entityManager.find(Person.class, person.getId());
}
public void save(Person person) {
entityManager.persist(person);
}
public void update(Person person) {
entityManager.merge(person);
}
public EntityManager getEntityManager() {
return entityManager;
}
@PersistenceContext
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
}
10. 在applicationContext.xml中加入Service的配置:
<!-- 配置Service -->
<bean id="PersonService" class="com.njy.serviceImpl.PersonServiceImpl"
scope="prototype">
</bean>
11. 在src下创建com.njy.action.Person.java
package com.njy.action;
import java.util.List;
import com.njy.model.Person;
import com.njy.service.PersonService;
public class PersonAction {
private static final long serialVersionUID = 1L;
private PersonService personService;
private Person person;
private List<Person> listPerson;
public String save() {
personService.save(person);
return "toShowList";
}
public String delete() {
personService.delete(person);
return "toShowList";
}
public String update() {
personService.update(person);
return "toShowList";
}
public String getById() {
person = personService.getById(person);
return "toEdit";
}
public String getAll() {
listPerson = personService.getAll();
return "toList";
}
public PersonService getPersonService() {
return personService;
}
public void setPersonService(PersonService personService) {
this.personService = personService;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public List<Person> getListPerson() {
return listPerson;
}
public void setListPerson(List<Person> listPerson) {
this.listPerson = listPerson;
}
}
12. 在src下新建struts.xml文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.objectFactory" value="spring"></constant>
<constant name="struts.i18n.encoding" value="UTF-8"></constant>
<package name="PersonAction" extends="struts-default">
<action name="person_*" method="{1}" class="personAction">
<result name="toShowList" type="redirect">
person_getAll.action
</result>
<result name="toList">/list.jsp</result>
<result name="toEdit">/edit.jsp</result>
</action>
</package>
</struts>
13. 在applicationContext.xml中加入Action和Service的配置:
<!-- 配置Action -->
<bean id="personAction" class="com.njy.action.PersonAction" scope="prototype">
<property name="personService">
<ref bean="PersonService" />
</property>
</bean>
14. 新建数据库testJpa,如果此处不建该库,程序会抛错,之后发布并运行程序。
15. View部分
既然是改写,这里我们依然采用之前的CRUD程序页面,详细代码请参看程序源代码,程序运行效果图如下所示:
【操作1:添加信息】
单击“添加”按钮,程序将转到列表页:
【操作2:修改信息】
修改后的列表页面:
【操作3:删除信息】
删除编号为1的记录,删除之后程序转到列表页:
程序源码的jar包在附件中,因附件大小有限制,故分成两个压缩包!请自行下载!