zoukankan      html  css  js  c++  java
  • spring4 hibernate4 transaction

    http://www.cnblogs.com/leiOOlei/p/3727859.html

    http://www.cnblogs.com/GarfieldTom/p/3422574.html

    http://www.cnblogs.com/xusir/p/4156575.html

    关于spring和hibernate的使用以及特征等等,在此不再啰嗦,相信大家也都知道,或者去搜索一下即可。

    本篇博文的内容主要是我最近整理的关于spring4.x 和 hibernate 4.x 相关配置和使用方式,当然spring3.x以及hibernate4.x也可以借鉴。

    首先是配置文件 web.xml 增加以下代码即可

    <!-- 加载spring相关的配置文件 -->
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:/applicationContext.xml</param-value>
      </context-param>
      
      <!-- 启用spring监听 -->
      <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>

    然后建立 applicationContext.xml 文件 ,src下。 文件内容如下,注释我尽量写的很详细

    <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns="http://www.springframework.org/schema/beans" 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:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p"
      xsi:schemaLocation="http://www.springframework.org/schema/beans 
         http://www.springframework.org/schema/beans/spring-beans-4.0.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
         http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd">
      <!-- 引入properties文件 -->
      <context:property-placeholder location="classpath*:/appConfig.properties" />
      <!-- 定义数据库连接池数据源bean destroy-method="close"的作用是当数据库连接不使用的时候,就把该连接重新放到数据池中,方便下次使用调用 -->
      <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close">
        <!-- 设置JDBC驱动名称 -->
        <property name="driverClass" value="${jdbc.driver}" />
        <!-- 设置JDBC连接URL -->
        <property name="jdbcUrl" value="${jdbc.url}" />
        <!-- 设置数据库用户名 -->
        <property name="user" value="${jdbc.username}" />
        <!-- 设置数据库密码 -->
        <property name="password" value="${jdbc.password}" />
        <!-- 设置连接池初始值 -->
        <property name="initialPoolSize" value="5" />
      </bean>
    
      <!-- 配置sessionFactory -->
      <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <!-- 数据源 -->
        <property name="dataSource" ref="dataSource" />
    
        <!-- hibernate的相关属性配置 -->
        <property name="hibernateProperties">
          <value>
            <!-- 设置数据库方言 -->
            hibernate.dialect=org.hibernate.dialect.MySQLDialect
            <!-- 设置自动创建|更新|验证数据库表结构 -->
            hibernate.hbm2ddl.auto=update
            <!-- 是否在控制台显示sql -->
            hibernate.show_sql=true
            <!-- 是否格式化sql,优化显示 -->
            hibernate.format_sql=true
            <!-- 是否开启二级缓存 -->
            hibernate.cache.use_second_level_cache=false
            <!-- 是否开启查询缓存 -->
            hibernate.cache.use_query_cache=false
            <!-- 数据库批量查询最大数 -->
            hibernate.jdbc.fetch_size=50
            <!-- 数据库批量更新、添加、删除操作最大数 -->
            hibernate.jdbc.batch_size=50
            <!-- 是否自动提交事务 -->
            hibernate.connection.autocommit=true
            <!-- 指定hibernate在何时释放JDBC连接 -->
            hibernate.connection.release_mode=auto
            <!-- 创建session方式 hibernate4.x 的方式 -->
            hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
            <!-- javax.persistence.validation.mode默认情况下是auto的,就是说如果不设置的话它是会自动去你的classpath下面找一个bean-validation**包 
              所以把它设置为none即可 -->
            javax.persistence.validation.mode=none
          </value>
        </property>
        <!-- 自动扫描实体对象 tdxy.bean的包结构中存放实体类 -->
        <property name="packagesToScan" value="tdxy.bean" />
      </bean>
      <!-- 定义事务管理 -->
      <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
      </bean>
      
      <!-- 定义 Autowired  自动注入 bean -->
      <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> 
      
      <!-- 扫描有注解的文件  base-package 包路径 -->
      <context:component-scan base-package="tdxy"/>
      
      <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
          <!-- 事务执行方式
            REQUIRED:指定当前方法必需在事务环境中运行,
            如果当前有事务环境就加入当前正在执行的事务环境,
            如果当前没有事务,就新建一个事务。
            这是默认值。 
           -->
          <tx:method name="create*" propagation="REQUIRED" />
          <tx:method name="save*" propagation="REQUIRED" />
          <tx:method name="add*" propagation="REQUIRED" />
          <tx:method name="update*" propagation="REQUIRED" />
          <tx:method name="remove*" propagation="REQUIRED" />
          <tx:method name="del*" propagation="REQUIRED" />
          <tx:method name="import*" propagation="REQUIRED" />
          <!-- 
            指定当前方法以非事务方式执行操作,如果当前存在事务,就把当前事务挂起,等我以非事务的状态运行完,再继续原来的事务。 
            查询定义即可
            read-only="true"  表示只读
           -->
          <tx:method name="*" propagation="NOT_SUPPORTED" read-only="true" />
        </tx:attributes>
      </tx:advice>
    
      <!-- 定义切面,在 * tdxy.*.service.*ServiceImpl.*(..) 中执行有关的hibernate session的事务操作 -->
      <aop:config>
        <aop:pointcut id="serviceOperation" expression="execution(* tdxy.*.service.*Service.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />
      </aop:config>
      
    </beans>

     applicationContext.xml 文件引用了一个properties文件 ,该文件也在src下,appConfig.properties 内容可以自己定义

    ########################数据库连接信息#############
    jdbc.username = root
    jdbc.password = admin
    jdbc.url = jdbc:mysql://localhost:3306/tdxy?useUnicode=true&characterEncoding=UTF-8
    jdbc.driver = com.mysql.jdbc.Driver

    自己写了一个test用的basedao 

    package tdxy.dao;
    
    import java.util.List;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Repository;
    
    /**
     * 
     * @Title: BaseDao.java
     * @Package tdxy.dao
     * @Description: TODO(baseDao 数据库操作实现类)
     * @author dapeng
     * @date 2014年5月7日 下午5:09:22
     * @version V1.0
     */
    @Repository
    public class BaseDao {
    
        /**
         * Autowired 自动装配 相当于get() set()
         */
        @Autowired
        protected SessionFactory sessionFactory;
    
        /**
         * gerCurrentSession 会自动关闭session,使用的是当前的session事务
         * 
         * @return
         */
        public Session getSession() {
            return sessionFactory.getCurrentSession();
        }
    
        /**
         * openSession 需要手动关闭session 意思是打开一个新的session
         * 
         * @return
         */
        public Session getNewSession() {
            return sessionFactory.openSession();
        }
    
        public void flush() {
            getSession().flush();
        }
    
        public void clear() {
            getSession().clear();
        }
    
        /**
         * 根据 id 查询信息
         * 
         * @param id
         * @return
         */
        @SuppressWarnings("rawtypes")
        public Object load(Class c, String id) {
            Session session = getSession();
            return session.get(c, id);
        }
    
        /**
         * 获取所有信息
         * 
         * @param c 
         *        
         * @return
         */
        @SuppressWarnings({ "rawtypes" })
        public List getAllList(Class c) {
            String hql = "from " + c.getName();
            Session session = getSession();
            return session.createQuery(hql).list();
        }
    
        /**
         * 获取总数量
         * 
         * @param c
         * @return
         */
        @SuppressWarnings("rawtypes")
        public Long getTotalCount(Class c) {
            Session session = getNewSession();
            String hql = "select count(*) from " + c.getName();
            Long count = (Long) session.createQuery(hql).uniqueResult();
            session.close();
            return count != null ? count.longValue() : 0;
        }
    
        /**
         * 保存
         * 
         * @param bean 
         *            
         */
        public void save(Object bean) {
            try {
                Session session = getNewSession();
                session.save(bean);
                session.flush();
                session.clear();
                session.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        /**
         * 更新
         * 
         * @param bean 
         *            
         */
        public void update(Object bean) {
            Session session = getNewSession();
            session.update(bean);
            session.flush();
            session.clear();
            session.close();
        }
    
        /**
         * 删除
         * 
         * @param bean 
         *            
         */
        public void delete(Object bean) {
            Session session = getNewSession();
            session.delete(bean);
            session.flush();
            session.clear();
            session.close();
        }
    
        /**
         * 根据ID删除
         * 
         * @param c 类
         *            
         * @param id ID
         *            
         */
        @SuppressWarnings({ "rawtypes" })
        public void delete(Class c, String id) {
            Session session = getNewSession();
            Object obj = session.get(c, id);
            session.delete(obj);
            flush();
            clear();
        }
    
        /**
         * 批量删除
         * 
         * @param c 类
         *            
         * @param ids ID 集合
         *            
         */
        @SuppressWarnings({ "rawtypes" })
        public void delete(Class c, String[] ids) {
            for (String id : ids) {
                Object obj = getSession().get(c, id);
                if (obj != null) {
                    getSession().delete(obj);
                }
            }
        }
    
    }

    不知大家有没有注意 applicationContext.xml 这样一句代码

    <!-- 设置自动创建|更新|验证数据库表结构 -->
        hibernate.hbm2ddl.auto=update

    这个意思是 只要在实体bean指定了entity,那么在数据库会自动创建对应的表和表结构

    test用的一个实体bean

    package tdxy.bean;
    
    import java.io.Serializable;
    
    import javax.persistence.Entity;
    import javax.persistence.Id;
    
    /**
     * 
     * @ClassName: UserInfoBean
     * @Description: TODO(用户信息类)
     * @author dapeng
     * @date 2014年5月7日 上午12:13:44
     * @version V1.0
     * 
     */
    @Entity
    public class UserInfoBean implements Serializable {
    
      private static final long serialVersionUID = 7280747949998651159L;
    
      @Id
      private String id;
      /**
       * 昵称
       */
      private String nickName;
      private String pwd;
      /**
       * 等级
       * 
       */
      private String level;
    
      /**
       * 经验值
       */
      private String emValue;
      /**
       * 性别(0 男 1女)
       */
      private String sex;
      private String birthday;
      private String qq;
      private String email;
      /**
       * 头像
       */
      private String img;
      /**
       * 所在地
       */
      private String address;
      /**
       * 签名
       */
      private String qmd;
    
      public String getId() {
        return id;
      }
    
      public void setId(String id) {
        this.id = id;
      }
    
      public String getNickName() {
        return nickName;
      }
    
      public void setNickName(String nickName) {
        this.nickName = nickName;
      }
    
      public String getPwd() {
        return pwd;
      }
    
      public void setPwd(String pwd) {
        this.pwd = pwd;
      }
    
      public String getLevel() {
        return level;
      }
    
      public void setLevel(String level) {
        this.level = level;
      }
    
      public String getEmValue() {
        return emValue;
      }
    
      public void setEmValue(String emValue) {
        this.emValue = emValue;
      }
    
      public String getSex() {
        return sex;
      }
    
      public void setSex(String sex) {
        this.sex = sex;
      }
    
      public String getBirthday() {
        return birthday;
      }
    
      public void setBirthday(String birthday) {
        this.birthday = birthday;
      }
    
      public String getQq() {
        return qq;
      }
    
      public void setQq(String qq) {
        this.qq = qq;
      }
    
      public String getEmail() {
        return email;
      }
    
      public void setEmail(String email) {
        this.email = email;
      }
    
      public String getImg() {
        return img;
      }
    
      public void setImg(String img) {
        this.img = img;
      }
    
      public String getAddress() {
        return address;
      }
    
      public void setAddress(String address) {
        this.address = address;
      }
    
      public String getQmd() {
        return qmd;
      }
    
      public void setQmd(String qmd) {
        this.qmd = qmd;
      }
    
    }

    当应用成功启动之后,数据库会出现表和结构,即刚才定义的bean是一样的,大家可以自己查看一下即可。

    以下是test的Service

    package tdxy.user.service;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import tdxy.bean.UserInfoBean;
    import tdxy.dao.BaseDao;
    import tdxy.util.TdxyUtil;
    
    @Service
    public class UserInfoService {
    
      @Autowired
      private BaseDao baseDao;
    
      public UserInfoBean queryUserInfoById(String id) {
        return (UserInfoBean) baseDao.load(UserInfoBean.class, id);
      }
    
      public void addUserInfo(UserInfoBean userInfo) {
        try {
          userInfo.setId(TdxyUtil.getId());
          userInfo.setAddress("32132");
          baseDao.save(userInfo);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
  • 相关阅读:
    ios修改了coredata数据结构后,更新安装会闪退
    iOS开发系列--UITableView全面解析
    iOS七种手势
    iOS 手势操作:拖动、捏合、旋转、点按、长按、轻扫、自定义
    iOS学习必须了解的七大手势
    iOS中respondsToSelector与conformsToProtocol的相关理解和使用
    iOS-MBProgressHUD使用
    ios学习--第三方框架-MBProgressHUD以及扩展
    Problem 2169 shadow
    測试加入多级文件夹篇
  • 原文地址:https://www.cnblogs.com/zouhao510/p/5554853.html
Copyright © 2011-2022 走看看