在Spring里使用Hibernate

在Spring里使用Hibernate

  在Hibernate配置文件中一般会定义3个方面的信息:数据源、对象关联映射文件以及Hibernate控制属性信息。在Hibernate中,可以使用一个配置文件创建一个SessionFactory实例,在Spring中,可以利用

LocalSessionFactoryBean指定一个Hibernate来达到同样的目的。

1
2
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"
P:configLocation="classpath:hibernate.cfg,xml"/>

  如有多个配置文件,可用逗号隔开。LocalSessionFactoryBean将利用Hibernate配置文件创建一个

SessionFactory代理对象,以便和Spring的事务管理机制配合工作,当数据访问代码使用SessionFactory时,可以获得线程绑定的Session,不管工作于本地还是全局事务,都能正确参与到当前的Spring事务管理中。

Spring风格的配置

  Spring可以对ORM技术提供统一的数据管理机制,可以在Spring容器中定义数据源、指定映射文件、设置Hibernate控制属性等信息,完成集成组装的工作,完全抛开了hibernate.cfg.xml配置文件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?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:p="http://www.springframework.org/schema/p"
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">
<!--JDBC配置信息-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--配置数据源-->
<bean id="dataSoruce" class="org.apache.commons.dbcp2.BasicDataSource"
destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}"/>

<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"
p:dataSource-ref="dataSoruce">
<!--指定Hibernate实体类映射文件-->
<property name="mappingLocations">
<list>
<value>classpath*:/model/User.hbm.xml</value>
</list>
</property>
<!--指定Hibernate配置属性-->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">
true
</prop>
<prop key="hibernate.format_sql">
true
</prop>
</props>
</property>
</bean>

<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate"
p:sessionFactory-ref="sessionFactory"/>
<bean class="model.User"/>
</beans>

  由于mappingLocations属性的类型是Resource[],因此也支持以下简洁的配置方式:

1
2
p:dataSource-ref="dataSoruce"
p:mappingLocations="classpath:/model/*hbm.xml"

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class HibernateTest1 {
static final String path="SpringXml/HibernateXml.xml";
static ApplicationContext con= new ClassPathXmlApplicationContext(path);
static HibernateTemplate hibernateTeplate;
static SessionFactory sessionFactory;
static Session session;
public void init(){
hibernateTeplate=con.getBean("hibernateTemplate",HibernateTemplate.class);
sessionFactory=hibernateTeplate.getSessionFactory();
session=sessionFactory.openSession();
session.beginTransaction();//开启事务
}
public void close(){
session.close();
sessionFactory.close();
}
@Test
public void findAllUser(){//查询表里所有的信息
init();
Query query=session.createQuery("from User ");
List<User> list=query.list();
for (User u:list)
System.out.println(u.getName()+" "+u.getPassword()+" "+u.getPhone());
close();
}
}

结果:


使用注解配置

  Hibernate不但可以使用XML提供的ORM配置信息,也可以直接在领域对象类中通过注解定义ORM映射信息。Hibernate不但自己定义了一套注解,还支持JSR 220的JPA注解。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Entity//声明实体类
@Table(name = "h_user")//映射的表为h_user
public class HibernateConfig implements Serializable {
@Id//主键
@GeneratedValue(strategy = GenerationType.IDENTITY)//自增
@Column(name = "id")//对应表中的列
protected int id;

@Column(name = "name")
protected String name;

@Column(name = "password")
protected String password;

@Column(name = "phone")
protected String phone;

@Column(name = "address")
protected String adress;

//省略get、set函数
}

  Hibernate通过addAnnotatedClass()或addPackage()方法加载使用JPA注解的实体类,获取映射的元数据信息,并在此基础上创建SessionFactory实例。

1
2
3
4
5
Configuration configuration=new Configuration().configure();
configuration.addAnnotatedClass(HibernateConfig.class);
SessionFactory sessionFactory=configuration.buildSessionFactory();
Session session=sessionFactory.openSession();
session.beginTransaction();

  Spring配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"
p:dataSource-ref="dataSoruce">
<!--扫描并加载这些包路径(包括子包)的所有带注解实体类,扫描多个包可用逗号隔开-->
<property name="packagesToScan" value="Config"/>

<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">
true
</prop>
<prop key="hibernate.format_sql">
true
</prop>
</props>
</property>
</bean>

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×