Spring+hibernate 配置实例

转自:http://www.cnblogs.com/hongten/archive/2012/03/10/java_spring_hibernate.html

项目结构:

http://www.cnblogs.com/hongten/gallery/image/112469.html

使用的jar包:

hibernate核心安装包:
hibernate3.jar
lib\rquired\*.jar
lib\optional\encache-1.2.3.jar    (二级缓存)

lib\test\slf4j-log4j12.jar    (hibernate注解安装包)

如下图:

http://www.cnblogs.com/hongten/gallery/image/112470.html

spring安装包:
dist\spring.jar
dist\modules\spring-webmvc-struts.jar
lib\jakarta-commons\commons-loggng.jar
lib\jakarta-commons\commons-dbcp.jar
lib\jakarta-commons\commons-pool.jar
lib\cglib\cglib-nodep-2.1_3.jar
lib\j2ee\common-annotations.jar
lib\log4j-1.2.15.jar

如下图:

http://www.cnblogs.com/hongten/gallery/image/112471.html

/spring+hibernate/src/com/b510/domain/Person.java

 1 package com.b510.domain; 2  3 /** 4  * Person实体类 5  *  6  * @author Hongten 7  *  8  */ 9 10 public class Person implements java.io.Serializable {11 12     // Fields13 14     /**15      * 版本号16 */17     private static final long serialVersionUID = -47270870639923184L;18     /**19      * id号20 */21     private Integer id;22     /**23      * 姓名24 */25     private String name;26     /**27      * 年龄28 */29     private Integer age;30     /**31      * 性别32 */33     private String sex;34 35     // Constructors36 37     /** default constructor */38     public Person() {39     }40 41     /** minimal constructor */42     public Person(String name) {43         this.name = name;44     }45 46     /** full constructor */47     public Person(String name, Integer age, String sex) {48         this.name = name;49         this.age = age;50         this.sex = sex;51     }52 53     // Property accessors54 55     public Integer getId() {56         return this.id;57     }58 59     public void setId(Integer id) {60         this.id = id;61     }62 63     public String getName() {64         return this.name;65     }66 67     public void setName(String name) {68         this.name = name;69     }70 71     public Integer getAge() {72         return this.age;73     }74 75     public void setAge(Integer age) {76         this.age = age;77     }78 79     public String getSex() {80         return this.sex;81     }82 83     public void setSex(String sex) {84         this.sex = sex;85     }86 87 }

/spring+hibernate/src/com/b510/domain/Person.hbm.xml

 1 <?xml version="1.0" encoding="utf-8"?> 2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 3 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 4  5 <hibernate-mapping> 6     <class name="com.b510.domain.Person" table="person" catalog="spring"> 7         <id name="id" type="java.lang.Integer"> 8             <column name="id" /> 9             <generator class="increment" />10         </id>11         <property name="name" type="java.lang.String">12             <column name="name" length="20" not-null="true" />13         </property>14         <property name="age" type="java.lang.Integer">15             <column name="age" />16         </property>17         <property name="sex" type="java.lang.String">18             <column name="sex" length="2" />19         </property>20     </class>21 </hibernate-mapping>

/spring+hibernate/src/com/b510/service/PersonService.java

 1 package com.b510.service; 2  3 import java.util.List; 4  5 import com.b510.domain.Person; 6  7 /** 8  * PersonService服务层 9  * 10  * @author Hongten11  * 12  */13 public interface PersonService {14 15     /**16      * 保存Person17      * 18      * @param person19 */20     public abstract void save(Person person);21 22     /**23      * 更新Person24      * 25      * @param person26 */27     public abstract void update(Person person);28 29     /**30      * 获取Person31      * 32      * @param id33      * @return34 */35     public abstract Person getPerson(Integer id);36 37     /**38      * 获取所有Person39      * 40      * @return41 */42     public abstract List<Person> getPerson();43 44     /**45      * 删除指定id的Person46      * 47      * @param id48 */49     public abstract void delete(Integer id);50 51 }

/spring+hibernate/src/com/b510/service/impl/PersonServiceBean.java

 1 package com.b510.service.impl; 2  3 import java.util.List; 4  5 import javax.annotation.Resource; 6  7 import org.hibernate.SessionFactory; 8 import org.springframework.transaction.annotation.Propagation; 9 import org.springframework.transaction.annotation.Transactional;10 11 import com.b510.domain.Person;12 import com.b510.service.PersonService;13 14 /**15  * 使用注解方式进行事务管理16  * 17  * @author Hongten18  * 19  */20 @Transactional21 public class PersonServiceBean implements PersonService {22     /**23      * 通过bean.xml配置文件按名称sessionFactory注入属性sessionFactory,24      * 当sessionFactory注入成功后,我们可以得到Session对象25 */26     @Resource27     private SessionFactory sessionFactory;28 29     @Override30     public void delete(Integer id) {31         sessionFactory.getCurrentSession().delete(32                 sessionFactory.getCurrentSession().load(Person.class, id));33     }34 35     // 在查询的时候,不需要开启事务,并且指定为只读,这样可以提高查询效率36     @Override37     @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)38     public Person getPerson(Integer id) {39         return (Person) sessionFactory.getCurrentSession()40                 .get(Person.class, id);41     }42 43     // 在查询的时候,不需要开启事务,并且指定为只读,这样可以提高查询效率44     @Override45     @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)46     @SuppressWarnings("unchecked")47     public List<Person> getPerson() {48         return sessionFactory.getCurrentSession().createQuery("from Person")49                 .list();50 51     }52 53     @Override54     public void save(Person person) {55         sessionFactory.getCurrentSession().persist(person);56     }57 58     @Override59     public void update(Person person) {60         sessionFactory.getCurrentSession().merge(person);61     }62 }

/spring+hibernate/src/com/b510/test/PersonServiceBeanTest.java

 1 package com.b510.test; 2  3 import org.junit.BeforeClass; 4 import org.junit.Test; 5 import org.springframework.context.ApplicationContext; 6 import org.springframework.context.support.ClassPathXmlApplicationContext; 7  8 import com.b510.domain.Person; 9 import com.b510.service.PersonService;10 11 public class PersonServiceBeanTest {12     static PersonService personService;13 14     @BeforeClass15     public static void setUpBeforeClass() throws Exception {16 17         try {18             ApplicationContext act = new ClassPathXmlApplicationContext(19                     "bean.xml");20             personService = (PersonService) act.getBean("personService");21         } catch (Exception e) {22             e.printStackTrace();23         }24     }25 26     @Test27     public void testSave() {28         personService.save(new Person("hongten", 21, "男"));29     }30 31     @Test32     public void testUpdate() {33         Person person =personService.getPerson(2);34         person.setName("hanyuan");35         person.setAge(21);36         person.setSex("男");37         personService.update(person);38     }39 40     @Test41     public void testGetPersonInteger() {42         Person person = personService.getPerson(1);43         System.out.println(person.getId() + "  " + person.getName() + "  "44                 + person.getAge() + "  " + person.getSex());45     }46 47     @Test48     public void testGetPerson() {49         java.util.List<Person> list = personService.getPerson();50         System.out.println("*******************");51         for (Person person : list) {52             System.out.println(person.getId() + "  " + person.getName() + "  "53                     + person.getAge() + "  " + person.getSex());54         }55     }56 57     @Test58     public void testDelete() {59         personService.delete(1);60     }61 62 }

/spring+hibernate/src/bean.xml

 1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 4     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 5     xsi:schemaLocation="http://www.springframework.org/schema/beans 6            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 7            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd 8            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 9            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">10     <context:annotation-config />11 12     <!-- 读取jdbc.properties配置文件 -->13     <context:property-placeholder location="classpath:jdbc.properties" />14 15     <!-- 配置数据源 -->16     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"17         destroy-method="close">18         <property name="driverClassName" value="${driverClassName}" />19         <property name="url" value="${url}" />20         <property name="username" value="${username}" />21         <property name="password" value="${password}" />22         <!-- 连接池启动时的初始值 -->23         <property name="initialSize" value="${initialSize}" />24         <!-- 连接池的最大值 -->25         <property name="maxActive" value="${maxActive}" />26         <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->27         <property name="maxIdle" value="${maxIdle}" />28         <!--  最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->29         <property name="minIdle" value="${minIdle}" />30     </bean>31 32     <bean id="sessionFactory"33         class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">34         <!-- 配置SessionFactory所需的数据源,注入上面定义的dataSource -->35         <property name="dataSource" ref="dataSource" />36 37         <!-- mappingResources属性用来列出全部映射文件 -->38         <property name="mappingResources">39             <list>40                 <!-- 配置所有PO映射文件 -->41                 <value>com/b510/domain/Person.hbm.xml</value>42             </list>43         </property>44 45         <!-- 定义hibernate的SessionFactory的属性 -->46         <property name="hibernateProperties">47             <value>48                 hibernate.dialect=org.hibernate.dialect.MySQL5Dialect49                 hibernate.hbm2ddl.auto=update50                 hibernate.show_sql=true51                 hibernate.format_sql=true52                 hibernate.cache.use_second_level_cache=true53                 hibernate.cache.use_query_cache=false54                 hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider55             </value>56         </property>57     </bean>58 59     <!-- 配置Hibernate的局部事务管理器,使用HibernateTransactionManager类 -->60     <!-- 该类是PlatformTransactionManager接口对采用Hibernate的特定实现类 -->61     <bean id="txManager"62         class="org.springframework.orm.hibernate3.HibernateTransactionManager">63         <property name="sessionFactory" ref="sessionFactory" />64     </bean>65 66     <!-- 采用注解方式配置事务 -->67     <tx:annotation-driven transaction-manager="txManager" />68 69     <bean id="personService" class="com.b510.service.impl.PersonServiceBean"></bean>70 </beans>

这里我们可以重写占位符配置器:

那么/spring+hibernate/src/bean.xml的另外一种配置方式是:要知道,程序执行是完全相同的。

 1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 4     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 5     xsi:schemaLocation="http://www.springframework.org/schema/beans 6            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 7            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd 8            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 9            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">10     <context:annotation-config />11 12     <!-- 13     重写占位符配置器,读取jdbc.properties配置文件 14     这时候jdbc.properties配置文件的书写方式如下:15     dataSource.driverClassName=org.gjt.mm.mysql.Driver16     dataSource.url=jdbc\:mysql\://localhost\:3307/spring?useUnicode\=true&characterEncoding\=UTF-817     dataSource.username=root18     dataSource.password=root19     dataSource.initialSize=120     dataSource.maxActive=30021     dataSource.maxIdle=222     dataSource.minIdle=123     24     dataSource.driverClassName对于dataSource必须是在此xml配置文件中可以找到的bean,25     否则程序会出错。26     -->27     <context:property-override location="classpath:jdbc.properties" />28     <!-- 配置数据源 -->29     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"30         destroy-method="close">31     </bean>32 33     <bean id="sessionFactory"34         class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">35         <!-- 配置SessionFactory所需的数据源,注入上面定义的dataSource -->36         <property name="dataSource" ref="dataSource" />37 38         <!-- mappingResources属性用来列出全部映射文件 -->39         <property name="mappingResources">40             <list>41                 <!-- 配置所有PO映射文件 -->42                 <value>com/b510/domain/Person.hbm.xml</value>43             </list>44         </property>45 46         <!-- 定义hibernate的SessionFactory的属性 -->47         <property name="hibernateProperties">48             <value>49                 hibernate.dialect=org.hibernate.dialect.MySQL5Dialect50                 hibernate.hbm2ddl.auto=update51                 hibernate.show_sql=true52                 hibernate.format_sql=true53                 hibernate.cache.use_second_level_cache=true54                 hibernate.cache.use_query_cache=false55                 hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider56             </value>57         </property>58     </bean>59 60     <!-- 配置Hibernate的局部事务管理器,使用HibernateTransactionManager类 -->61     <!-- 该类是PlatformTransactionManager接口对采用Hibernate的特定实现类 -->62     <bean id="txManager"63         class="org.springframework.orm.hibernate3.HibernateTransactionManager">64         <property name="sessionFactory" ref="sessionFactory" />65     </bean>66 67     <!-- 采用注解方式配置事务 -->68     <tx:annotation-driven transaction-manager="txManager" />69 70     <bean id="personService" class="com.b510.service.impl.PersonServiceBean"></bean>71 </beans>

/spring+hibernate/src/jdbc.properties

1 driverClassName=org.gjt.mm.mysql.Driver2 url=jdbc\:mysql\://localhost\:3307/spring?useUnicode\=true&characterEncoding\=UTF-83 username=root4 password=root5 initialSize=16 maxActive=3007 maxIdle=28 minIdle=1

运行结果:

 1 log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext). 2 log4j:WARN Please initialize the log4j system properly. 3 Hibernate:  4     select 5         max(id)  6     from 7         person 8 Hibernate:  9     insert 10     into11         spring.person12         (name, age, sex, id) 13     values14         (?, ?, ?, ?)15 Hibernate: 16     select17         person0_.id as id0_0_,18         person0_.name as name0_0_,19         person0_.age as age0_0_,20         person0_.sex as sex0_0_ 21     from22         spring.person person0_ 23     where24         person0_.id=?25 Hibernate: 26     select27         person0_.id as id0_0_,28         person0_.name as name0_0_,29         person0_.age as age0_0_,30         person0_.sex as sex0_0_ 31     from32         spring.person person0_ 33     where34         person0_.id=?35 Hibernate: 36     select37         person0_.id as id0_,38         person0_.name as name0_,39         person0_.age as age0_,40         person0_.sex as sex0_ 41     from42         spring.person person0_43 *******************44 2  hanyuan  21  男45 3  hongten  21  男46 Hibernate: 47     select48         person0_.id as id0_0_,49         person0_.name as name0_0_,50         person0_.age as age0_0_,51         person0_.sex as sex0_0_ 52     from53         spring.person person0_ 54     where55         person0_.id=?

haibernate 配置资源的XML配置方式:

<?xml version=‘1.0‘ encoding=‘utf-8‘?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>

        <property name="hibernate.connection.url" >jdbc:mysql://localhost/EducationCRM?useUnicode=true&characterEncoding=utf-8</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>

        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property><!--方言 -->
        <property name="hibernate.show_sql">false</property><!--是否打印SQL语句 -->
        <property name="hibernate.format_sql">true</property><!--在控制台和log4j 优化打印的语句 -->
        <property name="hibernate.hbm2ddl.auto">update</property><!--自动跟新 -->

        <property name="sessionInfoName">sessionInfo</property>
        <property name="uploadFieldName">filedata</property>
        <property name="uploadFileMaxSize">20971520</property>
        <property name="uploadFileExts">txt,rar,zip,doc,docx,xls,xlsx,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid</property>
        <property name="uploadDirectory">attached</property>

<!-- 配置mapping示例 -->
        <mapping class="com.educationcrm.dao.BuyVipCard"/>

    </session-factory>
</hibernate-configuration>

  

时间: 2024-11-17 04:29:19

Spring+hibernate 配置实例的相关文章

Spring hibernate配置中mappingLocations、mappingDirecto

mappingLocations.mappingDirectoryLocations与mappingJarLocations 区别 由于spring对hibernate配置文件hibernate.cfg.xml的集成相当好, 所以,在项目中我一直使用spring的org.springframework.orm.hibernate.LocalSessionFactoryBean来取代hibernate.cfg.xml文件的功能 LocalSessionFactoryBean有好几个属性用来查找hi

Spring Security 配置实例

这几天学习了一下Spring Security3.1,从官网下载了Spring Security3.1版别进行操练,通过屡次测验才摸清了其间的一些原理.自己不才,希望能协助大家.还有,这次我第2次写博客啊,文体不是很行.希望能让观看者不发生疲乏的感受,我现已心满意足了.一.数据库构造     先来看一下数据库构造,选用的是根据人物-资本-用户的权限办理规划.(MySql数据库)    为了节约华章,只对对比重要的字段进行注释.    1.用户表Users    CREATE TABLE `use

spring hibernate配置切换数据源,实现读写分离

spring的配置如下 <!-- 主数据源--> <bean id="masterDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <prope

Spring+Hibernate配置多数据源

配置说明 在实际应用中,经常会用到读写分离,这里就这种情况进行Spring+Hibernate的多数据源配置.此处的配置只是让读的方法操作一个数据库,写的方法操作另外一个数据库. 注:我这里的配置JDBC连接是放在properties文件中的,当然你也可以直接写在ApplicationCpntext.xml文件中或其他的配置方式. 配置步骤 1.配置多数据库 在jdbc.Properties中,配置两个数据库的连接.在此处的例子如下(我这里都是使用的MySql,如果要使用其他的请更换驱动): [

spring +spring+ hibernate配置1

这种配置方式是将Spring .SpringMVC.Hibernate三个模块分开配置,交叉引用!hibernate连接配置使用.properties文件 web.xml配置 <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.

springmvc+spring+hibernate配置过程

开发工具:eclipse 项目目录: jar包: web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5" xsi:s

16.spring+hibernate简单实例

1.概念 Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个全自动的orm框架,hibernate可以自动生成SQL语句,自动执行,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库. hibernate对象: ① configuration (Configuration 类的实例首先定位映射文档的位置,读取这些配置,然后创建一个SessionFactory对象) ②sessionFactory(一个

Spring事务配置实例

事务 一个使用 MyBatis-spring 的主要原因是它允许MyBatis 参与到 Spring 的事务管理中.而 不是给 MyBatis 创建一个新的特定的事务管理器,MyBatis-Spring 利用了存在于Spring 中的 DataSourceTransactionManager. 一旦 Spring 的PlatformTransactionManager 配置好了,你可以在 Spring 中以你通常的做 法来配置事务.@Transactional 注解和AOP(Aspect-Ori

Spring + Quartz配置实例

Spring为创建Quartz的Scheduler.Trigger和JobDetail提供了便利的FactoryBean类,以便能够在Spring 容器中享受注入的好处.此外Spring还提供了一些便利工具类直接将Spring中的Bean包装成合法的任务.Spring进一步降低了使用Quartz的难度,能以更具Spring风格的方式使用Quartz.概括来说它提供了两方面的支持:     1)为Quartz的重要组件类提供更具Bean风格的扩展类:     2)提供创建Scheduler的Bea