SSH-JPA环境搭建
JPA环境的搭建:
1. 新建Web工程
项目名:shop
ContentPath:/
2. JPA环境的搭建
文件:hibernate-distribution-3.3.2.GA-dist.zip,
hibernate-entitymanager-3.4.0.GA.zip
mysql-connector-java-5.1.12.zip
所需Jar文件:
2.1 Hibernate的Jar文件:
hibernate3.jar,antlr-2.7.6.jar, commons-collections-3.1.jar,dom4j-1.6.1.jar,javassist-3.9.0.GA.jar,jta-1.1.jar,slf4j-api-1.5.8.jar,c3p0-0.9.1.jar,oscache-2.1.jar,
slf4j-log4j12.jar,log4j.jar
2.2 entitymanager的jar文件:
hibernate-entitymanager.jar,hibernate-annotations.jar,
hibernate-commons-annotations.jar,hibernate-core.jar,ejb3-persistence.jar
2.3 MySQL驱动包
mysql-connector-java-5.1.12-bin.jar
3. JPA配置文件
在类路径下新建文件夹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="shop" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.url"
value="jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=UTF-8" />
<property name="hibernate.connection.username" value="root" />
<property name="hibernate.connection.password" value="root" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.jdbc.fetch_size" value="25" />
<property name="hibernate.jdbc.batch_size" value="10" />
</properties>
</persistence-unit>
</persistence>
4. JPA测试
4.1 新建Entity类:
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class ProductType implements Serializable {
private Integer typeId;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Integer getTypeId() {
return typeId;
}
public void setTypeId(Integer typeId) {
this.typeId = typeId;
}
}
4.2 新建Junit测试类:
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.junit.Test;
import cn.zlj.shop.bean.product.ProductType;
public class ProductTest {
@Test
public void testRun() {
EntityManagerFactory factory = Persistence
.createEntityManagerFactory("shop");
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
em.persist(new ProductType());
em.getTransaction().commit();
em.close();
factory.close();
}
}
4.2 运行JUnit
4.2.1 Console:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate:
insert
into
ProductType
values
( )
4.2.2 MySQL数据库
mysql> use shop;
Database changed
mysql> show tables;
+----------------+
| Tables_in_shop |
+----------------+
| producttype |
+----------------+
1 row in set (0.00 sec)
mysql> select * from producttype;
+--------+
| typeId |
+--------+
| 1 |
+--------+
1 row in set (0.00 sec)
JPA环境搭建成功。
Sring2.5集成JPA:
1. 文件:spring-framework-2.5.6.SEC01-with-dependencies.zip
所需Jar文件:spring.jar
Aspect : aspectjrt.jar, aspectjweaver.jar
Cglib: cglib-nodep-2.1_3.jar
J2EE: common-annotations.jar
Dbcp: commons-dbcp.jar, commons-pool.jar,
commons-logging.jar
2. 项目源文件夹下新建文件:beans.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: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.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<aop:aspectj-autoproxy />
<context:component-scan base-package="cn.*" />
<context:property-placeholder location="classpath:jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${driverClassName}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<!--连接池启动时的初始值 -->
<property name="initialSize" value="${initialSize}" />
<!--连接池的最大值 -->
<property name="maxActive" value="${maxActive}" />
<!--最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
<property name="maxIdle" value="${maxIdle}" />
<!--最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
<property name="minIdle" value="${minIdle}" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="loadTimeWeaver">
<bean
class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
3. 修改persistence.xml
将以下配置项删除:
hibernate.connection.driver_class,
hibernate.connection.username,
hibernate.connection.password,
hibernate.connection.url
<!--
<property name="hibernate.connection.driver_class"
value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.url"
value="jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=UTF-8"/>
<property name="hibernate.connection.username" value="root" />
<property name="hibernate.connection.password" value="root" />
-->
项目源文件夹下新建文件:jdbc.properties
driverClassName= com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=UTF-8
username=root
password=root
initialSize=1
maxActive=100
maxIdle=8
minIdle=1
集成测试:
4. 业务的接口类ProductTypeService.java
public interface ProductTypeService {
public void save(ProductType type);
}
5. 业务的具体实现类ProductTypeServiceBean.java
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class ProductTypeServiceBean implements ProductTypeService {
@PersistenceContext
private EntityManager em;
public void save(ProductType type) {
em.persist(type);
}
}
6. JUnit测试类ProductTest.java
public class ProductTest {
@Test
public void testRun() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
ProductTypeService productTypeService = (ProductTypeService) ctx
.getBean("productTypeServiceBean");
productTypeService.save(new ProductType());
}
}
7. 运行JUnit测试类
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
Hibernate:
insert
into
ProductType
values
( )
8. 数据库
mysql> select * from producttype;
+--------+
| typeId |
+--------+
| 1 |
| 2 |
+--------+
2 rows in set (0.00 sec)
集成成功。
Sring2.5集成Struts1.3:
1. 所需Jar文件:
Struts1.3.10中
antlr-2.7.2.jar,bsf-2.3.0.jar,commons-beanutils-1.8.0.jar
commons-chain-1.2.jar,commons-digester-1.8.jar,commons-fileupload-1.1.1.jar,commons-io-1.1.jar,
commons-logging-1.0.4.jar,commons-validator-1.3.1.jar
jstl-1.0.2.jar,oro-2.0.8.jar,standard-1.0.6.jar,struts-core-1.3.10.jar
struts-el-1.3.10.jar,struts-extras-1.3.10.jar,struts-faces-1.3.10.jar
struts-mailreader-dao-1.3.10.jar,struts-scripting-1.3.10.jar
struts-taglib-1.3.10.jar,struts-tiles-1.3.10.jar
Spring2.5中:
spring-webmvc-struts.jar
2. 在Web.xml中配置启动Spring的Listener
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:beans.xml</param-value>
</context-param>
<!-- 实例化Spring容器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
3. 在Web.xml中配置struts支持
<servlet>
<servlet-name>struts</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>struts</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
4. 在WEB-INF/中添加struts的配置文件struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<controller>
<set-property property="processorClass"
value="org.springframework.web.struts.DelegatingRequestProcessor" />
</controller>
</struts-config>
5. 测试
5.1 编写控制器类: ProductTypeAction.java
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.stereotype.Controller;
import cn.shop.bean.product.ProductType;
import cn.shop.service.product.ProductTypeService;
@Controller("/control/product/type/list")
public class ProductTypeAction extends Action {
@Resource(name = "productTypeServiceBean")
private ProductTypeService productTypeService;
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
productTypeService.save(new ProductType());
request.setAttribute("msg", "成功!!");
return mapping.findForward("success");
}
}
5.2 修改struts配置文件
<action-mappings>
<action path="/control/product/type/list">
<forward name="success" path="/WEB-INF/page/message.jsp" />
</action>
</action-mappings>
5.3 在/WEB-INF/page/下,新建jsp文件message.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!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=UTF-8">
<title>message</title>
</head>
<body>
消息:${msg}
</body>
</html>
5.4 启动Web服务器
启动成功后,通过浏览器访问control/product/type/list.do
url: http://localhost:8080/control/product/type/list.do
浏览器输出结果:
消息:成功!!
5.5 数据库
mysql> select * from producttype;
+--------+
| typeId |
+--------+
| 1 |
| 2 |
| 3 |
+--------+
3 rows in set (0.00 sec)
集成完成。