您的位置:首页 > 编程语言 > Java开发

Spring 学习记录 6

2014-10-23 11:06 225 查看
上篇介绍了 Spring 中的 AOP。

这篇将介绍如何在 Spring 中使用 Hibernate。

看看最新的配置文件

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd        http://www.springframework.org/schema/context        http://www.springframework.org/schema/context/spring-context.xsd"> 
    <bean id="myDataSource"
          class="com.mchange.v2.c3p0.ComboPooledDataSource"
          destroy-method="close"
          >
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost/gt?characterEncoding=utf8"/>
        <property name="user" value="root"/>
        <property name="password" value="rrrjjj"/>
    </bean>

    <bean id="mySessionFactory"
          class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.current_session_context_class">thread</prop>
            </props>
        </property>
        <property name="packagesToScan" value="model"/>
    </bean>

    <context:component-scan base-package="ivo"/>

</beans>


首先要介绍 DataSource 数据源,我也不知道数据源是个什么玩意。

但 C3P0 的数据连接池是符合的实现。

然后在 SessionFactroy 的 dataSource 属性中,引用之前定义的 dataSource。

其实和 hibernate 原先的参数基本相同。

除了 packagesToScan 这个属性,

它表示不需要一个个声明实体类了,扫描包即可。

public static void main(String[] args) {

        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bmpw.xml");
        SessionFactory sessionFactory = (SessionFactory) applicationContext.getBean("mySessionFactory");
        Session session = sessionFactory.getCurrentSession();
        session.beginTransaction();
        session.saveOrUpdate(getLi());
        session.getTransaction().commit();
    }

    private static Husband getLi(){

        Husband husband = new Husband();
        husband.setObjectId(UUID.randomUUID().toString());
        husband.setName("Li");
        return husband;
    }


就是这样,记得把 hibernate require 和 c3p0 下的包都添加到依赖。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: