`
robinsoncrusoe
  • 浏览: 748889 次
  • 性别: Icon_minigender_2
  • 来自: 深圳
社区版块
存档分类
最新评论

Spring和Hibernate整合开发

    博客分类:
  • J2EE
阅读更多
想的很复杂,用起来就那么回事.

怎么回事呢???

就是把hibernate的配置

dataSource    ----org.apache.commons.dbcp.BasicDataSource

sessionFactory  -----org.springframework.orm.hibernate3.LocalSessionFactoryBean

交给Spring去管理.

spring再管理自己的事务,bean等.

配置好spring,加入jar文件,

加入hibernate的jar文件.

加入数据库jar.







先看看配置文件,强烈建议复制,手动写我就出错了.最后还是复制别人现成的.

注解先要找开哦.

<?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">

       <context:annotation-config/>

     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">

        <property name="driverClassName" value="org.gjt.mm.mysql.Driver"/>

        <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=UTF-8"/>

        <property name="username" value="root"/>

        <property name="password" value="ff"/>

         <!-- 连接池启动时的初始值 -->

        <property name="initialSize" value="2"/>

        <!-- 连接池的最大值 -->

        <property name="maxActive" value="100"/>

        <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->

        <property name="maxIdle" value="2"/>

        <!--  最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->

        <property name="minIdle" value="1"/>

     </bean>

     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

         <property name="dataSource" ref="dataSource"/>

        <property name="mappingResources">

           <list>

             <value>com/liyu/bean/Person.hbm.xml</value>

           </list>

        </property>

         <property name="hibernateProperties">

           <value>

               hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

               hibernate.hbm2ddl.auto=update

               hibernate.show_sql=false

               hibernate.format_sql=false

               hibernate.cache.use_second_level_cache=true

                 hibernate.cache.use_query_cache=false

            hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider

             </value>

         </property>

    </bean>

    <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">

        <property name="sessionFactory" ref="sessionFactory"/>

    </bean>

    <tx:annotation-driven transaction-manager="txManager"/>

    <bean id="personService" class="com.liyu.service.impl.PersonServiceBean"/>

</beans>

再写那个Person bean文件PO,映射文件,这是基本的,写不出来,就不用看了.

再写那个服务类的接口,这个也是每个类公用的,无难度,飞过.

重点是那个接口的实现类了.PersonServiceBean

package com.liyu.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;

import org.springframework.transaction.annotation.Propagation;

import org.springframework.transaction.annotation.Transactional;

import com.liyu.bean.Person;

import com.liyu.service.PersonService;

@Transactional

public class PersonServiceBean implements PersonService {

    @Resource private SessionFactory sessionFactory;

    public void delete(Integer personid) {

       sessionFactory.getCurrentSession().delete(

              sessionFactory.getCurrentSession().load(Person.class, personid));

    }

    @Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)

    public Person getPerson(Integer personid) {

       return (Person)sessionFactory.getCurrentSession().get(Person.class, personid);

    }

    @Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)

    @SuppressWarnings("unchecked")

    public List<Person> getPersons() {

       return sessionFactory.getCurrentSession().createQuery("from Person").list();

    }

    public void save(Person person) {

       sessionFactory.getCurrentSession().persist(person);

    }

    public void update(Person person) {

       sessionFactory.getCurrentSession().merge(person);

    }

看看测试文件:

package com.liyu.test;

import java.util.List;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.liyu.bean.Person;

import com.liyu.service.PersonService;

public class SshTest {

    public static void main(String[] args) {

       ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");

       PersonService ps = (PersonService)applicationContext.getBean("personService");

       //增加一条记录

       //ps.save(new Person("wang da"));

       //查找一条记录

       //Person p=ps.getPerson(7);

       //System.out.println(p.getName());

       //p.setName("FFFF3");

       //更新记录

       //ps.update(p);

       //p=ps.getPerson(2);

       //System.out.println(p.getName());

       //删除记录

       //ps.delete(6);

       List<Person> list=ps.getPersons();

       for(Person p:list){

           System.out.println(p.getName());

       }

    }

运行的结果:

2010-6-17 14:54:34 org.springframework.context.support.AbstractApplicationContext prepareRefresh

信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@18ee9d6: display name [org.springframework.context.support.ClassPathXmlApplicationContext@18ee9d6]; startup date [Thu Jun 17 14:54:34 CST 2010]; root of context hierarchy

2010-6-17 14:54:34 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions

信息: Loading XML bean definitions from class path resource [beans.xml]

2010-6-17 14:54:35 org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory

信息: Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext@18ee9d6]: org.springframework.beans.factory.support.DefaultListableBeanFactory@18a49e0

2010-6-17 14:54:35 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons

信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@18a49e0: defining beans [org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,dataSource,sessionFactory,txManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,personService]; root of factory hierarchy

2010-6-17 14:54:35 org.hibernate.cfg.Environment <clinit>

信息: Hibernate 3.2.6

2010-6-17 14:54:35 org.hibernate.cfg.Environment <clinit>

信息: hibernate.properties not found

2010-6-17 14:54:35 org.hibernate.cfg.Environment buildBytecodeProvider

信息: Bytecode provider name : cglib

2010-6-17 14:54:35 org.hibernate.cfg.Environment <clinit>

信息: using JDK 1.4 java.sql.Timestamp handling

2010-6-17 14:54:35 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues

信息: Mapping class: com.liyu.bean.Person -> person

2010-6-17 14:54:35 org.springframework.orm.hibernate3.LocalSessionFactoryBean buildSessionFactory

信息: Building new Hibernate SessionFactory

2010-6-17 14:54:35 org.hibernate.connection.ConnectionProviderFactory newConnectionProvider

信息: Initializing connection provider: org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider

2010-6-17 14:54:35 org.hibernate.cfg.SettingsFactory buildSettings

信息: RDBMS: MySQL, version: 5.1.42-community

2010-6-17 14:54:35 org.hibernate.cfg.SettingsFactory buildSettings

信息: JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.1.7 ( Revision: ${svn.Revision} )

2010-6-17 14:54:35 org.hibernate.dialect.Dialect <init>

信息: Using dialect: org.hibernate.dialect.MySQL5Dialect

2010-6-17 14:54:35 org.hibernate.transaction.TransactionFactoryFactory buildTransactionFactory

信息: Transaction strategy: org.springframework.orm.hibernate3.SpringTransactionFactory

2010-6-17 14:54:35 org.hibernate.transaction.TransactionManagerLookupFactory getTransactionManagerLookup

信息: No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)

2010-6-17 14:54:35 org.hibernate.cfg.SettingsFactory buildSettings

信息: Automatic flush during beforeCompletion(): disabled

2010-6-17 14:54:35 org.hibernate.cfg.SettingsFactory buildSettings

信息: Automatic session close at end of transaction: disabled

2010-6-17 14:54:35 org.hibernate.cfg.SettingsFactory buildSettings

信息: JDBC batch size: 15

2010-6-17 14:54:35 org.hibernate.cfg.SettingsFactory buildSettings

信息: JDBC batch updates for versioned data: disabled

2010-6-17 14:54:35 org.hibernate.cfg.SettingsFactory buildSettings

信息: Scrollable result sets: enabled

2010-6-17 14:54:35 org.hibernate.cfg.SettingsFactory buildSettings

信息: JDBC3 getGeneratedKeys(): enabled

2010-6-17 14:54:35 org.hibernate.cfg.SettingsFactory buildSettings

信息: Connection release mode: auto

2010-6-17 14:54:35 org.hibernate.cfg.SettingsFactory buildSettings

信息: Maximum outer join fetch depth: 2

2010-6-17 14:54:35 org.hibernate.cfg.SettingsFactory buildSettings

信息: Default batch fetch size: 1

2010-6-17 14:54:35 org.hibernate.cfg.SettingsFactory buildSettings

信息: Generate SQL with comments: disabled

2010-6-17 14:54:35 org.hibernate.cfg.SettingsFactory buildSettings

信息: Order SQL updates by primary key: disabled

2010-6-17 14:54:35 org.hibernate.cfg.SettingsFactory buildSettings

信息: Order SQL inserts for batching: disabled

2010-6-17 14:54:35 org.hibernate.cfg.SettingsFactory createQueryTranslatorFactory

信息: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory

2010-6-17 14:54:35 org.hibernate.hql.ast.ASTQueryTranslatorFactory <init>

信息: Using ASTQueryTranslatorFactory

2010-6-17 14:54:35 org.hibernate.cfg.SettingsFactory buildSettings

信息: Query language substitutions: {}

2010-6-17 14:54:35 org.hibernate.cfg.SettingsFactory buildSettings

信息: JPA-QL strict compliance: disabled

2010-6-17 14:54:35 org.hibernate.cfg.SettingsFactory buildSettings

信息: Second-level cache: enabled

2010-6-17 14:54:35 org.hibernate.cfg.SettingsFactory buildSettings

信息: Query cache: disabled

2010-6-17 14:54:35 org.hibernate.cfg.SettingsFactory createCacheProvider

信息: Cache provider: org.hibernate.cache.EhCacheProvider

2010-6-17 14:54:35 org.hibernate.cfg.SettingsFactory buildSettings

信息: Optimize cache for minimal puts: disabled

2010-6-17 14:54:35 org.hibernate.cfg.SettingsFactory buildSettings

信息: Structured second-level cache entries: disabled

2010-6-17 14:54:35 org.hibernate.cfg.SettingsFactory buildSettings

信息: Statistics: disabled

2010-6-17 14:54:35 org.hibernate.cfg.SettingsFactory buildSettings

信息: Deleted entity synthetic identifier rollback: disabled

2010-6-17 14:54:35 org.hibernate.cfg.SettingsFactory buildSettings

信息: Default entity-mode: pojo

2010-6-17 14:54:35 org.hibernate.cfg.SettingsFactory buildSettings

信息: Named query checking : enabled

2010-6-17 14:54:36 org.hibernate.impl.SessionFactoryImpl <init>

信息: building session factory

2010-6-17 14:54:36 net.sf.ehcache.config.ConfigurationFactory parseConfiguration

警告: No configuration found. Configuring ehcache from ehcache-failsafe.xml  found in the classpath: jar:file:/E:/java/SSH/WebRoot/WEB-INF/lib/ehcache-1.2.3.jar!/ehcache-failsafe.xml

2010-6-17 14:54:36 org.hibernate.cache.EhCacheProvider buildCache

警告: Could not find configuration [cn.itcast.bean.Person]; using defaults.

2010-6-17 14:54:36 org.hibernate.impl.SessionFactoryObjectFactory addInstance

信息: Not binding factory to JNDI, no JNDI name configured

2010-6-17 14:54:36 org.hibernate.tool.hbm2ddl.SchemaUpdate execute

信息: Running hbm2ddl schema update

2010-6-17 14:54:36 org.hibernate.tool.hbm2ddl.SchemaUpdate execute

信息: fetching database metadata

2010-6-17 14:54:36 org.hibernate.tool.hbm2ddl.SchemaUpdate execute

信息: updating schema

2010-6-17 14:54:36 org.hibernate.tool.hbm2ddl.TableMetadata <init>

信息: table found: test.person

2010-6-17 14:54:36 org.hibernate.tool.hbm2ddl.TableMetadata <init>

信息: columns: [id, name]

2010-6-17 14:54:36 org.hibernate.tool.hbm2ddl.TableMetadata <init>

信息: foreign keys: []

2010-6-17 14:54:36 org.hibernate.tool.hbm2ddl.TableMetadata <init>

信息: indexes: [primary]

2010-6-17 14:54:36 org.hibernate.tool.hbm2ddl.SchemaUpdate execute

信息: schema update complete

2010-6-17 14:54:36 org.springframework.orm.hibernate3.HibernateTransactionManager afterPropertiesSet

信息: Using DataSource [org.apache.commons.dbcp.BasicDataSource@1955970] of Hibernate SessionFactory for HibernateTransactionManager

FFFF1

xxx05

xxx06

FFFF3
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics