how2j.cn

相关下载
文件名 文件大小
spring_hibernate.rar 12m
使用站长秘制下载工具

工具版本兼容问题
整合思路是,使DAO继承HibernateTemplate这个类
HibernateTemplate这个类提供了setSessionFactory()方法用于注入SessionFactory
通过spring获取DAO的时候,注入SessionFactory.

步骤 1 : pojo   
步骤 2 : hbm   
步骤 3 : DAO   
步骤 4 : applicationContext.xml   
步骤 5 : 测试查询   
步骤 6 : 测试增 删 改   

步骤 1 :

pojo

package com.how2java.pojo; public class Category { 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; } private int id; private String name; }
package com.how2java.pojo;
 
public class Category {
 
    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;
    }
    private int id;
    private String name;
}
步骤 2 :

hbm

<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.how2java.pojo"> <class name="Category" table="category_"> <id name="id" column="id"> <generator class="native"> </generator> </id> <property name="name" /> </class> </hibernate-mapping>
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.how2java.pojo">
	<class name="Category" table="category_">
		<id name="id" column="id">
			<generator class="native">
			</generator>
		</id>
		<property name="name" />

	</class>
	
</hibernate-mapping>
步骤 3 :

DAO

DAO继承HibernateTemplete,而HibernateTemplete类里有一个setSessionFactory用于接收sessionFactory的注入
package com.how2java.dao; import org.springframework.orm.hibernate3.HibernateTemplate; public class CategoryDAO extends HibernateTemplate{ }
package com.how2java.dao;

import org.springframework.orm.hibernate3.HibernateTemplate;

public class CategoryDAO extends HibernateTemplate{

}
步骤 4 :

applicationContext.xml

创建dao的时候,会注入sessionfactory
创建sessionFactory的时候会注入数据源ds
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean name="c" class="com.how2java.pojo.Category"> <property name="name" value="yyy" /> </bean> <bean name="dao" class="com.how2java.dao.CategoryDAO"> <property name="sessionFactory" ref="sf" /> </bean> <bean name="sf" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="ds" /> <property name="mappingResources"> <list> <value>com/how2java/pojo/Category.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.show_sql=true hbm2ddl.auto=update </value> </property> </bean> <bean name="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/how2java?characterEncoding=UTF-8" /> <property name="username" value="root" /> <property name="password" value="admin" /> </bean> </beans>
步骤 5 :

测试查询

因为CategoryDAO 继承了HibernateTemplate,所以可以直接使用
find来查询所有的Category
测试查询
package com.how2java.test; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.how2java.dao.CategoryDAO; import com.how2java.pojo.Category; public class TestSpring { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext( new String[] { "applicationContext.xml" }); CategoryDAO dao = (CategoryDAO) context.getBean("dao"); List<Category> cs= dao.find("from Category c"); System.out.println(cs); } }
package com.how2java.test;
 
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.how2java.dao.CategoryDAO;
import com.how2java.pojo.Category;
 
public class TestSpring {
 
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                new String[] { "applicationContext.xml" });
        CategoryDAO dao = (CategoryDAO) context.getBean("dao");
        List<Category> cs= dao.find("from Category c");
        System.out.println(cs);
    }
}
步骤 6 :

测试增 删 改

因为CategoryDAO 继承了HibernateTemplate,所以可以直接使用
1. save 增加
2. get 获取
3. update 修改
4. delete 删除
package com.how2java.test; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.how2java.dao.CategoryDAO; import com.how2java.pojo.Category; public class TestSpring { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext( new String[] { "applicationContext.xml" }); CategoryDAO dao = (CategoryDAO) context.getBean("dao"); Category c = new Category(); c.setName("category yyy"); //增加 dao.save(c); //获取 Category c2 = dao.get(Category.class, 1); //修改 c2.setName("category zzz"); dao.update(c2); //删除 dao.delete(c2); } }


HOW2J公众号,关注后实时获知布最新的教程和优惠活动,谢谢。


问答区域    
2018-06-12 关于getHibernateTemplate().find()方法过时的问题
SugarMan
这个问题在我使用spring5+hibernate5 idea出现提示。站长有没有解决方案?








答案 或者 代码至少填写一项, 如果是自己有问题,请重新提问,否则站长有可能看不到




2018-06-05 把代码搬到myeclipse上运行不了错误如下
oookoooo--



代码是在右上角下载的,然后复制相应文件到myeclipse的相应位置没做其他操作

							
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dao' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'sf' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sf' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Unable to get the default Bean Validation factory
	at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
	at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1325)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
	at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
	at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
	at com.how2java.test.TestSpring.main(TestSpring.java:15)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sf' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Unable to get the default Bean Validation factory
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1420)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
	at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:322)
	... 15 more
Caused by: org.hibernate.HibernateException: Unable to get the default Bean Validation factory
	at org.hibernate.cfg.beanvalidation.BeanValidationActivator.applyDDL(BeanValidationActivator.java:127)
	at org.hibernate.cfg.Configuration.applyBeanValidationConstraintsOnDDL(Configuration.java:1704)
	at org.hibernate.cfg.Configuration.applyConstraintsToDDL(Configuration.java:1654)
	at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1445)
	at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1375)
	at org.springframework.orm.hibernate3.SessionFactoryBuilderSupport.doBuildSessionFactory(SessionFactoryBuilderSupport.java:403)
	at org.springframework.orm.hibernate3.SessionFactoryBeanDelegate.afterPropertiesSet(SessionFactoryBeanDelegate.java:110)
	at org.springframework.orm.hibernate3.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:96)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1479)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
	... 22 more
Caused by: java.lang.reflect.InvocationTargetException
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:606)
	at org.hibernate.cfg.beanvalidation.BeanValidationActivator.applyDDL(BeanValidationActivator.java:118)
	... 31 more
Caused by: org.hibernate.HibernateException: Unable to build the default ValidatorFactory
	at org.hibernate.cfg.beanvalidation.TypeSafeActivator.getValidatorFactory(TypeSafeActivator.java:383)
	at org.hibernate.cfg.beanvalidation.TypeSafeActivator.applyDDL(TypeSafeActivator.java:109)
	... 36 more
Caused by: javax.validation.ValidationException: Unable to create a Configuration, because no Bean Validation provider could be found. Add a provider like Hibernate Validator (RI) to your classpath.
	at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:271)
	at javax.validation.Validation.buildDefaultValidatorFactory(Validation.java:110)
	at org.hibernate.cfg.beanvalidation.TypeSafeActivator.getValidatorFactory(TypeSafeActivator.java:380)
	... 37 more






答案 或者 代码至少填写一项, 如果是自己有问题,请重新提问,否则站长有可能看不到





2018-05-17 为什么不配置Hibernate的cfg文件....
2018-05-12 好多说的应该都是没自动建表的问题,缺个hibernate
2018-02-28 第一步就卡住了,hibernate没有自动建表
2018-02-22 ddd
2018-02-04 context.getBean这个方法作用
2017-12-14 请问为什么导入报错呢?
2017-10-10 关于 JAVA 框架-Spring+Hibernate-整合步骤 的提问
2017-09-30
2017-09-04 右上角下载的代码没有跑起来
2017-06-14 Spring 3.1 M2 版本Tomcat异常退出
2017-04-30 数据库连接关闭是自动关闭吗?
2017-04-26 问题补充
2017-04-26 运行报错
2017-03-15 spring4 取消了HibernateTemplate
2016-06-07 dao.find()




提问之前请登陆
关于 JAVA 框架-Spring+Hibernate-整合步骤 的提问

尽量提供截图代码异常信息,有助于分析和解决问题。 也可进本站QQ群交流: 620943819
提问尽量提供完整的代码,环境描述,越是有利于问题的重现,您的问题越能更快得到解答。
对教程中代码有疑问,请提供是哪个步骤,哪一行有疑问,这样便于快速定位问题,提高问题得到解答的速度
在已经存在的几千个提问里,有相当大的比例,是因为使用了和站长不同版本的开发环境导致的,比如 jdk, eclpise, idea, mysql,tomcat 等等软件的版本不一致。
请使用和站长一样的版本,可以节约自己大量的学习时间。 站长把教学中用的软件版本整理了,都统一放在了这里, 方便大家下载: http://how2j.cn/k/helloworld/helloworld-version/1718.html

上传截图