java之spring之spring整合hibernate
这篇讲下spring和hibernate的整合
目录结构如下:

1.新建java项目
2.导入jar包
antlr-2.7.7.jar
aopalliance.jar
aspectjweaver.jar
commons-logging.jar
dom4j-1.6.1.jar
hibernate-commons-annotations-4.0.5.Final.jar
hibernate-core-4.3.10.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
jandex-1.1.0.Final.jar
javassist-3.18.1-GA.jar
jboss-logging-3.1.3.GA.jar
jboss-logging-annotations-1.2.0.Beta1.jar
jboss-transaction-api_1.2_spec-1.0.0.Final.jar
mysql-connector-java-5.1.20-bin.jar
spring-aop-4.1.6.RELEASE.jar
spring-aspects-4.1.6.RELEASE.jar
spring-beans-4.1.6.RELEASE.jar
spring-context-4.1.6.RELEASE.jar
spring-core-4.1.6.RELEASE.jar
spring-expression-4.1.6.RELEASE.jar
spring-jdbc-4.1.6.RELEASE.jar
spring-orm-4.1.6.RELEASE.jar
spring-tx-4.1.6.RELEASE.jar
spring-web-4.1.6.RELEASE.jar
3.编写vo类
User.java
package cn.vincent.vo;
import java.io.Serializable;
public class User implements Serializable{
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
4.在src下,编写 hibernate.cfg.xml ,并且在cn.vincent.vo下编写vo类的映射文件 User.hbm.xml
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration>
<session-factory>
<!-- 数据库连接信息 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 默认 localhost:3306 -->
<property name="connection.url">jdbc:mysql:///test</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property> <!-- 通用配置 -->
<!-- 方言:hibernate要支持多种数据库,根据不同数据库生成对应的sql语句
告诉hibernate使用的什么数据库,以便生成对应数据库的sql
-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">update</property>
<!-- 打印sql语句 -->
<property name="show_sql">true</property>
<!-- 格式化sql -->
<property name="format_sql">true</property>
<!-- 映射信息 注意映射文件存放的是文档路径 需要用/ -->
<mapping resource="cn/vincent/vo/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
User.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.vincent.vo">
<class name="User" table="t_user">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"/>
<property name="age"/>
</class>
</hibernate-mapping>
5.准备好工具包 cn.vincent.util 下的 HibernateUtil.java 文件
HibernateUtil.java
package cn.vincent.util; import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry; public class HibernateUtil {
private static Configuration cfg;
private static ServiceRegistry registry;
private static SessionFactory factory;
private static ThreadLocal<Session> session;
static{
//初始化
cfg = new Configuration().configure();
registry = new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties())
.build();
factory = cfg.buildSessionFactory(registry);
session =new ThreadLocal<>();
}
//获取连接
public static Session getSession(){
if(session.get()==null){
session.set(factory.openSession());
}
return session.get();
}
//释放资源
public static void close(){
if(session.get()!=null){
session.get().close();
session.set(null);
}
}
}
6.编写 cn.vincent.dao 包下的 UserDao.java ,及cn.vincent.dao.impl下的 UserDaoImpl.java 文件
UserDao.java
package cn.vincent.dao;
import java.util.List;
import cn.vincent.vo.User;
public interface UserDao {
public List<User> findAll();
}
UserDaoImpl.java
package cn.vincent.dao.impl; import java.util.List; import org.hibernate.Session; import cn.vincent.dao.UserDao;
import cn.vincent.util.HibernateUtil;
import cn.vincent.vo.User; public class UserDaoImpl implements UserDao{ @Override
public List<User> findAll() {
Session session = HibernateUtil.getSession();
return session.createQuery("from User").list();
} }
7.编写 cn.vincent.service 下的 UserService.java 和 cn.vincent.service.impl 下的 UserServiceImpl.java
UserService.java
package cn.vincent.service;
import java.util.List; import cn.vincent.vo.User; public interface UserService {
public List<User> findAll();
}
UserServiceImpl.java
package cn.vincent.service.impl; import java.util.List; import cn.vincent.dao.UserDao;
import cn.vincent.service.UserService;
import cn.vincent.vo.User; public class UserServiceImpl implements UserService{
private UserDao userDao; @Override
public List<User> findAll() {
return userDao.findAll();
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
8.编写spring配置文件:beans.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="userDao" class="cn.vincent.dao.impl.UserDaoImpl"></bean>
<bean id="userService" class="cn.vincent.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"/>
</bean> </beans>
9.编写测试
新建名为 test 的source folder,并且在cn.vincent.service 下添加 UserServiceTest.java文件
package cn.vincent.service; import java.util.List; import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.vincent.vo.User; public class UserServiceTest { @Test
public void testFindAll(){
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
UserService us = ac.getBean(UserService.class);
List<User> list = us.findAll();
System.out.println(list.size());
}
}
10.运行测试,查看效果

结束!
补充:
11.在 spring 整合 hibernate 时,可以将 hibernate 的所有配置都写入 spring 中,这样就可以不要 hibernate.cfg.xml 配置文件:
beans.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 配置数据源:dbcp,c3p0,druid等 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///test"/>
<property name="username" value="root"/>
<property name="password" value="1111"/>
</bean>
<!-- sessionFactory对象由spring来创建 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- 通用属性配置 -->
<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>
<!-- 配置映射文件 -->
<property name="mappingLocations">
<array>
<value>classpath:cn/sxt/vo/User.hbm.xml</value>
</array>
</property>
</bean>
<bean id="userDao" class="cn.sxt.dao.impl.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="userService" class="cn.sxt.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"/>
</bean> </beans>
12.spring的声明式事务
<!-- 配置声明式事务 -->
<!-- 配置事务管理器 -->
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 配置事务通知 -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<!-- 表示以save开头的方法都需要事务
propagation 表示事务的传播特性
REQUIRED 查看当前是否有事务,如果有,使用当前事务,如果没有开启新事务
-->
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="find*" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- 配置事务aop -->
<aop:config>
<!--expression 指明事务在哪里起作用
第一个* 表示所有返回值
第二个* 表示所有类
第三个* 表示类中的所有方法
.. 表示所有参数
-->
<aop:pointcut expression="execution(* cn.sxt.service.impl.*.*(..))" id="pointcut"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
</aop:config>
github地址:https://github.com/Vincent-yuan/spring_hibernate
java之spring之spring整合hibernate的更多相关文章
- Spring学习7-Spring整合Hibernate
一.Springl为什么要整合Hibernate 二者的整合主要是把hibernate中核心的一些类型交给spring管理,这些类型主要包括sessionFactory. transactionM ...
- Spring Data初步--整合Hibernate
Spring Data课程中的技术介绍 Hibernate: Hibernate 是一个开放源代码的对象关系映射框架,它对 JDBC 进行了非常轻量级的对象封装,它将 pojo 与数据库表建立映射关系 ...
- Spring再接触 整合Hibernate
首先更改配置文件 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http ...
- 【Java EE 学习 53】【Spring学习第五天】【Spring整合Hibernate】【Spring整合Hibernate、Struts2】【问题:整合hibernate之后事务不能回滚】
一.Spring整合Hibernate 1.如果一个DAO 类继承了HibernateDaoSupport,只需要在spring配置文件中注入SessionFactory就可以了:如果一个DAO类没有 ...
- java框架之Spring(4)-Spring整合Hibernate和Struts2
准备 导包 Struts2 导入 Struts2 zip 包解压目录下 'apps/struts-blank.war' 中所有 jar 包,如下: asm-3.3.jar asm-commons-3. ...
- Java进阶知识25 Spring与Hibernate整合到一起
1.概述 1.1.Spring与Hibernate整合关键点 1) Hibernate的SessionFactory对象交给Spring创建. 2) hibernate事务交给spring的声明 ...
- Java Web开发之Spring | SpringMvc | Mybatis | Hibernate整合、配置、使用
1.Spring与Mybatis整合 web.xml: <?xml version="1.0" encoding="UTF-8"?> <web ...
- spring整合hibernate
spring整合hibernate包括三部分:hibernate的配置.hibernate核心对象交给spring管理.事务由AOP控制 好处: 由java代码进行配置,摆脱硬编码,连接数据库等信息更 ...
- Spring整合Hibernate。。。。
环境搭建,在eclipse中导入spring和hibernate框架的插件,和导入所有使用到的架包 首先,hibernate的创建: 建立两个封装类,其中封装了数据库中表的属性,这儿只写属性,gett ...
随机推荐
- SpringBoot(十四):SpringCloud初步认识
SpringCloud是一个基于SpringBoot实现的云应用开发工具,它为开发人员提供了一些工具来快速构建分布式系统中的一些常见模式(例如配置管理.服务发现.断路器.智能路由.微代理.控制总线.一 ...
- ocketMQ概念模型
ocketMQ概念模型 https://blog.csdn.net/binzhaomobile/article/details/73332463 HTTPS://blog.CSDN.net/bin找M ...
- HTML+CSS编写五环居中案例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- SpringCloud 微服务中 @Async 注解自定义线程池 引发的aop 问题
背景 在 使用springCloud 的@Async注解来做异步操作时,想自定义其线程池. 引发问题 自定义完线程池后,发现代码里并没有使用自定义线程池里的线程,于是新建一个demo工程,一样的配置代 ...
- ARM 链接脚本分析
分析连接脚本的语法规则 /* ---------------------------------------------------------------------------- * Memory ...
- BigDecimal 基本使用 比较大小和加减乘除
//比较大小: int a = bigdemical.compareTo(bigdemical2) //a = -1,表示bigdemical小于bigdemical2: //a = 0,表示bigd ...
- RabbitMQ安装后无法访问15672端口
切换到RabbitMQ的安装目录 sbin 目录下执行: rabbitmq-plugins enable rabbitmq_management 即可打开管理界面. rabbitmq的web管理界面无 ...
- linux驱动开发学习二:创建一个阻塞型的字符设备
在Linux 驱动程序中,可以使用等待队列来实现阻塞进程的唤醒.等待队列的头部定义如下,是一个双向列表. struct list_head { struct list_head *next, *pre ...
- 【计算机视觉基础】IPM
IPM code #if 0 void xyp2ipmp(cv::Mat& xyp, cv::Mat& ipmp, cv::Mat& xylim, Size& sz){ ...
- C# web项目乱码问题解决
在 web.config 文件中添加代码 <globalization requestEncoding="GB2312" responseEncoding="GB ...