ssh

<?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"
       xmlns:cache="http://www.springframework.org/schema/cache"
       
       xsi:schemaLocation="http://www.springframework.org/schema/beans  
                           http://www.springframework.org/schema/beans/spring-beans.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/aop
                           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
                           http://www.springframework.org/schema/cache
                           http://www.springframework.org/schema/cache/spring-cache.xsd">

    <!-- post-processors for all standard config annotations -->
    <context:annotation-config/>
    
    <!--设置二级缓存的配置方式为Annotation -->
    <cache:annotation-driven />
    
    <!--自动扫描,并加载Bean-->
    <context:component-scan base-package="com.chinasoft" />
    
    <!--加载jdbc连接配置文件 -->
    <context:property-placeholder location="classpath:config/jdbc.properties" />
    <!-- 配置Data Source -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>
    
    <!--
        通过DBCP的方式配置Data Source时,通过实践我发现,除了需要spring默认的jar包以外,还需要以下jar包
        commons-dbcp.jar
        commons-logging.jar
        commons-pool.jar
        commons-collections.jar
     -->
    <!--
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>
    -->
    
    <!-- 构建Hibernate的Session Factory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!--
            装载Entity有三种形式 :
            <1>.通过配置XML的形式
            <2>.通过配置Class类的形式
            <3>.通过自动扫描文件夹的形式
        -->
        <!--第一种方式:通过配置XML的形式来加载Entity,在LocalSessionFactoryBean类中有一个mappingResources属性 -->
        <!--
        <property name="mappingResources">
            <list>
                <value>com/chinasoft/entity/User.hbm.xml</value>
            </list>
        </property>
         -->
        
        <!--第二种方式:使用annotation的形式,在LocalSessionFactoryBean类中有一个annotatedClasses属性 -->
        <!--
        <property name="annotatedClasses">
            <list>
                <value>com.chinasoft.entity.User</value>
            </list>
        </property>
         -->
         <!--第三种方式:使用自动扫描文件夹的形式,在LocalSessionFactoryBean类中有一个packagesToScan属性 -->
        <property name="packagesToScan">
            <list>
                <value>com.chinasoft.entity</value>
            </list>
        </property>
        
        <!--
            在LocalSessionFactoryBean这个类中应该有一个hibernateProperties属性,
                  这个属性告诉程序应该用什么数据库方言,其中,hibernate的properties可以参考hibernate文档
            3.4. Optional configuration properties
        -->
        <property name="hibernateProperties">
          <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
          </props>
        </property>
    </bean>
    
    <!-- 配置事务管理者 -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    
    <!-- <1>声明使用annotation的方式来处理事务 -->
    <!--<tx:annotation-driven transaction-manager="transactionManager"/> -->
    
    <!-- <2>使用Xml的方式来处理事务,也就是Aop的声明式事务 -->
    <aop:config>
        <!-- 定义一个pointcut -->
        <aop:pointcut id="serviceTransactionBusiness" expression="execution(public * com.chinasoft.service..*.*(..))" />
        <!--建议将哪个advice加在定义的pointcut上面 -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceTransactionBusiness"/>
    </aop:config>
    
    <!-- 建议的定义,声明式事务建议 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!--所有以find开头的方法都会加上read-only事务 -->
            <tx:method name="find*" read-only="true" />
            <!-- 设定以add,update,delete开头的方法都启用默认的事务 -->
            <tx:method name="add*" propagation="REQUIRED" isolation="DEFAULT"/>
            <tx:method name="update*" propagation="REQUIRED" isolation="DEFAULT" />
            <tx:method name="delete*" propagation="REQUIRED" isolation="DEFAULT" />
        </tx:attributes>
    </tx:advice>
    
    <!-- 加载ehcache配置文件 -->
    <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <property name="configLocation" value="classpath:config/ehcache.xml" />
    </bean>
    
    <!-- 声明Cache的管理者 -->
    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
        <property name="cacheManager" ref="ehcache" />
    </bean>

</beans>

-----------------------applicationContext.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">
        <default-action-ref name="index" />
        <global-results>
            <result name="error">/error.jsp</result>
        </global-results>

        <global-exception-mappings>
            <exception-mapping exception="java.lang.Exception" result="error"/>
        </global-exception-mappings>

        <action name="index">
            <result type="redirectAction">
                <param name="actionName">HelloWorld</param>
                <param name="namespace">/example</param>
            </result>
        </action>
    </package>
    <include file="example.xml"/>
    -->
    <!-- struts中动态的方法调用 -->
    <constant name="struts.enable.DynamicMethodInvocation" value="true" />
    <!-- 开发模式设置成true表示支持热部署 -->
    <constant name="struts.devMode" value="true" />
    
    <package name="com.chinasoft.user" namespace="/" extends="struts-default">
        <action name="userAction"  class="com.chinasoft.action.UserAction">
            <result name="success">/success.jsp</result>
            <result name="failure">/failure.jsp</result>
        </action>
    </package>
</struts>

---------------------------struts.xml

<!--
  ~ Hibernate, Relational Persistence for Idiomatic Java
  ~
  ~ Copyright (c) 2007, Red Hat Middleware LLC or third-party contributors as
  ~ indicated by the @author tags or express copyright attribution
  ~ statements applied by the authors. All third-party contributions are
  ~ distributed under license by Red Hat Middleware LLC.
  ~
  ~ This copyrighted material is made available to anyone wishing to use, modify,
  ~ copy, or redistribute it subject to the terms and conditions of the GNU
  ~ Lesser General Public License, as published by the Free Software Foundation.
  ~
  ~ This program is distributed in the hope that it will be useful,
  ~ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  ~ or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
  ~ for more details.
  ~
  ~ You should have received a copy of the GNU Lesser General Public License
  ~ along with this distribution; if not, write to:
  ~ Free Software Foundation, Inc.
  ~ 51 Franklin Street, Fifth Floor
  ~ Boston, MA  02110-1301  USA
  -->
<ehcache>

    <!-- Sets the path to the directory where cache .data files are created.

         If the path is a Java System Property it is replaced by
         its value in the running VM.

         The following properties are translated:
         user.home - User's home directory
         user.dir - User's current working directory
         java.io.tmpdir - Default temp file path -->
    <diskStore path="./target/tmp"/>


    <!--Default Cache configuration. These will applied to caches programmatically created through
        the CacheManager.

        The following attributes are required for defaultCache:

        maxInMemory       - Sets the maximum number of objects that will be created in memory
        eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
                            is never expired.
        timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
                            if the element is not eternal. Idle time is now - last accessed time
        timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
                            if the element is not eternal. TTL is now - creation time
        overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
                            has reached the maxInMemory limit.

        -->
    <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        overflowToDisk="true"
        />

    <!--Predefined caches.  Add your cache configuration settings here.
        If you do not have a configuration for your cache a WARNING will be issued when the
        CacheManager starts

        The following attributes are required for defaultCache:

        name              - Sets the name of the cache. This is used to identify the cache. It must be unique.
        maxInMemory       - Sets the maximum number of objects that will be created in memory
        eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
                            is never expired.
        timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
                            if the element is not eternal. Idle time is now - last accessed time
        timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
                            if the element is not eternal. TTL is now - creation time
        overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
                            has reached the maxInMemory limit.

        -->

    <!-- Sample cache named sampleCache1
        This cache contains a maximum in memory of 10000 elements, and will expire
        an element if it is idle for more than 5 minutes and lives for more than
        10 minutes.

        If there are more than 10000 elements it will overflow to the
        disk cache, which in this configuration will go to wherever java.io.tmp is
        defined on your system. On a standard Linux system this will be /tmp"
        -->
    <cache name="userCache"
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="300"
        timeToLiveSeconds="600"
        overflowToDisk="true"
        />

    <!-- Sample cache named sampleCache2
        This cache contains 1000 elements. Elements will always be held in memory.
        They are not expired. -->
    <cache name="studentCache"
        maxElementsInMemory="1000"
        eternal="true"
        timeToIdleSeconds="0"
        timeToLiveSeconds="0"
        overflowToDisk="false"
        /> -->

    <!-- Place configuration for your caches following -->

</ehcache>

-------------------------------ehcache.xml

------------------------

package com.chinasoft.action;

import java.util.List;

import org.hibernate.Cache;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.chinasoft.entity.User;
import com.chinasoft.service.IUserService;
import com.opensymphony.xwork2.ActionSupport;

@Component("userAction")
public class UserAction extends ActionSupport{

    private static final long serialVersionUID = 9160145984518262102L;
    
    @Autowired
    private SessionFactory    sessionFactory;
    
    @Autowired
    private IUserService userService;
    
    private User user;
    
    private List<User> userList;
    
    public String addUser(){
        boolean flag = userService.addUser(user);
        if(flag){
            userList = userService.findAllUser();
        }
        return flag==true?"success":"failure";
    }
    
    public String deleteUser(){
        boolean flag = userService.deleteUserById(user.getId());
        if(flag){
            userList = userService.findAllUser();
        }
        return flag==true?"success":"failure";
    }
    
    public String updateUser(){
        return userService.updateUser(user)==true?"success":"failure";
    }
    
    public String getAllUser(){
        userList = userService.findAllUser();
        if(null!=userList){
            user = userList.get(0);
        }
        return SUCCESS;
    }
    
    public String getUserById(){
        user = userService.findUserById(user.getId());
        return SUCCESS;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public List<User> getUserList() {
        return userList;
    }

    public void setUserList(List<User> userList) {
        this.userList = userList;
    }
}

--------------------------------

package com.chinasoft.dao;

import java.util.List;

import com.chinasoft.entity.Student;

public interface IStudentDao {
    public List<Student> findAllUser();
}
------------------------------------------

package com.chinasoft.dao;

import java.util.List;

import com.chinasoft.entity.User;

public interface IUserDao {

public User findUserById(int id);
    
    public List<User> findAllUser();
    
    public Integer addUser(User user);
    
    public Integer updateUser(User user);
    
    public Integer deleteUserById(int id);
}
--------------------------------------

package com.chinasoft.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.chinasoft.entity.Student;

@Repository("studentDao")
public class StudentDaoImpl implements IStudentDao{
    
    @Autowired
    private SessionFactory    sessionFactory;
    
    @Override
    public List<Student> findAllUser() {
        return sessionFactory.getCurrentSession().createQuery("from Student").list();
    }

}

---------------------------------

package com.chinasoft.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.chinasoft.entity.User;

@Repository("userDao")
public class UserDaoImpl implements  IUserDao {
    
    @Autowired
    private SessionFactory    sessionFactory;
    
    @Override
    public User findUserById(int id) {
        return (User) sessionFactory.getCurrentSession().get(User.class, id);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<User> findAllUser() {
        return (List<User>) sessionFactory.getCurrentSession().createQuery("from User").list();
    }

    @Override
    public Integer addUser(User user) {
        sessionFactory.getCurrentSession().save(user);
        if(user.getId()>0){
            return 1;
        }
        return 0;
    }

    @Override
    public Integer updateUser(User user) {
        sessionFactory.getCurrentSession().update(user);
        return 1;
    }

    @Override
    public Integer deleteUserById(int id) {
        User user = new User();
        user.setId(id);
        sessionFactory.getCurrentSession().delete(user);
        return 1;
    }
}

------------------------------------

package com.chinasoft.entity;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

@Entity
@Table(name="T_STUDENT")
public class Student implements Serializable {

    private static final long serialVersionUID = -5233839243374931521L;
    
    @Id
    @SequenceGenerator(name="student_id_sequence",sequenceName="T_STUDENT_SEQ",allocationSize=1)
    @GeneratedValue(generator="student_id_sequence",strategy=GenerationType.SEQUENCE)
    private Integer id;
    
    @Column(name="name",length=50,nullable=false)
    private String name;
    
    @Column(name="card",length=20,nullable=false)
    private Integer card;
    
    @Column(name="address",length=300,nullable=false)
    private String address;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getCard() {
        return card;
    }

    public void setCard(Integer card) {
        this.card = card;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

--------------------------

package com.chinasoft.entity;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

@Entity
@Table(name="T_USER")
public class User implements Serializable{
    
    private static final long serialVersionUID = -4971543883942732140L;
    
    @Id
    @SequenceGenerator(name="user_id_sequence",sequenceName="T_USER_SEQ",allocationSize=1)
    @GeneratedValue(generator="user_id_sequence",strategy=GenerationType.SEQUENCE)
    private Integer id;
    
    @Column(name="NAME",length=50,nullable=false)
    private String name;
    
    @Column(name="SEX",length=10,nullable=false)
    private Integer sex;
    
    @Column(name="MAILADDRESS")
    private String mailAddress;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    public String getMailAddress() {
        return mailAddress;
    }

    public void setMailAddress(String mailAddress) {
        this.mailAddress = mailAddress;
    }
}

-------------------------------

package com.chinasoft.service;

import java.util.List;

import com.chinasoft.entity.Student;

public interface IStudentService {
    
    public List<Student> findAllStudent();
}

------------------------------------

package com.chinasoft.service;

import java.util.List;

import com.chinasoft.entity.User;

public interface IUserService {
    
    public User findUserById(int id);
    
    public List<User> findAllUser();
    
    public boolean addUser(User user);
    
    public boolean updateUser(User user);
    
    public boolean deleteUserById(int id);
    
    public boolean updateAndDeleteTest();
}

-------------------------------------------------

package com.chinasoft.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.chinasoft.dao.IStudentDao;
import com.chinasoft.entity.Student;

@Service("studentService")
public class StudentServiceImpl implements IStudentService {
    
    @Autowired
    private IStudentDao studentDao;
    
    @Override
    @Cacheable(value="studentCache")
    public List<Student> findAllStudent() {
        return studentDao.findAllUser();
    }

}

------------------------------------------------

package com.chinasoft.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.chinasoft.dao.IUserDao;
import com.chinasoft.entity.User;

@Service("userService")
//@Cacheable("sampleCache1")
public class UserServiceImpl implements IUserService {
    
    @Autowired
    private IUserDao userDao;

    @Override
    @Cacheable(key="#id",value="userCache")
    public User findUserById(int id) {
        return userDao.findUserById(id);
    }

    @Override
    @Cacheable(value="userCache")
    public List<User> findAllUser() {
        return userDao.findAllUser();
    }
    
    /**
     * 设置allEntries为true,它会清除当前Cache中的所有entry
     */
    @Override
    @CacheEvict(value="userCache",allEntries=true)
    public boolean addUser(User user) {
        return userDao.addUser(user)>0?true:false;
    }

    @Override
    public boolean updateUser(User user) {
        return userDao.updateUser(user)>0?true:false;
    }

    @Override
    @CacheEvict(value="userCache",allEntries=true)
    public boolean deleteUserById(int id) {
        return userDao.deleteUserById(id)>0?true:false;
    }

    @Override
    @Transactional
    public boolean updateAndDeleteTest() {
        
        User user = new User();
        user.setId(84);
        user.setName("Jason.chen111");
        user.setSex(0);
        user.setMailAddress("Jason.chen111@163.com");
        userDao.updateUser(user);
        
        userDao.deleteUserById(85);
        return true;
    }
}

--------------------------------------------jdbc.properties

jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:orcl
jdbc.username=chinasoft
jdbc.password=root123


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值