欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

7. Spring Hibernate 整合

程序员文章站 2022-06-09 12:51:47
...

XML配置

反向生成

cn.po

  • 实体类

package cn.po;

/**
 * Bank entity. @author MyEclipse Persistence Tools
 */

public class Bank implements java.io.Serializable {

	// Fields

	private Integer bid;
	private String uname;
	private Integer acount;

	// Constructors

	/** default constructor */
	public Bank() {
	}

	/** minimal constructor */
	public Bank(String uname) {
		this.uname = uname;
	}

	/** full constructor */
	public Bank(String uname, Integer acount) {
		this.uname = uname;
		this.acount = acount;
	}

	// Property accessors

	public Integer getBid() {
		return this.bid;
	}

	public void setBid(Integer bid) {
		this.bid = bid;
	}

	public String getUname() {
		return this.uname;
	}

	public void setUname(String uname) {
		this.uname = uname;
	}

	public Integer getAcount() {
		return this.acount;
	}

	public void setAcount(Integer acount) {
		this.acount = acount;
	}

}

  • 映射文件
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="cn.po.Bank" table="BANK" schema="BANK_DB">
        <id name="bid" type="java.lang.Integer">
            <column name="BID" precision="9" scale="0" />
            <generator class="increment" />
        </id>
        <property name="uname" type="java.lang.String">
            <column name="UNAME" length="50" not-null="true" />
        </property>
        <property name="acount" type="java.lang.Integer">
            <column name="ACOUNT" precision="9" scale="0" />
        </property>
    </class>
</hibernate-mapping>


cn.dao

  • 持久层业务
package cn.dao;

import java.util.List;
import org.hibernate.LockMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import cn.po.Bank;

/**
 * A data access object (DAO) providing persistence and search support for Bank
 * entities. Transaction control of the save(), update() and delete() operations
 * can directly support Spring container-managed transactions or they can be
 * augmented to handle user-managed Spring transactions. Each of these methods
 * provides additional information for how to configure it for the desired type
 * of transaction control.
 * 
 * @see cn.po.Bank
 * @author MyEclipse Persistence Tools
 */
public class BankDAO extends HibernateDaoSupport {
	private static final Logger log = LoggerFactory.getLogger(BankDAO.class);
	// property constants
	public static final String UNAME = "uname";
	public static final String ACOUNT = "acount";

	protected void initDao() {
		// do nothing
	}

	public void save(Bank transientInstance) {
		log.debug("saving Bank instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(Bank persistentInstance) {
		log.debug("deleting Bank instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public Bank findById(java.lang.Integer id) {
		log.debug("getting Bank instance with id: " + id);
		try {
			Bank instance = (Bank) getHibernateTemplate().get("cn.po.Bank", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(Bank instance) {
		log.debug("finding Bank instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: " + results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding Bank instance with property: " + propertyName + ", value: " + value);
		try {
			String queryString = "from Bank as model where model." + propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByUname(Object uname) {
		return findByProperty(UNAME, uname);
	}

	public List findByAcount(Object acount) {
		return findByProperty(ACOUNT, acount);
	}

	public List findAll() {
		log.debug("finding all Bank instances");
		try {
			String queryString = "from Bank";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public Bank merge(Bank detachedInstance) {
		log.debug("merging Bank instance");
		try {
			Bank result = (Bank) getHibernateTemplate().merge(detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(Bank instance) {
		log.debug("attaching dirty Bank instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(Bank instance) {
		log.debug("attaching clean Bank instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static BankDAO getFromApplicationContext(ApplicationContext ctx) {
		return (BankDAO) ctx.getBean("BankDAO");
	}
}

cn.biz

  • 逻辑业务
package cn.biz;

import cn.dao.BankDAO;
import cn.po.Bank;

public class BanBiz {
	private BankDAO bankdao;
	public void setBankdao(BankDAO bankdao) {
		this.bankdao = bankdao;
	}
	public void update(int[] bkid , Integer money){
		Bank bk1 = bankdao.findById(bkid[0]);
		System.out.println("查询1");
		Bank bk2 = bankdao.findById(bkid[1]);
		System.out.println("查询2");
		bk1.setAcount(bk1.getAcount()+money);
		System.out.println("运算1");
		bk2.setAcount(bk2.getAcount()-money);
		System.out.println("运算2");
		bankdao.merge(bk1);
		System.out.println("保存1");
		bankdao.merge(bk2);
		System.out.println("保存2");
	}

} 

  • 日志文件
package cn.biz;

public class banlog {
	public void log() {
		System.out.println("开始转账");
	}

	public void end() {
		System.out.println("转账结束");
	}

}



log4j.properties

  • 日志配置文件
log4j.properties 文件内容:具体需求课根据自己的意愿选择不同的权限


# Log4j properties
log4j.rootLogger=INFO, stdout


log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=INFO
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c,%L] - %m%n


#log4j.appender.logfile.encoding=UTF-8
#log4j.appender.logfile=org.apache.log4j.RollingFileAppender
#log4j.appender.logfile.File=${lms.root}/WEB-INF/logs/lms.log
#log4j.appender.logfile.MaxFileSize=512KB
# Keep three backup files.
#log4j.appender.logfile.MaxBackupIndex=3
# Pattern to output: date priority [category] - message
#log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
#log4j.appender.logfile.layout.ConversionPattern=%d %p [%c,%L] - %m%n


#设置为debug,可以看到更详细的信息


log4j.logger.org.hibernate=INFO
log4j.logger.org.springframework=INFO
log4j.logger.com.opensymphony.xwork2=INFO
uname=bank_db
passwd=java


log4j.logger.org.apache.struts2=INFO
proDataSource.properties

  • 数据库用户配置
uname=bank_db
passwd=java

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:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	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.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
	<!-- 引入数据库配置的属性文件 -->
	<context:property-placeholder location="proDataSource.properties" />
	<!-- 数据库连接配置 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="oracle.jdbc.OracleDriver" />
		<property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl" />
		<property name="username" value="${uname}" />
		<property name="password" value="${passwd}" />
		<!-- 连接池启动时的初始值 -->
		<property name="initialSize" value="1" />
		<!-- 连接池的最大值 -->
		<property name="maxActive" value="500" />
		<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
		<property name="maxIdle" value="2" />
		<!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
		<property name="minIdle" value="1"></property>
	</bean>
	<!-- sessionFactory 工厂 -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<!-- 设置数据源 -->
		<property name="dataSource">
			<ref bean="dataSource" />
		</property>
		<!-- hibernate设置 -->
		<property name="hibernateProperties">
			<props>
				<!-- 设置方言 -->
				<prop key="hibernate.dialect">
					org.hibernate.dialect.DerbyDialect
				</prop>
				<!-- 设置显示sql语句 -->
				<prop key="hibernate.show_sql">
					true
				</prop>
			</props>
		</property>
		<!-- 设置实体类映射 -->
		<property name="mappingResources">
			<list>
				<value>cn/po/Bank.hbm.xml</value>
			</list>
		</property>

	</bean>
	<!-- dao层 -->
	<bean id="BankDAO" class="cn.dao.BankDAO">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<!-- biz层 -->
	<bean id="BankBiz" class="cn.biz.BanBiz">
		<property name="bankdao" ref="BankDAO" />
	</bean>
	<!-- log层 -->
	<bean id="log" class="cn.biz.banlog">

	</bean>
	<!-- 创建事务管理器 -->
	<bean id="txmanager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<!-- 配置sessionFactory -->
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<!-- 配置事务 -->
	<tx:advice id="txAdvice" transaction-manager="txmanager">
		<tx:attributes>
			<!-- 指定事务隔离级别 -->
			<tx:method name="update" propagation="REQUIRED" />
		</tx:attributes>
	</tx:advice>
	<!-- 添加切点 -->
	<aop:config>
		<!-- 配置aop切点 -->
		<aop:pointcut expression="execution(* cn.biz.BanBiz.*(..))"
			id="bank_biz_aop" />
		<!-- 配置事务增强切面 -->
		<aop:advisor advice-ref="txAdvice" pointcut-ref="bank_biz_aop" />
		<!-- 配置方法增强切面 -->
		<aop:aspect ref="log">
			<!-- 配置切面通知类型 -->
			<!-- 前置通知 -->
			<aop:before method="log()" pointcut-ref="bank_biz_aop" />
			<!-- 后置通知 -->
			<aop:after method="end()" pointcut-ref="bank_biz_aop" />
		</aop:aspect>
	</aop:config>

</beans>


相关标签: 案例