对于Hibernate学习1--SpringMVC+Hibernate集成环境搭建感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍springspringmvchibernate框架搭建,并为您
对于Hibernate学习1--SpringMVC+Hibernate集成环境搭建感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍spring springmvc hibernate框架搭建,并为您提供关于10.31 springMVC 与 hibernate 配置、asp.net-mvc-3 – 没有使用asp mvc 3,nhibernate 3.2和spring.net 1.3.2绑定到线程异常的Hibernate Session、hibernate 学习笔记 01-- 在 eclipse 环境下搭建 hibernate 框架、Hibernate 学习笔记(一)—— Hibernate 概述和使用 Hibernate 进行简单的增删改查操作的有用信息。
本文目录一览:- Hibernate学习1--SpringMVC+Hibernate集成环境搭建(spring springmvc hibernate框架搭建)
- 10.31 springMVC 与 hibernate 配置
- asp.net-mvc-3 – 没有使用asp mvc 3,nhibernate 3.2和spring.net 1.3.2绑定到线程异常的Hibernate Session
- hibernate 学习笔记 01-- 在 eclipse 环境下搭建 hibernate 框架
- Hibernate 学习笔记(一)—— Hibernate 概述和使用 Hibernate 进行简单的增删改查操作
Hibernate学习1--SpringMVC+Hibernate集成环境搭建(spring springmvc hibernate框架搭建)
除了刚毕业那会用了几个月的hibernate好像好久都没有碰过了,正好最近在整理以前的学习笔记就把这块知识系统的学习一下,特别是hibernate和ibatis的对比应该对我现在做的东西有很大的帮助。
这个博客可能会是一个系列,今天是第一篇,搭建环境篇。由于以前的环境是springmvc+maven的环境,所以本系列博客就采用springmvc+hibernate的环境。
1 maven环境的jar包依赖,我这里采用的是spring3.2.2的版本和Hibernte的4.2.0的版本(pom.xml)
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
<!-- hibernate start-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.2.0.Final</version>
</dependency>
<!-- hibernate end-->
2 springMvc的配置(web.xml)
<!--spring mvc 配置 start-->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--spring mvc 配置 end-->
3 Spring代理Hibernate的配置,正常来说,hibernate应该有自己的配置文件的,里面配置数据源信息及hibernate的属性设置,但是我们使用了spring就可以把相关配置放到spirng里了。(spring-servlet.xml)
<!--配置数据源-->
<bean id="dataSource" >
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://XXXX:3306/zz_test"/>
<property name="username" value="XXXX"/>
<property name="password" value="XXXX"/>
</bean>
<!--配置hibernate-->
<bean id="sessionFactory" >
<property name="dataSource" ref="dataSource"></property>
<property name="mappingResources">
<list>
<value>com/XXX/test/hibernate/studentTest/Student.hbm.xml</value>
</list>
</property>
<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="txManager" >
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="txManager"/>
4 接下来就是hibernate的业务配置文件了(Student.hbm.xml)
<hibernate-mapping>
<class name="com.XXX.test.hibernate.studentTest.Student" table="student1" schema="zz_test">
<id name="id" type="java.lang.Integer" column="id">
<generator />
</id>
<property name="name" type="java.lang.String">
<column name="name" length="16" />
</property>
</class>
</hibernate-mapping>
对应的表结构为
5 Student的DO和相关DAO实现如下(Student.java,StudentDAO.java)
public class Student implements Serializable {
private Integer id;
private String name;
public Student() {
super();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Service
public class StudentDAO {
@Autowired
private SessionFactory sessionFactory;
private Session session=null;
public void init() {
session = sessionFactory.openSession();
}
public void save(Student student) {
Transaction tran = session.getTransaction();
tran.begin();
session.save(student);
tran.commit();
}
public void update(Student student) {
Transaction tran = session.getTransaction();
tran.begin();
session.update(student);
tran.commit();
}
public void delete(Integer id) {
String hql = "delete from Student o where o.id = ?";
Transaction tran = session.getTransaction();
tran.begin();
Query query = session.createQuery(hql);
query.setParameter(0, id);
query.executeUpdate();
tran.commit();
}
@SuppressWarnings("unchecked")
public Student getModel(Integer id) {
String hql = "from Student o where id = :id";
Query query = session.createQuery(hql);
query.setParameter("id", id);
List list = query.list();
if (list != null && list.size() == 1) {
return (Student) list.get(0);
} else {
return null;
}
}
@SuppressWarnings("unchecked")
public List getPagination(int maxResults, int firstResult) {
String hql = "from Student o";
Query query = session.createQuery(hql);
query.setFirstResult(firstResult);
query.setMaxResults(maxResults);
return query.list();
}
}
6 前台的调用方法如下(StudentController.java)
@Controller
public class StudentController {
@Autowired
StudentDAO studentDAO;
@RequestMapping(value = "/student/test.do" )
public String test(HttpServletRequest request, HttpServletResponse response) {
studentDAO.init();
//添加
for (int i = 0; i < 10; i++) {
Student student = new Student();
student.setName("Tao" + i);
studentDAO.save(student);
}
//删除
studentDAO.delete(2);
// 修改
Student student = new Student();
student.setId(4);
studentDAO.update(student);
// 单个查询
Student s = studentDAO.getModel(4);
System.out.println(s.getName());
// 分布查询
List list = studentDAO.getPagination(4, 1);
for (int i = 0; i < list.size(); i++) {
Student std = (Student) list.get(i);
System.out.println(std.getName());
}
return "success";
}
}
总结一下,以上就是基本的运行环境了,以后的代码都是在这个环境的基础上进行展开。主要是maven的依赖,spring代理hibernate的配置及hibernate的DO和数据库的映射。当然Hibernate这么流行,其功能不可能只有这些,以后我们会探讨一些更深入的知识。
另外 下面这两句的配置会在console端打印出相关的调用sql语句,对于代码的调试有很大帮助。
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
下面是一些其他的hibernate属性配置
<!--数据库连接池的大小-->
<property name="hibernate.connection.pool.size">20</property>
<!--是否在后台显示Hibernate用到的SQL语句,开发时设置为true,便于差错,程序运行时可以在Eclipse的控制台显示Hibernate的执行Sql语句。项目部署后可以设置为false,提高运行效率-->
<property name="hibernate.show_sql">true</property>
<!--jdbc.fetch_size是指Hibernate每次从数据库中取出并放到JDBC的Statement中的记录条数。Fetch Size设的越大,读数据库的次数越少,速度越快,Fetch Size越小,读数据库的次数越多,速度越慢-->
<property name="jdbc.fetch_size">50</property>
<!--jdbc.batch_size是指Hibernate批量插入,删除和更新时每次操作的记录数。Batch Size越大,批量操作的向数据库发送Sql的次数越少,速度就越快,同样耗用内存就越大-->
<property name="jdbc.batch_size">23</property>
<!--jdbc.use_scrollable_resultset是否允许Hibernate用JDBC的可滚动的结果集。对分页的结果集。对分页时的设置非常有帮助-->
<property name="jdbc.use_scrollable_resultset">false</property>
<!--connection.useUnicode连接数据库时是否使用Unicode编码-->
<property name="Connection.useUnicode">true</property>
<!--connection.characterEncoding连接数据库时数据的传输字符集编码方式,最好设置为gbk,用gb2312有的字符不全-->
<property name="connection.characterEncoding">gbk</property>
另外,dilletc是用来配置hibernte的方言的,我们这里用的是mysql所以按照如下配置,
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
Hibenate的还支持以下方言
DB2 | org.hibernate.dialect.DB2Dialect |
DB2 AS/400 | org.hibernate.dialect.DB2400Dialect |
DB2 OS390 | org.hibernate.dialect.DB2390Dialect |
PostgreSQL | org.hibernate.dialect.PostgreSQLDialect |
MySQL | org.hibernate.dialect.MySQLDialect |
MySQL with InnoDB | org.hibernate.dialect.MySQLInnoDBDialect |
MySQL with MyISAM | org.hibernate.dialect.MySQLMyISAMDialect |
Oracle (any version) | org.hibernate.dialect.OracleDialect |
Oracle 9i/10g | org.hibernate.dialect.Oracle9Dialect |
Sybase | org.hibernate.dialect.SybaseDialect |
Sybase Anywhere | org.hibernate.dialect.SybaseAnywhereDialect |
Microsoft SQL Server | org.hibernate.dialect.SQLServerDialect |
SAP DB | org.hibernate.dialect.SAPDBDialect |
Informix | org.hibernate.dialect.InformixDialect |
HypersonicSQL | org.hibernate.dialect.HSQLDialect |
Ingres | org.hibernate.dialect.IngresDialect |
Progress | org.hibernate.dialect.ProgressDialect |
Mckoi SQL | org.hibernate.dialect.MckoiDialect |
Interbase | org.hibernate.dialect.InterbaseDialect |
Pointbase | org.hibernate.dialect.PointbaseDialect |
FrontBase | org.hibernate.dialect.FrontbaseDialect |
Firebird | org.hibernate.dialect.FirebirdDialect |
10.31 springMVC 与 hibernate 配置
springMVC与hibernate 配置代码片段
<beans>
<bean id = "dataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@localhost:1521:ORCL" />
<property name="userName" value="spring" />
<property name="password" value="spring" />
</bean>
<bean id="sessionFactory">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10Dialect</prop>
只要bibernate映射文件改变就更新数据库里面的表,不用手动创建,自动更新,如果将update改成create,则每次更新的时候会将之前的表及数据全部删除
<prop key="hibernate.hbm2ddl.auto">update</prop>
打印sql语句
<prop key="hibernate.show_sql">true</prop>
格式化sql语句
<prop key="hibernate..format_sql">true</prop>
</props>
</property>
</bean>
</beans>
asp.net-mvc-3 – 没有使用asp mvc 3,nhibernate 3.2和spring.net 1.3.2绑定到线程异常的Hibernate Session
我得到的错误是
No Hibernate Session bound to thread,and configuration does not allow creation of non-transactional one here Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: NHibernate.HibernateException: No Hibernate Session bound to thread,and configuration does not allow creation of non-transactional one here Source Error: An unhandled exception was generated during the execution of the current web request. information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [HibernateException: No Hibernate Session bound to thread,and configuration does not allow creation of non-transactional one here] Spring.Data.NHibernate.SpringSessionContext.CurrentSession() in c:\_prj\spring-net\trunk\src\Spring\Spring.Data.NHibernate12\Data\NHibernate\SpringSessionContext.cs:72 Technolog.Rma.Business.Repositories.RepairBatchDAO.findRepairBatchPageCount(String login,Int32 rowsPerPage) in C:\work\samplemvc\src\Technolog.Rma.Business\Repositories\RepairBatchDAO.cs:55 _dynamic_Technolog.Rma.Business.Repositories.RepairBatchDAO.findRepairBatchPageCount(Object,Object[] ) +273 Spring.Reflection.Dynamic.SafeMethod.Invoke(Object target,Object[] arguments) in c:\_prj\spring-net\trunk\src\Spring\Spring.Core\Reflection\Dynamic\Dynamicmethod.cs:156 Spring.Aop.Framework.DynamicmethodInvocation.InvokeJoinpoint() in c:\_prj\spring-net\trunk\src\Spring\Spring.Aop\Aop\Framework\DynamicmethodInvocation.cs:100 Spring.Dao.Support.PersistenceExceptionTranslationInterceptor.Invoke(IMethodInvocation invocation) in c:\_prj\spring-net\trunk\src\Spring\Spring.Data\Dao\Support\PersistenceExceptionTranslationInterceptor.cs:181 <snip/>
我的web.config文件是
<?xml version="1.0" encoding="utf-8"?> <!-- For more information on how to configure your ASP.NET application,please visit http://go.microsoft.com/fwlink/?LinkId=152368 Spring.Context.Support.ContextHandler,Spring.Core <resource uri="~/Config/propertyConfigurer.xml" /> --> <configuration> <configSections> <sectionGroup name="spring"> <section name="context" type="Spring.Context.Support.MvcContextHandler,Spring.Web.Mvc3" /> </sectionGroup> </configSections> <appSettings> <add key="dataFile" value="App_Data\data.db3" /> <add key="ClientValidationEnabled" value="true"/> <add key="UnobtrusiveJavaScriptEnabled" value="true"/> <add key="Spring.Data.NHibernate.Support.OpenSessionInViewModule.SessionFactoryObjectName" value="SessionFactory"/> </appSettings> <spring> <context> <resource uri="file://~/Config/propertyConfigurer.xml" /> <resource uri="file://~/Config/sessionFactory.xml" /> <resource uri="file://~/Config/mappers.xml" /> <resource uri="file://~/Config/repositories.xml" /> <resource uri="file://~/Config/controllers.xml" /> <resource uri="file://~/Config/scopedobjects.xml" /> <resource uri="file://~/Config/utils.xml" /> </context> </spring> <system.web> <httpModules> <!-- <add name="Spring" type="Spring.Context.Support.WebSupportModule,Spring.Web"/> <add name="OpenSessionInView" type="Spring.Data.NHibernate.Support.OpenSessionInViewModule,Spring.Data.NHibernate32"/> --> </httpModules> <compilation debug="true" targetFramework="4.0"> <assemblies> <add assembly="System.Web.Abstractions,Version=4.0.0.0,Culture=neutral,PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Web.Helpers,Version=1.0.0.0,PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Web.Routing,PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Web.Mvc,Version=3.0.0.0,PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Web.WebPages,PublicKeyToken=31BF3856AD364E35" /> </assemblies> </compilation> <pages> <namespaces> <add namespace="System.Web.Helpers" /> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing" /> <add namespace="System.Web.WebPages" /> </namespaces> </pages> <authentication mode="Forms"> <forms loginUrl="~/Account/logon" timeout="2880" /> </authentication> <customErrors mode="Off"/> </system.web> <system.webServer> <validation validateIntegratedModeConfiguration="false" /> <modules runAllManagedModulesForAllRequests="true"> <add name="Spring" type="Spring.Context.Support.WebSupportModule,Spring.Data.NHibernate32"/> </modules> <!-- <handlers> <add name="SpringPageHandler" verb="*" path="*.aspx" type="Spring.Web.Support.PageHandlerFactory,Spring.Web"/> <add name="SpringWebServiceHandler" verb="*" path="*.asmx" type="Spring.Web.Services.WebServiceHandlerFactory,Spring.Web" /> <add name="SpringContextMonitor" verb="*" path="ContextMonitor.ashx" type="Spring.Web.Support.ContextMonitor,Spring.Web"/> </handlers> --> </system.webServer> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-4.0.7.0" newVersion="4.0.7.0" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration>
我的sessionFactory.xml文件是
<?xml version="1.0" encoding="utf-8" ?> <objects xmlns="http://www.springframework.net" xmlns:db="http://www.springframework.net/database" xmlns:tx="http://www.springframework.net/tx"> <object id="siteRoot" type="System.Web.Hosting.HostingEnvironment,System.Web" factory-method="get_ApplicationPhysicalPath" /> <object id="dataFile" type="System.IO.Path,mscorlib" factory-method="Combine"> <constructor-arg name="path1" ref="siteRoot" /> <constructor-arg name="path2" value="${dataFile}" /> </object> <db:provider id="dbProvider" provider="System.Data.sqlClient" connectionString="Data Source=AJAsql7;Initial Catalog=Xanadu;User ID=RMA;Password=RMA;"/> <object id="sessionFactory" scope="application" type="Spring.Data.NHibernate.LocalSessionFactoryObject,Spring.Data.NHibernate32"> <property name="DbProvider" ref="dbProvider"/> <property name="MappingAssemblies"> <list> <value>Technolog.Rma.Business</value> </list> </property> <property name="HibernateProperties"> <dictionary> <entry key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider"/> <entry key="dialect" value="NHibernate.Dialect.Mssql7Dialect"/> <entry key="connection.driver_class" value="NHibernate.Driver.sqlClientDriver"/> <entry key="use_proxy_validator" value="false" /> <entry key="current_session_context_class" value="Spring.Data.NHibernate.SpringSessionContext,Spring.Data.NHibernate32"/> </dictionary> </property> </object> <!-- Transaction Management Strategy - local database transactions --> <object id="transactionManager" type="Spring.Data.NHibernate.HibernateTransactionManager,Spring.Data.NHibernate32"> <property name="DbProvider" ref="dbProvider"/> <property name="SessionFactory" ref="sessionFactory"/> </object> <!-- Exception translation object post processor --> <object type="Spring.Dao.Attributes.PersistenceExceptionTranslationPostProcessor,Spring.Data"/> </objects>
我的RepairBatchDao的一部分是
[Repository] class RepairBatchDAO : IRepairBatchDAO { public ISessionFactory SessionFactory { get; set; } public long findRepairBatchPageCount(string login,int rowsPerPage) { var rowCount = 1L; var session = SessionFactory.GetCurrentSession(); // line 55 var transaction = session.BeginTransaction(); try { transaction = session.BeginTransaction(); var hqlCountQuery = session.createquery("select count(*) from Technolog.Rma.Business.Domain.RepairBatch rb where rb.Customer.Login=?") .SetParameter(0,login); rowCount = hqlCountQuery.UniqueResult<long>(); transaction.Commit(); return (rowCount + rowsPerPage - 1) / rowsPerPage; } catch { if (transaction != null) transaction.Rollback(); } finally { if (session != null) session.Close(); // I shouldn't be doing this... } return 0L; } // snip ...
我花了太多时间试图自己解决这个问题.我希望有人能指出我正确的方向.我已经检查了stackoverflow中的各种帖子(太多提及),但他们没有帮助.
我是一个Java人,这是我的第一个.net项目,所以不确定我是否做过傻事.
25/9/2012
我已经对我的customerDAO进行了更改
public class CustomerDAO : ICustomerDAO { public ISessionFactory SessionFactory { get; set; } private TransactionTemplate tt; public IPlatformTransactionManager TransactionManager { set { tt = new TransactionTemplate(value); } } <snip/> public Customer find(string login) { IList<Customer> customers; Object result = tt.Execute(delegate(ITransactionStatus status) //line 42 { var transaction = status.Transaction; var session = this.SessionFactory.GetCurrentSession(); //var transaction = session.BeginTransaction(); try { customers = session.createquery("from Technolog.Rma.Business.Domain.Customer Customer where Customer.Login=?") .SetParameter(0,login) .List<Customer>(); if (customers.Count > 0) { return customers[0]; } } catch { } finally { if (session != null) session.Close(); } return null; }); return (Customer)result; }
我现在得到的错误是
Server Error in '/RMA' Application. -------------------------------------------------------------------------------- Cannot access a disposed object. Object name: 'AdoTransaction'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.ObjectdisposedException: Cannot access a disposed object. Object name: 'AdoTransaction'. Source Error: An unhandled exception was generated during the execution of the current web request. information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [ObjectdisposedException: Cannot access a disposed object. Object name: 'AdoTransaction'.] NHibernate.Transaction.AdoTransaction.Commit() +425 Spring.Data.NHibernate.HibernateTransactionManager.DoCommit(DefaultTransactionStatus status) in c:\_prj\spring-net\trunk\src\Spring\Spring.Data.NHibernate\Data\NHibernate\HibernateTransactionManager.cs:579 Spring.Transaction.Support.AbstractPlatformTransactionManager.ProcessCommit(DefaultTransactionStatus status) in c:\_prj\spring-net\trunk\src\Spring\Spring.Data\Transaction\Support\AbstractPlatformTransactionManager.cs:853 Spring.Transaction.Support.TransactionTemplate.Execute(TransactionDelegate transactionMethod) in c:\_prj\spring-net\trunk\src\Spring\Spring.Data\Transaction\Support\TransactionTemplate.cs:159 Technolog.Rma.Business.Repositories.CustomerDAO.find(String login) in C:\work\samplemvc\src\Technolog.Rma.Business\Repositories\CustomerDAO.cs:42 _dynamic_Technolog.Rma.Business.Repositories.CustomerDAO.find(Object,Object[] ) +147 Spring.Reflection.Dynamic.SafeMethod.Invoke(Object target,Object[] arguments) in c:\_prj\spring-net\trunk\src\Spring\Spring.Core\Reflection\Dynamic\Dynamicmethod.cs:156 Spring.Aop.Framework.DynamicmethodInvocation.InvokeJoinpoint() in c:\_prj\spring-net\trunk\src\Spring\Spring.Aop\Aop\Framework\DynamicmethodInvocation.cs:100 Spring.Dao.Support.PersistenceExceptionTranslationInterceptor.Invoke(IMethodInvocation invocation) in c:\_prj\spring-net\trunk\src\Spring\Spring.Data\Dao\Support\PersistenceExceptionTranslationInterceptor.cs:190 CompositionAopProxy_33677284ca854c0b8c01a5b0ae0a0524.find(String login) +383 Technolog.Rma.Web.Controllers.HomeController.Index(Int32 page) in C:\work\samplemvc\src\Technolog.Rma.Web\Controllers\HomeController.cs:36 lambda_method(Closure,ControllerBase,Object[] ) +112 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext,IDictionary`2 parameters) +248 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext,ActionDescriptor actionDescriptor,IDictionary`2 parameters) +39 System.Web.Mvc.<>c__displayClass15.<InvokeActionMethodWithFilters>b__12() +125 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter,ActionExecutingContext preContext,Func`1 continuation) +640 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext,IList`1 filters,IDictionary`2 parameters) +312 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext,String actionName) +691 System.Web.Mvc.Controller.ExecuteCore() +162 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +305 System.Web.Mvc.<>c__displayClassb.<BeginProcessRequest>b__5() +62 System.Web.Mvc.Async.<>c__displayClass1.<MakeVoidDelegate>b__0() +20 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +469 System.Web.HttpApplication.ExecuteStep(IExecutionStep step,Boolean& completedSynchronously) +375 -------------------------------------------------------------------------------- Version information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272
解决方法
Cannot access a disposed object.
我使用OSIV的web.config文件是
<?xml version="1.0" encoding="utf-8"?> <!-- For more information on how to configure your ASP.NET application,Spring.Web.Mvc3" /> </sectionGroup> </configSections> <appSettings> <add key="dataFile" value="App_Data\data.db3" /> <add key="ClientValidationEnabled" value="true"/> <add key="UnobtrusiveJavaScriptEnabled" value="true"/> <add key="Spring.Data.NHibernate.Support.OpenSessionInViewModule.SessionFactoryObjectName" value="SessionFactory"/> </appSettings> <spring> <context> <resource uri="file://~/Config/propertyConfigurer.xml" /> <resource uri="file://~/Config/sessionFactory.xml" /> <resource uri="file://~/Config/mappers.xml" /> <resource uri="file://~/Config/repositories.xml" /> <resource uri="file://~/Config/controllers.xml" /> <resource uri="file://~/Config/scopedobjects.xml" /> <resource uri="file://~/Config/utils.xml" /> </context> </spring> <system.web> <httpModules> <add name="Spring" type="Spring.Context.Support.WebSupportModule,Spring.Data.NHibernate32"/> </httpModules> <compilation debug="true" targetFramework="4.0"> <assemblies> <add assembly="System.Web.Abstractions,PublicKeyToken=31BF3856AD364E35" /> </assemblies> </compilation> <pages> <namespaces> <add namespace="System.Web.Helpers" /> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing" /> <add namespace="System.Web.WebPages" /> </namespaces> </pages> <authentication mode="Forms"> <forms loginUrl="~/Account/logon" timeout="2880" /> </authentication> <customErrors mode="Off"/> </system.web> <system.webServer> <validation validateIntegratedModeConfiguration="false" /> <modules runAllManagedModulesForAllRequests="true"> <add name="Spring" type="Spring.Context.Support.WebSupportModule,Spring.Web"/> </handlers> --> </system.webServer> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-4.0.7.0" newVersion="4.0.7.0" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration>
请注意,对osiv和spring WebSupportModule的引用是/在其中使它在我的开发环境中工作,也在/中使应用程序在IIS 7.5中工作
我也在我的视图中使用延迟加载,因此osiv是更好的解决方案.我在我的问题中展示了程序化事务控制,因为这是我尝试提出解决方案的过程.
hibernate 学习笔记 01-- 在 eclipse 环境下搭建 hibernate 框架

1. 下载并解压 hibernate-distribution-3.3.2.GA.zip 和 slf4j-1.5.8.zip
2. 在 hibernate-distribution-3.3.2.GA 文件夹中找到:
hibernate3.jar
3. 在 hibernate-distribution-3.3.2.GA/lib/required 文件夹中找到 hibernate 运行必要的 jar 包 :
antlr-2.7.6.jar
commons-collections-3.1.jar
dom4j-1.6.1.jar
javassist-3.9.0.GA.jar
jta-1.1.jar
slf4j-api-1.5.8.jar
4. 在 slf4j-1.5.8 文件夹下找到 :
slf4j-nop-1.5.8.jar
5. 在 eclipse 中新建 Dynamic Web Project 工程,名为 hibernateHelloWorld 如下图:
5.1 建立好的工程结构图如下:
6. 将以上 8 个 jar 包放入 hibernateHelloWorld/WebContent/WEB-INF/lib 文件夹下,如下图:
7. 选择 Windows - Preferences - java - Build Path - User Libraries 如下图
7.1 New 随便起个名字叫 “hibernate” 如下图:
7.2 OK
7.3 为我们自定义的 "hibernate" 添加 jar 包。
Add JARs.. 并找到 hibernateHelloWorld/WebContent/WEB-INF/lib 将刚才放入 lib 中的 8 个包选中因为这 8 个 jar 包是 hibernate 所需的包,所以将它放入一个我们自定义的 Libraries 中,并单击 OK,如下图 :
8. 为工程添加 hibernate 支持的包 步骤如下:
8.1 右击 hibernateHelloWorld -- Build Path -- Configure Build Path..
8.2 如下图
8.3 Add Library... User Library ---> Next
8.4 选中 "hibernate" Finish。
9. 看下我们的工程多了个 hibernate Libraries , 如下图:
10. 至此,我们工程所需要的包添加完毕。
Hibernate 学习笔记(一)—— Hibernate 概述和使用 Hibernate 进行简单的增删改查操作
Hibernate是一个开放源代码的对象关系映射框架,它将 POJO与数据库表建立映射关系,Hibernate 可以自动生成SQL语句,自动执行,完成数据持久化的任务,使得我们方便的使用对象编程思维来操纵数据库。 [TOC]
一、Hibernate 概述
Hibernate 的API一共有6个接口,分别为:Session、SessionFactory、Transaction、Query、Criteria和Configuration。通过这些接口,可以对持久化对象进行存取、事务控制。
- **Session:**Session接口负责执行被持久化对象的CRUD操作。但需要注意的是Session对象是非线程安全的。
- **SessionFactory:**SessionFactory接口负责初始化Hibernate,并负责创建Session对象。这里用到了工厂模式。SessionFactory并不是轻量级的,所以在一般情况下,一个项目通常只需要一个SessionFactory对象。
- **Transaction:**Transaction 接口是对实际事务实现的一个抽象,这些实现包括JDBC的事务、JTA 中的UserTransaction、甚至可以是CORBA 事务。
- **Query:**Query接口可以实现对数据库及持久对象进行查询,它可以有两种表达方式:HQL语言或本地数据库的SQL语句。
- **Criteria:**Criteria接口与Query接口非常类似,允许创建并执行面向对象的标准化查询。
- **Configuration:**Configuration 类的作用是对Hibernate 进行配置,以及对它进行启动。在Hibernate 的启动过程中,Configuration 类的实例首先定位映射文档的位置,读取这些配置,然后创建一个SessionFactory对象。
二、创建第一个 Hibernate 项目
2.1、导入 Jar 包
一个简单的 Hibernate 工程共需要两类 Jar 包,一种是 Hibernate 所必须使用的 Jar 包,另外一种是数据库驱动 Jar 包。所需的 Jar 包名称如下:
- Hibernate 必备的 Jar 包
antlr-2.7.7.jar
dom4j-1.6.1.jar
geronimo-jta_1.1_spec-1.1.1.jar
hibernate-commons-annotations-5.0.1.Final.jar
hibernate-core-5.0.7.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
jandex-2.0.0.Final.jar
javassist-3.18.1-GA.jar
jboss-logging-3.3.0.Final.jar
- 数据库驱动 Jar 包
mysql-connector-java-5.1.47.jar
c3p0-0.9.2.1.jar
hibernate-c3p0-5.0.7.Final.jar
mchange-commons-java-0.2.3.4.jar
2.2、编写实体类
创建用户(User) 实体类,其中包含用户名、密码、昵称、出生日期等基本信息。
package com.hibernate.domain;
import java.util.Date;
public class User {
private Integer uid;
private String username;
private String password;
private String nickname;
private Date birthday;
private String realname;
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getRealname() {
return realname;
}
public void setRealname(String realname) {
this.realname = realname;
}
@Override
public String toString() {
return "User [uid=" + uid + ", username=" + username + ", password=" + password + ", nickname=" + nickname
+ ", birthday=" + birthday + ", realname=" + realname + "]";
}
}
2.3、编写Hibernate和实体类配置文件
2.3.1、编写 Hibernate 配置文件 —— hibernate.cfg.xml
Hibernate 的配置文件默认编写位置是在工程项目的 src
下,在配置文件中,主要配置 session-factory
,用于创建 Session
对象,以便对 POJO 进行增删改查的操作。
在 session-factory
中,主要配置数据库的配置信息、连接池供应商以及实体类映射文件的位置。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<!-- 配置 SessionFactory 用于创建 Session 对象 -->
<session-factory>
<!-- 数据库的配置信息 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///hibernate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">admin</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 可选配置 -->
<property name="hibernate.show_sql">true</property>
<!-- <property name="hibernate.format_sql">true</property> -->
<!-- 配置 Hibernate 以何种方式生成DDL语句 update:表示检测实体类的映射配置和数据库表结构是否一致,不一致则自动更新
auto: -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 配置 Session 绑定本地线程 -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- 设置连接池供应商 -->
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<!-- 配置实体类的映射文件位置 -->
<mapping resource="com/one_to_many/domain/User.hbm.xml" />
</session-factory>
</hibernate-configuration>
2.3.2、编写实体类配置文件 —— User.hbm.xml
实体类映射文件则是编写在与实体类相同的包下面,命名通常以 实体类名称.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">
<!-- package:配置实体类所在的包名称 -->
<hibernate-mapping package="com.hibernate.domain">
<!--
class标签,对应实体类
name:实体类的名称,如果配有配置package属性,需要写类的绝对路径
table:对应数据库中的表名称
-->
<class name="User" table="tb_user">
<!--
id:数据库表中的主键
id,property
name:实体类的属性名称
column:实体类属性对应数据库表中的列名称
-->
<id name="uid" column="user_id">
<!-- generator:表主键的生成策略 -->
<generator></generator>
</id>
<property name="username" column="username"></property>
<property name="password" column="password"></property>
<property name="nickname" column="nickname"></property>
<property name="birthday" column="birthday"></property>
<property name="realname" column="realname"></property>
</class>
</hibernate-mapping>
2.3.3、编写 Hibernate 工具类,获取 Session 对象
package com.hibernate.utils;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
// 使用静态代码块来创建 SessionFactory 对象,保证单例
private static SessionFactory sessionFactory;
static {
// 创建 Configuration 对象
Configuration cfg = new Configuration();
// 加载 Hibernate 默认配置文件,如果配置文件不在 src 目录下,则需要填写配置文件地址
cfg.configure();
// 根据配置文件,创建 SessionFactory 对象
sessionFactory = cfg.buildSessionFactory();
}
public static Session openSession() {
// 获取 session 对象
return sessionFactory.openSession();
}
public static Session getCurrentSession() {
// 获取与当前线程绑定的 session 对象
return sessionFactory.getCurrentSession();
}
}
2.3.4、测试工具类
package com.hibernate.test;
import org.hibernate.Session;
import org.junit.Test;
import com.hibernate.utils.HibernateUtil;
public class TestHibernateUtil {
@Test
public void test() {
Session session = HibernateUtil.openSession();
}
}
如果测试类运行成功,则在 Hibernate 配置中所连接的数据库中就会出现 tb_user
表。
三、简单的增删改查操作
3.1、保存操作
使用 Hibernate 保存数据,只需要调用 session 的 save() 方法,即可将 POJO 保存到数据库中。
package com.hibernate.test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import com.hibernate.domain.User;
import com.hibernate.utils.HibernateUtil;
public class TestHibernate {
@Test
public void testSave() {
// 获取 session 对象
Session session = HibernateUtil.openSession();
// 获取 Transaction 对象
Transaction tx = session.beginTransaction();
// 开启事务
tx.begin();
try {
User user = new User();
user.setUsername("martin_depp@126.com");
user.setPassword("martin0319");
user.setNickname("奔跑的小蚂蚁");
user.setBirthday(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("1991-03-19 11:55:00"));
user.setRealname("孟祥杰");
// 调用 session 对象的 save() 实现数据的持久化操作
session.save(user);
} catch (ParseException e) {
e.printStackTrace();
} finally {
// 提交事务
tx.commit();
// 关闭 session
session.close();
}
}
}
3.2、查找操作
使用 Hibernate 进行查找,只需要调用 session 的get(Class<T> arg0, Serializable arg1)
方法,其中 arg0 表示对应实体类名称,arg1表示主键值,如:查询主键为1的 User 实体对象。
package com.hibernate.test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import com.hibernate.domain.User;
import com.hibernate.utils.HibernateUtil;
public class TestHibernate {
@Test
public void testGet() {
// 获取 session 对象
Session session = HibernateUtil.openSession();
// 获取 Transaction 对象
Transaction tx = session.beginTransaction();
// 开启事务
tx.begin();
// 此时需要注意所查询实体类主键的类型,如果是Long类型,最好为1L
User user = session.get(User.class, 1);
// 输出结果:
// User [uid=1, username=martin_depp@126.com, password=martin0319, nickname=奔跑的小蚂蚁, birthday=1991-03-19 11:55:00.0, realname=孟祥杰]
System.out.println(user);
// 提交事务
tx.commit();
// 关闭 session
session.close();
}
}
3.3、更新操作
使用 Hibernate 更新数据,只需要调用 session 的 update() 方法,即可将 POJO 数据更新到数据库中。
package com.hibernate.test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import com.hibernate.domain.User;
import com.hibernate.utils.HibernateUtil;
public class TestHibernate {
@Test
public void testUpdate() {
// 获取 session 对象
Session session = HibernateUtil.openSession();
// 获取 Transaction 对象
Transaction tx = session.beginTransaction();
// 开启事务
tx.begin();
User user = session.get(User.class, 1);
user.setUsername("mengxiangjie2005@126.com");
session.update(user);
// 提交事务
tx.commit();
// 关闭 session
session.close();
}
}
3.4、删除操作
使用 Hibernate 保存数据,只需要调用 session 的 delete() 方法,即可将 POJO 从数据库中删除。
package com.hibernate.test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import com.hibernate.domain.User;
import com.hibernate.utils.HibernateUtil;
public class TestHibernate {
@Test
public void testDelete() {
// 获取 session 对象
Session session = HibernateUtil.openSession();
// 获取 Transaction 对象
Transaction tx = session.beginTransaction();
// 开启事务
tx.begin();
User user = session.get(User.class, 1);
session.delete(user);
// 提交事务
tx.commit();
// 关闭 session
session.close();
}
}
}
关于Hibernate学习1--SpringMVC+Hibernate集成环境搭建和spring springmvc hibernate框架搭建的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于10.31 springMVC 与 hibernate 配置、asp.net-mvc-3 – 没有使用asp mvc 3,nhibernate 3.2和spring.net 1.3.2绑定到线程异常的Hibernate Session、hibernate 学习笔记 01-- 在 eclipse 环境下搭建 hibernate 框架、Hibernate 学习笔记(一)—— Hibernate 概述和使用 Hibernate 进行简单的增删改查操作等相关知识的信息别忘了在本站进行查找喔。
本文标签: