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-05-17 为什么不配置Hibernate的cfg文件....
WayneChou



看Hibernate教学的时候都是要配置数据库cfg文件的,为什么和Spring一整合就不不配置Hibernate的cfg文件了....而且没有cfg文件也就没有<mapping resource="com/how2java/pojo/Category.hbm.xml" />,就出现了无法建表的错误啊....运行大佬的例子也出现了无法建表的错误...

							
Hibernate: insert into category_ (name) values (?)
Exception in thread "main" org.springframework.dao.InvalidDataAccessResourceUsageException: could not insert: [com.how2java.pojo.Category]; SQL [insert into category_ (name) values (?)]; nested exception is org.hibernate.exception.SQLGrammarException: could not insert: [com.how2java.pojo.Category]
	at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:629)
	at org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:413)
	at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:410)
	at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:373)
	at org.springframework.orm.hibernate3.HibernateTemplate.save(HibernateTemplate.java:682)
	at com.how2java.test.TestSpring.main(TestSpring.java:22)
Caused by: org.hibernate.exception.SQLGrammarException: could not insert: [com.how2java.pojo.Category]
	at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
	at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
	at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:64)
	at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2345)
	at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2852)
	at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
	at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
	at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:320)
	at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:203)
	at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:129)
	at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
	at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
	at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
	at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
	at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
	at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:713)
	at org.hibernate.impl.SessionImpl.save(SessionImpl.java:701)
	at org.hibernate.impl.SessionImpl.save(SessionImpl.java:697)
	at org.springframework.orm.hibernate3.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:685)
	at org.springframework.orm.hibernate3.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:1)
	at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:405)
	... 3 more
Caused by: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Table 'how2java.category_' doesn't exist
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
	at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)
	at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
	at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
	at com.mysql.jdbc.Connection.execSQL(Connection.java:3283)
	at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1332)
	at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1604)
	at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1519)
	at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1504)
	at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:94)
	at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:57)
	... 21 more


1 个答案

WayneChou 答案时间:2018-05-17
发错了,没有<property name="hbm2ddl.auto">update</property>就无法建表




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





2018-05-12 好多说的应该都是没自动建表的问题,缺个hibernate
Mx128174
# Hibernate 相关配置 ## 方言 #hibernate.dialect=org.hibernate.dialect.MySQL5Dialect ## 显示Sql hibernate.show_sql=true ## 自动建表方式 #hibernate.hbm2ddl.auto= update ## 自动扫描的包前缀 entitymanager.packagesToScan= com.zslin ## 数据库连接 spring.datasource.url=jdbc:mysql://localhost:3306/study05?\ useUnicode=true&characterEncoding=utf-8&useSSL=true&autoReconnect=true ## 用户名 spring.datasource.username=root ## 密码 spring.datasource.password=123 ## 数据库驱动 spring.datasource.driver-class-name=com.mysql.jdbc.Driver ## 建表方式 spring.jpa.properties.hibernate.hbm2ddl.auto=update # 方言 spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect








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




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
站长会在每个工作日早上尽量回答提问(如果有漏掉没有回答的,请进群提醒一下)
提问尽量提供完整的代码,环境描述,越是有利于问题的重现,您的问题越能更快得到解答。
对教程中代码有疑问,请提供是哪个步骤,哪一行有疑问,这样便于快速定位问题,提高问题得到解答的速度
站长是玻璃心,提问的时候请语气温柔些 kiss~
截止2017-5-19日累计提问 1638个,站长回答了 1546个
截止2017-8-15日累计提问 2788个,站长回答了 2544个

上传截图