Structs2+spring+hibernate+JPA整合

1.目录

2.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/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext*.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <!-- 配置 Struts2 的 Filter -->
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

2.db.properties

jdbc.user=root
jdbc.password=1234
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///spring7

jdbc.initPoolSize=5
jdbc.maxPoolSize=10
#...

3.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:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
    
    <!-- spring注解配置-->
<!--     <context:annotation-config/>-->
    <context:component-scan base-package="com.atguigu.ssh"></context:component-scan> 

    <!-- 导入资源文件 -->
    <context:property-placeholder location="classpath:db.properties"/>

    <!-- 配置 C3P0 数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="driverClass" value="${jdbc.driverClass}"></property>
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
        
        <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
        <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
    </bean>
    
    <!-- 配置 SessionFactory -->
<!--     <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
        自动扫描实体
        <property name="packagesToScan"  value="com.atguigu.ssh.entities"/>
    </bean> -->
    
    <!-- 配置 EntityManagerFactory -->
    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <!-- 配置 JPA 提供商的适配器. 可以通过内部 bean 的方式来配置 -->
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"></bean>
        </property>    
        <!-- 配置实体类所在的包 -->
        <property name="packagesToScan" value="com.atguigu.ssh.entities"></property>
        <!-- 配置 JPA 的基本属性. 例如 JPA 实现产品的属性 -->
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>
    
    
    
    <!-- 配置 Spring 的声明式事务 -->
    <!-- 1. 配置 hibernate 的事务管理器 -->
<!--     <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean> -->
    
    <!-- 配置 JPA 使用的事务管理器 -->
    <bean id="transactionManager"
        class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"></property>    
    </bean>
    

    <!-- 2. 配置事务属性 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="lastNameIsValid" read-only="true"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>
    
    <!-- 3. 配置事务切入点, 再把事务属性和事务切入点关联起来 -->
    <aop:config>
        <aop:pointcut expression="execution(* com.atguigu.ssh.service.*.*(..))" id="txPointcut"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config>

</beans>

4.struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />

    <package name="default" namespace="/" extends="struts-default">
    
        <!-- 定义新的拦截器栈, 配置 prepare 拦截器栈的 alwaysInvokePrepare 参数值为 false -->
        <interceptors>
            <interceptor-stack name="sshStack">
                <interceptor-ref name="paramsPrepareParamsStack">
                    <param name="prepare.alwaysInvokePrepare">false</param>
                </interceptor-ref>
            </interceptor-stack>
        </interceptors>
        
        <!-- 使用新的拦截器栈 -->
        <default-interceptor-ref name="sshStack"></default-interceptor-ref>
    
        <action name="emp-*" class="employeeAction"
            method="{1}">
            <result name="list">/WEB-INF/views/emp-list.jsp</result>
            <result type="stream" name="ajax-success">
                <param name="contentType">text/html</param>
                <param name="inputName">inputStream</param>
            </result>    
            <result name="input">/WEB-INF/views/emp-input.jsp</result>
            <result name="success" type="redirect">/emp-list</result>
        </action>
            
    </package>

</struts>

5.entity

参考JPA注解文章

6.dao

public class BaseDao {
    
    @PersistenceContext
    private EntityManager entityManager;

    public EntityManager getEntityManager() {
        return entityManager;
    }

    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }
}

7.Service

@Service
public class DepartmentService {
    
    @Autowired
    private DepartmentDao departmentDao;
    
    public void setDepartmentDao(DepartmentDao departmentDao) {
        this.departmentDao = departmentDao;
    }
    @Transactional
    public List<Department> getAll(){
        return departmentDao.getAll();
    }
    
}

8.Actions

@Controller
public class EmployeeAction extends ActionSupport implements RequestAware,
 ModelDriven<Employee>, Preparable{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    
    @Autowired
    private EmployeeService employeeService;

    public void setEmployeeService(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }
    
    @Autowired
    private DepartmentService departmentService;
    
    public void setDepartmentService(DepartmentService departmentService) {
        this.departmentService = departmentService;
    }

    public String list() {
        request.put("employees", employeeService.getAll());
        return "list";
    }

    private Integer id;

    public void setId(Integer id) {
        this.id = id;
    }

    private InputStream inputStream;

    public InputStream getInputStream() {
        return inputStream;
    }

    public String delete() {
        try {
            employeeService.delete(id);
            inputStream = new ByteArrayInputStream("1".getBytes("UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
            try {
                inputStream = new ByteArrayInputStream("0".getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
        }
        return "ajax-success";
    }
    
    public String input(){
        request.put("departments", departmentService.getAll());
        return INPUT;
    }
    
    public void prepareInput(){
        if(id != null){
            model = employeeService.get(id);
        }
    }
    
    public String save(){
        if(id == null){
            model.setCreateTime(new Date());            
        }
        //System.out.println(model);
        employeeService.saveOrUpdate(model);
        return SUCCESS;
    }
    
    /**
     * 可以根据 id 来判断为 save 方法准备的 model 是 new 的还是从数据库获取的!
     */
    public void prepareSave(){
        if(id == null){
            model = new Employee();
        }else{
            model = employeeService.get(id);
        }
    }
    
    private String lastName;
    
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    
    public String validateLastName() throws UnsupportedEncodingException{
        if(employeeService.lastNameIsValid(lastName)){
            inputStream = new ByteArrayInputStream("1".getBytes("UTF-8")); 
        }else{
            inputStream = new ByteArrayInputStream("0".getBytes("UTF-8")); 
        }
        
        return "ajax-success";
    }

    private Map<String, Object> request;

    @Override
    public void setRequest(Map<String, Object> arg0) {
        this.request = arg0;
    }

    @Override
    public void prepare() throws Exception {}

    private Employee model;
    
    @Override
    public Employee getModel() {
        return model;
    }

}

9.总结

JPA与hibernate的整合关键在于dao层的方法调用,其余的只是配置文件上的区别,上面已经列出

 

注:以上代码源自尚硅谷的ssh+JPA视频教程学习整理

后续会整理一份完整的学习视频

posted @ 2019-08-16 09:52  SI3  阅读(284)  评论(0编辑  收藏  举报