`

异常:could not initialize proxy - the owning Session was closed

阅读更多

异常:could not initialize proxy - the owning Session was closed

其实这个异常写的非常之清楚,就是会话关闭,无法对Hibernate实体进行操作。造成这样的情况有很多,什么书写错误啊,逻辑错误啊。

但就此说一下关于lazy机制:

延迟初始化错误是运用Hibernate开发项目时最常见的错误。如果对一个类或者集合配置了延迟检索策略,那么必须当代理类实例或代理集合处于持久化状态(即处于Session范围内)时,才能初始化它。如果在游离状态时才初始化它,就会产生延迟初始化错误。

下面把Customer.hbm.xml文件的<class>元素的lazy属性设为true,表示使用延迟检索策略:

<class name="mypack.Customer" table="CUSTOMERS" lazy="true">

当执行Session的load()方法时,Hibernate不会立即执行查询CUSTOMERS表的select语句,仅仅返回Customer类的代理类的实例,这个代理类具由以下特征:

(1) 由Hibernate在运行时动态生成,它扩展了Customer类,因此它继承了Customer类的所有属性和方法,但它的实现对于应用程序是透明的。
(2) 当Hibernate创建Customer代理类实例时,仅仅初始化了它的OID属性,其他属性都为null,因此这个代理类实例占用的内存很少。
(3)当应用程序第一次访问Customer代理类实例时(例如调用customer.getXXX()或customer.setXXX()方法), Hibernate会初始化代理类实例,在初始化过程中执行select语句,真正从数据库中加载Customer对象的所有数据。但有个例外,那就是当应用程序访问Customer代理类实例的getId()方法时,Hibernate不会初始化代理类实例,因为在创建代理类实例时OID就存在了,不必到数据库中去查询。

提示:Hibernate采用CGLIB工具来生成持久化类的代理类。CGLIB是一个功能强大的Java字节码生成工具,它能够在程序运行时动态生成扩展 Java类或者实现Java接口的代理类。关于CGLIB的更多知识,请参考:http://cglib.sourceforge.net/

以下代码先通过Session的load()方法加载Customer对象,然后访问它的name属性:

tx = session.beginTransaction();
Customer customer=(Customer)session.load(Customer.class,new Long(1));
customer.getName();
tx.commit();

 

在运行session.load()方法时Hibernate不执行任何select语句,仅仅返回Customer类的代理类的实例,它的OID为1,这是由load()方法的第二个参数指定的。当应用程序调用customer.getName()方法时,Hibernate会初始化Customer代理类实例,从数据库中加载Customer对象的数据,执行以下select语句:

select * from CUSTOMERS where ID=1;
select * from ORDERS where CUSTOMER_ID=1;

当<class>元素的lazy属性为true,会影响Session的load()方法的各种运行时行为,下面举例说明。

1.如果加载的Customer对象在数据库中不存在,Session的load()方法不会抛出异常,只有当运行customer.getName()方法时才会抛出以下异常:

ERROR LazyInitializer:63 - Exception initializing proxy
net.sf.hibernate.ObjectNotFoundException: No row with the given identifier exists: 1, of class:
mypack.Customer

2.如果在整个Session范围内,应用程序没有访问过Customer对象,那么Customer代理类的实例一直不会被初始化,Hibernate不会执行任何select语句。以下代码试图在关闭Session后访问Customer游离对象:

tx = session.beginTransaction();
Customer customer=(Customer)session.load(Customer.class,new Long(1));
tx.commit();
session.close();
customer.getName();

 

由于引用变量customer引用的Customer代理类的实例在Session范围内始终没有被初始化,因此在执行customer.getName()方法时,Hibernate会抛出以下异常:

ERROR LazyInitializer:63 - Exception initializing proxy
net.sf.hibernate.HibernateException: Could not initialize proxy - the owning Session was closed

由此可见,Customer代理类的实例只有在当前Session范围内才能被初始化。

3.net.sf.hibernate.Hibernate类的initialize()静态方法用于在Session范围内显式初始化代理类实例,isInitialized()方法用于判断代理类实例是否已经被初始化。例如:

tx = session.beginTransaction();
Customer customer=(Customer)session.load(Customer.class,new Long(1));
if(!Hibernate.isInitialized(customer)) 
Hibernate.initialize(customer);
tx.commit();
session.close();
customer.getName();

 

以上代码在Session范围内通过Hibernate类的initialize()方法显式初始化了Customer代理类实例,因此当Session关闭后,可以正常访问Customer游离对象。

4.当应用程序访问代理类实例的getId()方法时,不会触发Hibernate初始化代理类实例的行为,例如:

tx = session.beginTransaction();
Customer customer=(Customer)session.load(Customer.class,new Long(1));
customer.getId();
tx.commit();
session.close();
customer.getName();

 

当应用程序访问customer.getId()方法时,该方法直接返回Customer代理类实例的OID值,无需查询数据库。由于引用变量 customer始终引用的是没有被初始化的Customer代理类实例,因此当Session关闭后再执行customer.getName()方法, Hibernate会抛出以下异常:

ERROR LazyInitializer:63 - Exception initializing proxy
net.sf.hibernate.HibernateException: Could not initialize proxy - the owning Session was closed


解决方法:

由于hibernate采用了lazy=true,这样当你用hibernate查询时,返回实际为利用cglib增强的代理类,但其并没有实际填充;当你在前端,利用它来取值(getXXX)时,这时Hibernate才会到数据库执行查询,并填充对象,但此时如果和这个代理类相关的session已关闭掉,就会产生种错误.
在做一对多时,有时会出现"could not initialize proxy - clothe owning Session was sed,这个好像是hibernate的缓存问题.问题解决:需要在<many-to-one>里设置lazy="false". 但有可能会引发另一个异常叫

failed to lazily initialize a collection of role: XXXXXXXX, no session or session was closed

此异常解决方案请察看本人博客(http://hi.baidu.com/kekemao1)的Hibernate异常中的《failed to lazily initialize a collection of role异常》

?
解决方法:在web.xml中加入

<filter>
    <filter-name>hibernateFilter</filter-name>
    <filter-class>
     org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    </filter-class>
</filter>
<filter-mapping>
    <filter-name>hibernateFilter</filter-name>
    <url-pattern>*.do</url-pattern>
</filter-mapping>

 

就可以了;

参考了:
Hibernate与延迟加载:

Hibernate对象关系映射提供延迟的与非延迟的对象初始化。非延迟加载在读取一个对象的时候会将与这个对象所有相关的其他对象一起读取出来。这有时会导致成百的(如果不是成千的话)select语句在读取对象的时候执行。这个问题有时出现在使用双向关系的时候,经常会导致整个数据库都在初始化的阶段被读出来了。当然,你可以不厌其烦地检查每一个对象与其他对象的关系,并把那些最昂贵的删除,但是到最后,我们可能会因此失去了本想在ORM工具中获得的便利。


一个明显的解决方法是使用Hibernate提供的延迟加载机制。这种初始化策略只在一个对象调用它的一对多或多对多关系时才将关系对象读取出来。这个过程对开发者来说是透明的,而且只进行了很少的数据库操作请求,因此会得到比较明显的性能提升。这项技术的一个缺陷是延迟加载技术要求一个Hibernate会话要在对象使用的时候一直开着。这会成为通过使用DAO模式将持久层抽象出来时的一个主要问题。为了将持久化机制完全地抽象出来,所有的数据库逻辑,包括打开或关闭会话,都不能在应用层出现。最常见的是,一些实现了简单接口的DAO实现类将数据库逻辑完全封装起来了。一种快速但是笨拙的解决方法是放弃DAO模式,将数据库连接逻辑加到应用层中来。这可能对一些小的应用程序有效,但是在大的系统中,这是一个严重的设计缺陷,妨碍了系统的可扩展性。

在Web层进行延迟加载

幸运的是,Spring框架为Hibernate延迟加载与DAO模式的整合提供了一种方便的解决方法。对那些不熟悉Spring与Hibernate集成使用的人,我不会在这里讨论过多的细节,但是我建议你去了解Hibernate与Spring集成的数据访问。以一个Web应用为例,Spring提供了OpenSessionInViewFilter和OpenSessionInViewInterceptor。我们可以随意选择一个类来实现相同的功能。两种方法唯一的不同就在于interceptor在Spring容器中运行并被配置在web应用的上下文中,而Filter在Spring之前运行并被配置在web.xml中。不管用哪个,他们都在请求将当前会话与当前(数据库)线程绑定时打开Hibernate会话。一旦已绑定到线程,这个打开了的Hibernate会话可以在DAO实现类中透明地使用。这个会话会为延迟加载数据库中值对象的视图保持打开状态。一旦这个逻辑视图完成了,Hibernate会话会在Filter的doFilter方法或者Interceptor的postHandle方法中被关闭。下面是每个组件的配置示例:

Interceptor的配置:

<beans> 
<bean id="urlMapping" 
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> 
<property name="interceptors"> 
<list> 
<ref bean="openSessionInViewInterceptor"/> 
</list> 
</property> 
<property name="mappings"> 

</bean> 

<bean name="openSessionInViewInterceptor" 
class="org.springframework.orm.hibernate.support.OpenSessionInViewInterceptor"> 
<property name="sessionFactory"><ref bean="sessionFactory"/></property> 
</bean> 
</beans>

 
Filter的配置

<web-app> 

<filter> 
<filter-name>hibernateFilter</filter-name> 
<filter-class> 
org.springframework.orm.hibernate.support.OpenSessionInViewFilter 
</filter-class> 
</filter> 

<filter-mapping> 
<filter-name>hibernateFilter</filter-name> 
<url-pattern>*. spring </url-pattern> 
</filter-mapping> 

</web-app>

 
实现Hibernate的Dao接口来使用打开的会话是很容易的。事实上,如果你已经使用了Spring框架来实现你的Hibernate Dao,很可能你不需要改变任何东西。方便的HibernateTemplate公用组件使访问数据库变成小菜一碟,而DAO接口只有通过这个组件才可以访问到数据库。下面是一个示例的DAO:

public class HibernateProductDAO extends HibernateDaoSupport implements ProductDAO {

public Product getProduct(Integer productId) { 
return (Product)getHibernateTemplate().load(Product.class, productId); 
}

public Integer saveProduct(Product product) { 
return (Integer) getHibernateTemplate().save(product); 
}

public void updateProduct(Product product) { 
getHibernateTemplate().update(product); 
} 
}

 
在业务逻辑层中使用延迟加载

即使在视图外面,Spring框架也通过使用AOP 拦截器 HibernateInterceptor来使得延迟加载变得很容易实现。这个Hibernate 拦截器透明地将调用配置在Spring应用程序上下文中的业务对象中方法的请求拦截下来,在调用方法之前打开一个Hibernate会话,然后在方法执行完之后将会话关闭。让我们来看一个简单的例子,假设我们有一个接口BussinessObject:

public     interface    BusinessObject     { 
public     void    doSomethingThatInvolvesDaos(); 
} 
类BusinessObjectImpl实现了BusinessObject接口:

public     class    BusinessObjectImpl    implements    BusinessObject     { 
public     void    doSomethingThatInvolvesDaos()     { 
//    lots of logic that calls 
//    DAO classes Which access 
//    data objects lazily  
}  
}  

 

通过在Spring应用程序上下文中的一些配置,我们可以让将调用BusinessObject的方法拦截下来,再令它的方法支持延迟加载。看看下面的一个程序片段:

<beans> 
<bean id="hibernateInterceptor" class="org.springframework.orm.hibernate.HibernateInterceptor"> 
<property name="sessionFactory"> 
<ref bean="sessionFactory"/> 
</property> 
</bean> 
<bean id="businessObjectTarget" class="com.acompany.BusinessObjectImpl"> 
<property name="someDAO"><ref bean="someDAO"/></property> 
</bean> 
<bean id="businessObject" class="org.springframework.aop.framework.ProxyFactoryBean"> 
<property name="target"><ref bean="businessObjectTarget"/></property> 
<property name="proxyInterfaces"> 
<value>com.acompany.BusinessObject</value> 
</property> 
<property name="interceptorNames"> 
<list> 
<value>hibernateInterceptor</value> 
</list> 
</property> 
</bean> 
</beans>

 

当businessObject被调用的时候,HibernateInterceptor打开一个Hibernate会话,并将调用请求传递给BusinessObjectImpl对象。当BusinessObjectImpl执行完成后,HibernateInterceptor透明地关闭了会话。应用层的代码不用了解任何持久层逻辑,还是实现了延迟加载。


在单元测试中测试延迟加载

最后,我们需要用J-Unit来测试我们的延迟加载程序。我们可以轻易地通过重写TestCase类中的setUp和tearDown方法来实现这个要求。我比较喜欢用这个方便的抽象类作为我所有测试类的基类。

 

public abstract class MyLazyTestCase extends TestCase {

private SessionFactory sessionFactory; 
private Session session;

public void setUp() throws Exception { 
super.setUp(); 
SessionFactory sessionFactory = (SessionFactory) getBean("sessionFactory"); 
session = SessionFactoryUtils.getSession(sessionFactory, true); 
Session s = sessionFactory.openSession(); 
TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(s));

}

protected Object getBean(String beanName) { 
//Code to get objects from Spring application context 
}

public void tearDown() throws Exception { 
super.tearDown(); 
SessionHolder holder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory); 
Session s = holder.getSession(); 
s.flush(); 
TransactionSynchronizationManager.unbindResource(sessionFactory); 
SessionFactoryUtils.closeSessionIfNecessary(s, sessionFactory); 
} 
}

  
 


答案一:

当<class>元素或者<set>元素的lazy属性为true时,load() or get() or find()加载这些对象时,Hibernate不会马上产生任何select语句,只是产生一个Obj代理类实例,只有在session没有关闭的情况下运行Obj.getXxx()时才会执行select语句从数据库加载对象,如果没有运行任何Obj.getXxx()方法,而session已经关闭,Obj已成游离状态,此时再运行Obj.getXxx()方法,Hibernate就会抛出"Could not initialize proxy - the owning Session was closeed"的异常,是说Obj代理类实例无法被初始化。然而想在Session关闭之前不调用Obj.getXxx()方法而关闭Session之后又要用,此时只要在Session关闭之前调用Hibernate.initialize(Obj)或者Hibernate.initialize(Obj.getXxx())即可,net.sf.hibernate.Hibernate类的initialize()静态方法用于在Session范围内显示初始化代理类实例。

答案二:

抛出这个错误的主要原因我觉得并不是由于Session没有关闭造成的,这种问题我也遇到过,不过原因说不是很清楚,我用的hibernate3.0的lazy默认好像是true这个原因是没有初始化造成的,可以在session.close()之前把customer的一个属性输出来试一试,或者用Hibernate.initialize初始化,在或者干脆把lazy改为false行了。

错误1、出现对象名 '×××(表名)' 无效错误。
原因:可能是由于你在配置文件中写数据库连接url时没有写明所要连接的数据库。
现在将各种驱动连接总结如下:


1. MySQL(http://www.mysql.com)mm.mysql-2.0.2-bin.jar
Class.forName( "org.gjt.mm.mysql.Driver" );
cn = DriverManager.getConnection( "jdbc:mysql://MyDbComputerNameOrIP:3306/myDatabaseName", sUsr, sPwd );

2. PostgreSQL(http://www.de.postgresql.org)pgjdbc2.jar
Class.forName( "org.postgresql.Driver" );
cn = DriverManager.getConnection( "jdbc:postgresql://MyDbComputerNameOrIP/myDatabaseName", sUsr, sPwd );

3. Oracle(http://www.oracle.com/ip/deploy/database/oracle9i/)classes12.zip
Class.forName( "oracle.jdbc.driver.OracleDriver" );
cn = DriverManager.getConnection( "jdbc:oracle:thin:@MyDbComputerNameOrIP:1521:ORCL", sUsr, sPwd );

4. Sybase(http://jtds.sourceforge.net)jconn2.jar
Class.forName( "com.sybase.jdbc2.jdbc.SybDriver" );
cn = DriverManager.getConnection( "jdbc:sybase:Tds:MyDbComputerNameOrIP:2638", sUsr, sPwd );
//(Default-Username/Password: "dba"/"sql")

5. Microsoft SQLServer(http://jtds.sourceforge.net)
Class.forName( "net.sourceforge.jtds.jdbc.Driver" );
cn = DriverManager.getConnection( "jdbc:jtds:sqlserver://MyDbComputerNameOrIP:1433/master", sUsr, sPwd );

6. Microsoft SQLServer(http://www.microsoft.com)
Class.forName( "com.microsoft.jdbc.sqlserver.SQLServerDriver" );
cn = DriverManager.getConnection( "jdbc:microsoft:sqlserver://MyDbComputerNameOrIP:1433;databaseName=master", sUsr, sPwd );

7. ODBC
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
Connection cn = DriverManager.getConnection( "jdbc:odbc:" + sDsn, sUsr, sPwd );

8.DB2(新添加)
Class.forName("com.ibm.db2.jdbc.net.DB2Driver");
String url="jdbc:db2://192.9.200.108:6789/SAMPLE"
cn = DriverManager.getConnection( url, sUsr, sPwd );

补充
Microsoft SQL Server series (6.5, 7.x and 2000) and Sybase 10

JDBC Name: jTDS
URL: http://jtds.sourceforge.net/
Version: 0.5.1
Download URL: http://sourceforge.net/project/showfiles.php?group_id=33291

语法:

Class.forName("net.sourceforge.jtds.jdbc.Driver ");
Connection con = DriverManager.getConnection("jdbc:jtds:sqlserver://host:port/database","user","password");
or
Connection con = DriverManager.getConnection("jdbc:jtds:sybase://host:port/database","user","password");
Postgresql

JDBC Name: PostgreSQL JDBC
URL: http://jdbc.postgresql.org/
Version: 7.3.3 build 110
Download URL: http://jdbc.postgresql.org/download.html

语法:

Class.forName("org.postgresql.Driver");
Connection con=DriverManager.getConnection("jdbc:postgresql://host:port/database","user","password");


IBM AS400主机在用的JDBC语法

有装V4R4以上版本的Client Access Express
可以在C:\Program Files\IBM\Client Access\jt400\lib
找到 driver 档案 jt400.zip,并更改扩展名成为 jt400.jar

语法

java.sql.DriverManager.registerDriver (new com.ibm.as400.access.AS400JDBCDriver ());
Class.forName("com.ibm.as400.access.AS400JDBCConnection");
con = DriverManager.getConnection("jdbc:as400://IP","user","password");

informix

Class.forName("com.informix.jdbc.IfxDriver").newInstance();

String url =

"jdbc:informix-sqli://123.45.67.89:1533/testDB:INFORMIXSERVER=myserver;

user=testuser;password=testpassword";


Lib:jdbcdrv.zip<br><br>Class.forName( "com.sybase.jdbc.SybDriver" )<br>url="jdbc:sybase:Tds:127.0.0.1:2638/asademo";<br>SybConnection connection= (SybConnection)DriverManager.getConnection(url,"dba","sql");<br>


补充两个
SAP DB
Class.forName ("com.sap.dbtech.jdbc.DriverSapDB");
java.sql.Connection connection = java.sql.DriverManager.getConnection ( "jdbc:sapdb://" + host + "/" + database_name,user_name, password)

InterBase
String url = "jdbc:interbase://localhost/e:/testbed/database/employee.gdb";
Class.forName("interbase.interclient.Driver");
//Driver d = new interbase.interclient.Driver (); /* this will also work if you do not want the line above */
Connection conn = DriverManager.getConnection( url, "sysdba", "masterkey" );

我也来补一个吧:HSqlDB

url:     http://hsqldb.sourceforge.net/
driver:  org.hsqldb.jdbcDriver

连接方式有4种,分别为:
con-str(内存): jdbc:hsqldb.
con-str(本地): jdbc:hsqldb:/path/to/the/db/dir
con-str(http): jdbc:hsqldb:http://dbsrv
con-str(hsql): jdbc:hsqldb:hsql://dbsrv


错误2、Caused by: java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]Can't start a cloned connection while in manual transaction mode. 
原因:你在尝试打开一个克隆连接,
有两种解决办法: 每个数据库的连接在执行完毕后,关闭,
第二,在连接时,判断是否已经有连接存在,有则使用现成的连接。

也可以在连接字符串中加入SelectMethod=cursor,即写成这样:“jdbc:microsoft:sqlserver://localhost:1433;SelectMethod=cursor;DatabaseName=bugzero_db”

或者改用
Microsoft SQLServer(http://jtds.sourceforge.net)
Class.forName( "net.sourceforge.jtds.jdbc.Driver" );
cn = DriverManager.getConnection( "jdbc:jtds:sqlserver://MyDbComputerNameOrIP:1433/master", sUsr, sPwd );

Hibernate常见错误:
Caused by: org.dom4j.DocumentException: Invalid byte 2 of 2-byte UTF-8 sequence. Nested exception: Invalid byte 2 of 2-byte UTF-8 sequence.
如果出现这行错误说明你的xml配置文件有不规范的字符,检查下。

net.sf.hibernate.MappingException: Error reading resource: hibernate/Hello_Bean.hbm.xml


如果出现这行错误说明你的hibernate的XML配置文件有错\r

net.sf.hibernate.MappingException: Resource: hibernate/Hello_Bean.hbm.xml not found


如果出现这行错误说明hibernate的XML配置文件没有找到,你应该把XML文件放在与你的类文件同个目录下,本文中是放在hibernate\classes\hibernate\目录下,也就是跟Hello_Bean.class类文件一起。

net.sf.hibernate.PropertyNotFoundException: Could not find a setter for property name in class hibernate.Hello_Bean


如果出现这行错误说明你的xml文件里设置的字段名name的值与Hello_Bean.java类里的getXXX或setXXX方法不一致。

net.sf.hibernate.HibernateException: JDBC Driver class not found: org.gjt.mm.mysql.Driver
如果出现这行错误说明你的MYSQL驱动没有加进JB库里或者不在CLASSPATH里。

no bean specialed.
出错了,jsp页面报错。
原因是html:select 标签 中 option bean is null/.

Set不能加同一实体
在保存数据的时候循环添加一PO数据到Set,居然最后Set的size()为1。各实体设置不同数据啊,只是没Id.
原因是这个PO以前自己实现了Comparable .只比较Id,

HibernateSystemException: SQL insert,update or delete failed
hibernate级联保存或更新时可能会出这个错误
原因是由于子实体的主键设置了不符合保存更新的数据.

No persister for错误
这个错误说的是no persister for java.lang.Integer;
映射文件未添加肯定不是这个问题了。
那只有映射文件出错。
锁定了关联的id;
PO里面写的关联ID,而建表看不出问题。而且映射文件里面基本上看不出来。
出现No persister for错误后一般是3个情况:
1hbm.xml文件特殊类未制定类型。
2cfg.xml文件未添加类的hbm.xml文件名。
3PO和 hbm类映射不匹配。 

net.sf.hibernate.LazyInitializationException: Failed to lazily initialize a collection - no session or session was closed
hibernate最常见错误.
Lazy为true
session关闭后调用延迟加载属性.

在session关闭之前如果调用该属性,会加载.
或者是使用Hibernate.Initalize();

BigDecimal对象属性映射出错
这个问题是不小心造成的.
属性映射应该加上 length="2"指定2位小数,或者几位小数,小数位数在0-19之间

property value with CGLIB 错误
比较常见的hibernate错误了.
当PO属性为原始类型(int,double...)时,数据库纪录为null,调出PO时由于这些属性必须有值而出现错误.

把属性值设置为对象属性解决.

hibernate出错
在configure.buildSessionFactory()时java.nullpointException.
在eclipse里没问题,但部署在tomcat里就出问题了,
是由于包冲突了。
还有个可能就是configure(path),path不对。

是由于eclipse的class loader和tomcat不同,在tomcat里,不能有两个一样一起加载。
eclipse里却是指定jar的。

 

常见错误:
Caused by: org.dom4j.DocumentException: Invalid byte 2 of 2-byte UTF-8 sequence. Nested exception: Invalid byte 2 of 2-byte UTF-8 sequence.

如果出现这行错误说明你的xml配置文件有不规范的字符,检查下。

net.sf.hibernate.MappingException: Error reading resource: hibernate/Hello_Bean.hbm.xml


如果出现这行错误说明你的hibernate的XML配置文件有错

net.sf.hibernate.MappingException: Resource: hibernate/Hello_Bean.hbm.xml not found


如果出现这行错误说明hibernate的XML配置文件没有找到,你应该把XML文件放在与你的类文件同个目录下,本文中是放在hibernate\classes\hibernate\目录下,也就是跟Hello_Bean.class类文件一起。

net.sf.hibernate.PropertyNotFoundException: Could not find a setter for property name in class hibernate.Hello_Bean


如果出现这行错误说明你的xml文件里设置的字段名name的值与Hello_Bean.java类里的getXXX或setXXX方法不一致。

net.sf.hibernate.HibernateException: JDBC Driver class not found: org.gjt.mm.mysql.Driver
如果出现这行错误说明你的MYSQL驱动没有加进JB库里或者不在CLASSPATH里。
调试出现 net.sf.hibernate.MappingException 很有可能是由于
类库文件没有找到,类库的版本不同,他的名字会不同 要重新配置 setenv.bat
类库的路径。

 

 

自己遇到的hibernate常见错误
1>

错误显示: net.sf.hibernate.PropertyValueException: not-null property references a null or transient value: com.Order.customer

部分原文件:( customer 和 order 类关系:一对多关联)

Order.hbm.xml …………… < many-to-one         name = "customer"         column = "CUSTOMER_ID"         class = "com.Customer"         not-null = "true"         cascade = "save-update"            /> 执行文件:
………

Session session = sessionFactory.openSession();

    Transaction tx = null;

    try {

      // Create some data and persist it

     tx = session.beginTransaction();

 
     Customer customer=new Customer();

     customer.setName("Jack");

    

     Order order=new Order();

     order.setOrderNumber("Jack_Order001");

         session.save(customer);

         session.save(order);

   tx.commit();

原因分析:因为在执行代码中,没有将 customer 和 order 类一对多关联起来,若单独持久化两个类: session.save(customer);session.save(order); 则在保存 order 的时候,由于 CUSTOMER_ID是与 customer类外键,因此无法读取 customer_id, 而在 order.hbm.xml 中指定其不为空,则产生了以上错误。

问题解决: not-null = "true" 改为:not-null="false" 虽然程序无问题,但order表 CUSTOMER_ID为空,不符合逻辑。应该将指定其一对多的关联。 order.setCustomer(customer);       customer.getOrders().add(order);   2〉 错误显示: RROR SessionImpl:2400 - Could not synchronize database state with session net.sf.hibernate.exception.GenericJDBCException: could not delete collection: [com.Customer.orders#2]
部分原文件:

Session session = sessionFactory.openSession();

    Transaction tx = null;

    try {

      tx = session.beginTransaction();

      Customer customer=(Customer)session.load(Customer.class,new Long(3));

      session.delete(customer);

      tx.commit();

原因分析:因为 cascade默认值为 none,所以当删除customer时,不会自动删除与其关联的order对象。 问题解决:添加语句 cascade = "delete"   3>
错误显示:

17:24:34,992 ERROR JDBCExceptionReporter:58 - [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]在关键字 'ORDER' 附近有语法错误。 17:24:34,992  WARN JDBCExceptionReporter:57 - SQL Error: 156, SQLState: HY000 17:24:35,002 ERROR JDBCExceptionReporter:58 - [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]在关键字 'ORDER' 附近有语法错误。 17:24:35,022  WARN JDBCExceptionReporter:34 - SQL Warning: 0, SQLState: net.sf.hibernate.exception.GenericJDBCException : could not initialize collection: [com.Customer.orders#2]
部分原文件: order.hbm.xml

< hibernate-mapping >   < class name = "com.Order" table = "ORDER" >      < id name = "id" type = "long" column = "ID" >         < generator class = "increment" />       </ id >    < property name = "orderNumber" type = "string" >         < column name = "ORDER_NUMBER" length = "15" />       </ property >             < many-to-one         name = "customer"         column = "CUSTOMER_ID"         class = "com.Customer"         outer-join = "true"          />
原因分析:因为 order 表在 SQL 2000 数据库中已经定义了,如果用户在定义了 order 表,并且程序对该表进行连接等操作就会出错

问题解决:将 引用 order 处改为 [order]

< class name = "com.Order" table = "[ORDER]" >   4> net.sf.hibernate.exception.SQLGrammarException : Could not save object     at net.sf.hibernate.exception.SQLStateConverter.convert( SQLStateConverter.java:58 )     at net.sf.hibernate.exception.JDBCExceptionHelper.convert( JDBCExceptionHelper.java:29 )     at net.sf.hibernate.impl.SessionImpl.convert( SessionImpl.java:4131 )     at net.sf.hibernate.impl.SessionImpl.saveWithGeneratedIdentifier( SessionImpl.java:794 )     at net.sf.hibernate.impl.SessionImpl.save( SessionImpl.java:749 )     at com.BusinessService.saveCategoryWithCascade( BusinessService.java:54 )     at com.BusinessService.test( BusinessService.java:104 )     at com.BusinessService.main( BusinessService.java:109 ) Caused by: java.sql.SQLException : [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]对象名 'CATEGORIES' 无效。 5〉
错误显示: net.sf.hibernate.MappingException : Resource: Add valid path not found

部分原文件: hibernate.hbm.xml

< hibernate-configuration >   < session-factory >     < property name = "connection.username" > sa </ property >     < property name = "connection.url" > jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=test </ property >     < property name = "dialect" > net.sf.hibernate.dialect.SQLServerDialect </ property >     < property name = "myeclipse.connection.profile" > MSSQL </ property >     < property name = "connection.password" > hheryh </ property >     < property name = "connection.driver_class" > com.microsoft.jdbc.sqlserver.SQLServerDriver </ property >     < mapping resource = "Add valid path" /> </ session-factory >
原因分析:找不到有效的 xml 文件

问题解决:将所有配置文件都加到 resource 里

将< mapping resource = "Add valid path" />改为 < mapping resource = "com/Customer.hbm.xml" /> < mapping resource = "com/Order.hbm.xml" /> 6〉 错误显示 net.sf.hibernate.MappingException : Error reading resource: com/Customer.hbm.xml     at net.sf.hibernate.cfg.Configuration.addResource( Configuration.java:340 )     at net.sf.hibernate.cfg.Configuration.doConfigure( Configuration.java:1027 )     at net.sf.hibernate.cfg.Configuration.doConfigure( Configuration.java:983 )     at net.sf.hibernate.cfg.Configuration.configure( Configuration.java:911 )     at net.sf.hibernate.cfg.Configuration.configure( Configuration.java:897 )     at com.BusinessService.<clinit>( BusinessService.java:17 ) Caused by: net.sf.hibernate.MappingException : duplicate import: Customer     at net.sf.hibernate.cfg.Mappings.addImport( Mappings.java:85 )     at net.sf.hibernate.cfg.Binder.bindClass( Binder.java:126 )     at net.sf.hibernate.cfg.Binder.bindRootClass( Binder.java:221 )     at net.sf.hibernate.cfg.Binder.bindRoot( Binder.java:1256 )     at net.sf.hibernate.cfg.Configuration.add( Configuration.java:253 )     at net.sf.hibernate.cfg.Configuration.addInputStream( Configuration.java:289 )     at net.sf.hibernate.cfg.Configuration.addResource( Configuration.java:337 )     ... 5 more 部分原文件 :hibernate.hbm.xml <? xml version = '1.0' encoding = 'UTF-8' ?> <! DOCTYPE hibernate-configuration PUBLIC           "-//Hibernate/Hibernate Configuration DTD 2.0//EN"           "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd" >   <!-- Generated by MyEclipse Hibernate Tools.                   --> < hibernate-configuration >   < session-factory >     < property name = "connection.username" > sa </ property >     < property name = "connection.url" > jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=test </ property >     < property name = "dialect" > net.sf.hibernate.dialect.SQLServerDialect </ property >     < property name = "myeclipse.connection.profile" > MSSQL </ property >     < property name = "connection.password" > hheryh </ property >     < property name = "connection.driver_class" > com.microsoft.jdbc.sqlserver.SQLServerDriver </ property >     < mapping resource = "com/Customer.hbm.xml" /> </ session-factory >   </ hibernate-configuration >  
主程序:

static{

     try{

      // Create a configuration based on the properties file we've put

       Configuration config = new Configuration();

       config.addClass(Customer.class);

      // Get the session factory we can use for persistence

      sessionFactory = config

      .configure()

      .buildSessionFactory();

    }catch(Exception e){e.printStackTrace();}

 
  }

解决方法: config.addClass(Customer.class);
sessionFactory = config.configure().buildSessionFactory();

原因分析: hibernaet 配置文件有两种格式,一种是 xml 格式,一种是普通的 .property 格式 .

在 1.2 版本中,编译时自动会在 path 路径中查找 property 格式的配置文件。但不会查询 xml 格式的配置文件,因此需要在程序中手动添加 config.configure() ,但此时就不要加载了。

上面的程序 加载了一次 config.configure() ,又映射了一次,所以出错。

 
解决方法:

若配置文件为 xml 格式的,程序编写如下:

// Create a configuration based on the properties file we've put

       Configuration config = new Configuration();

             // Get the session factory we can use for persistence

      sessionFactory = config

      .configure()

.buildSessionFactory();

 
若配置文件为 property 格式的,程序编写如下:

// Create a configuration based on the properties file we've put

       Configuration config = new Configuration();

       config.addClass(Customer.class);

      // Get the session factory we can use for persistence

      sessionFactory = config.buildSessionFactory();


hibernate常见错误及解决方法
hibernate 的自动生成工具
class,?mapping?file?and?DDL
1.?Middlegen
是用来从DB中已存在的表,生成相应的mapping?file.?可以下载一个老外的middlegen的例子。
http://sourceforge.net/project/showfiles.php?group_id=40712
调用Middlegen很简单,例子中的middlegen自动生成ant指令如下
?????????appname="${name}"
?????????prefsdir="${src.dir}"
?????????gui="${gui}"
?????????databaseurl="${database.url}"
?????????initialContextFactory="${java.naming.factory.initial}"
?????????providerURL="${java.naming.provider.url}"
?????????datasourceJNDIName="${datasource.jndi.name}"
?????????driver="${database.driver}"
?????????username="${database.userid}"
?????????password="${database.password}"
?????????
??????>
?????????????????destination="${build.gen-src.dir}"
????????????package="${name}.hibernate"
??????/>
??
然后会有一个GUI,给我们专门设计各种表与表之间的关系(一对一,一对多以及单向双向关系)。需要说明的是,middlegen生成的代码没有直接写mapping?file灵活性好,所以生成的mapping?file有时还需要我们去修改。
2.?XDoclet
它是用来从java文件自动生成hbm文件的,不过我们需要在java代码中写一些规定的tag,才能得到自动生成的hbm文件.
??????????destdir="src"
??????????excludedtags="@version,@author,@todo"
??????????force="true"
??????????verbose="true">
??????????
??????????????
??????
??????bobomail 阅读(744) 评论(20) 编辑收藏 收藏至365Key
评论
#re: hibernate 的自动生成工具 2005-04-30 16:43 caravarn
大内高手
Java到.NET的转换利器——JLCA
JLCA(Java Language Conversion Assistant)是VS.NET中内置的一套Java语言到.NET语言的转换工具,对于有这样需求的开发团队而言,这是一篇不可不读的文章。
OptimalJ实现MDA的实践
OptimalJ是另一个重量级的MDA工具。虽然OptimalJ目前只支持Java的MDA变换,但是其独树一帜的设计思想,仍然值得我们好好学习。
#re: hibernate 的自动生成工具 2005-08-10 14:11 bobo
一个不错的德jsp 分页工具的讨论
http://www.md.jxufe.cn/blog1/more.asp?name=xiaohuakai&id=406
#re: hibernate 的自动生成工具 2005-08-10 14:48 bobo
hibernate 分页工具的讨论
http://dev.csdn.net/develop/article/20/20764.shtm
#re: hibernate 的自动生成工具 2005-08-10 16:18 伯伯
hibernate 工具的介绍http://dev.csdn.net/article/71/71115.shtm
#re: hibernate 的自动生成工具 2005-08-11 14:51 caravarn
MiddleGen 工具介绍
http://dev.csdn.net/develop/article/53/53412.shtm
#re: hibernate 的自动生成工具 2005-08-11 17:01 caravarn
hibernate 库更新列表
http://prdownloads.sourceforge.net/hibernate/?sort_by=date&sort=desc
#re: hibernate 的自动生成工具 2005-08-15 18:10 caravarn
常见错误:
Caused by: org.dom4j.DocumentException: Invalid byte 2 of 2-byte UTF-8 sequence. Nested exception: Invalid byte 2 of 2-byte UTF-8 sequence.
如果出现这行错误说明你的xml配置文件有不规范的字符,检查下。
net.sf.hibernate.MappingException: Error reading resource: hibernate/Hello_Bean.hbm.xml
如果出现这行错误说明你的hibernate的XML配置文件有错
net.sf.hibernate.MappingException: Resource: hibernate/Hello_Bean.hbm.xml not found
如果出现这行错误说明hibernate的XML配置文件没有找到,你应该把XML文件放在与你的类文件同个目录下,本文中是放在hibernateclasseshibernate目录下,也就是跟Hello_Bean.class类文件一起。
net.sf.hibernate.PropertyNotFoundException: Could not find a setter for property name in class hibernate.Hello_Bean
如果出现这行错误说明你的xml文件里设置的字段名name的值与Hello_Bean.java类里的getXXX或setXXX方法不一致。
net.sf.hibernate.HibernateException: JDBC Driver class not found: org.gjt.mm.mysql.Driver
如果出现这行错误说明你的MYSQL驱动没有加进JB库里或者不在CLASSPATH里。
#re: hibernate 的自动生成工具 2005-08-15 18:56 caravarn
调试出现 net.sf.hibernate.MappingException 很有可能是由于
类库文件没有找到,类库的版本不同,他的名字会不同 要重新配置 setenv.bat
类库的路径。
#re: hibernate 的自动生成工具 2005-08-15 19:16 caravarn
[ERROR] CodeGenerator - Error parsing XML: file:/C:/projects/hibernate/javasampl
e/(1) DOCTYPE root "null".>org.xml.sax.SAXParseException: Document root element "title
", must match DOCTYPE root "null".
生成文件的路径不对
#re: hibernate 的自动生成工具 2005-08-16 14:06 caravarn
Middlegen 工具 Hibernate辅助工具的功能,方便开发
#re: hibernate 的自动生成工具 2005-08-16 14:06 caravarn
http://www.matrix.org.cn/resource/article/1/1639_Hibernate-Script.html
#re: hibernate 的自动生成工具 2005-08-17 13:45 caravarn
Middlegen工具 连接数据库把数据结构导为 hbm2.xml 文件
Middlegen-Hibernate-r5configdatabase
mysql.xml 修改 数据库的连接文件
修改 Middlegen-Hibernate-r5uilder.xml 文件
执行ant 会出现 gui 的界面
#re: hibernate 的自动生成工具 2005-08-17 16:15 caravarn
hbm2java 配置 build.xml 文件
可以参考的文档
http://www.wnetw.com/jclub/technology/read.jsp?itemid=484
源文件路径
.........
........
.....
classname="net.sf.hibernate.tool.hbm2java.Hbm2JavaTask"
classpathref="project.class.path"/>
--任务名称
-- 源文件目录
--输出目录
 


spring常见错误分析现象1:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ''org.springframework.aop.support.DefaultPointcutAdvisor'' defined in null: Can''t resolve reference to bean ''txAdvice'' while setting property ''advice''; nested exception is
原因:缺少Spring开头的各种包,到Spring2.0 src中编译新的dist目录出来,拷贝全部的springxxx.jar到jpetstore/WEB-INF/lib下。OK。
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
现象2:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ''sessionFactory'' defined in resource [/WEB-INF/dataAccessContext-hibernate.xml] of ServletContext: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: javax/transaction/TransactionManager
java.lang.NoClassDefFoundError: javax/transaction/TransactionManager
原因:缺少jta.jar,OK
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
现象3:
java.lang.NoClassDefFoundError: org/dom4j/Attribute缺dom4j.jar
java.lang.NoClassDefFoundError: net/sf/ehcache/CacheException
缺ehcache.jar
java.lang.NoClassDefFoundError: net/sf/cglib/core/KeyFactory
缺cglib-full.jar
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
现象4:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ''sessionFactory'' defined in resource [/WEB-INF/dataAccessContext-hibernate.xml] of ServletContext: Initialization of bean failed; nested exception is net.sf.hibernate.MappingException: could not instantiate id generator
net.sf.hibernate.MappingException: could not instantiate id generator
原因:
hbm中id字段的定义为没有定义的sequesce,修改为inc
name="id"
type="string"
column="userid"
>
// 原来是sequence.
这样就可以了。
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
现象6:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ''/shop/addItemToCart.do'' defined in ServletContext resource [/WEB-INF/petstore-servlet.xml]: Can''t resolve reference to bean ''petStore'' while setting property ''petStore''; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ''petStore'' is defined
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ''petStore'' is defined原因:
我使用Struts作为action,当然就不需要使用Spring WEB framework,因此也不需要与之配套的配置文件例如,petstore-servlet.xml,
还有remote-servlet.xml ,但是Spring仍旧加载此两个文件,没办法,只好将此两个文件挪动到别的地方,但是又出现找不到这两个
文件的IO异常,没办法,只好又拷贝回来,然后把文件内容晴空。
终于好用了。
原因就是,只要你在web.xml中定义了这个servlet,他就要去找此servlet名字对应的配置文件(servletname-servlet.xml),找不到就出错。ok,现在注释掉web.xml中名字为petstore的servlet定义和影色,删除petstore-servlet.xml文件,哈哈,这下不报告错误了。
同理,注释名字为remote的servlet,删除remote-servlet.xml后,重新启动tomcat,这下不报告任何错误了。呵呵。原来如此啊。
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
现象:
java.lang.NullPointerException
srx.test.testhibernate.UserDAO.getAll(UserDAO.java:9)
srx.test.struts.action.UserAction.execute(UserAction.java:20)原因:
Action原来
UserDAO // 这个类OK
public class UserDAO extends HibernateDaoSupport {
public List getAll() {
return this.getHibernateTemplate().find("select aa from Account aa");
}
}
//这个类需要修改
public class UserAction extends ActionSupport {
UserDAO dao = new UserDAO();
List accounts = dao.getAll();
。。。
}
修改:
//UserDAO dao = new UserDAO(); WebApplicationContext wac = this.getWebApplicationContext();
UserDAO dao = (UserDAO) wac.getBean("userDAO"); 


Tags: Spring  error  Hibernate  struts 

原创文章如转载,请注明:转载自:飞扬部落编程仓库 : http://www.busfly.cn/csdn/

本文链接地址:http://www.busfly.cn/csdn/post/612.html

如果你喜欢本文,请顶一下,支持我,你的支持是我继续发好文章的最大动力。谢谢。
好东西需要分享,快把本文发给你的朋友吧~!~

     

hibernate的常见错误解决方法示例!!!
1、
org.springframework.orm.ObjectRetrievalFailureException: Object of class [com.xindeco.myregister.pojo.MyRegisterInfo] with identifier [14]: not found
MyRegisterInfo在数据库没有identifier [14]对象。
2、
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Initialization of bean failed; nested exception is org.hibernate.MappingException: Repeated column in mapping for entity: com.xindeco.myregister.pojo.MyRegisterInfo column: password (should be mapped with insert="false" update="false")
出错原因:password 和repassword同时对应数据库表中的password一列,同时update和insert都设为true。
xml文件如下:
    <property name="password"
                          type="java.lang.String"
                          update="true"
                          insert="true"
                          access="property"
                          column="password"
                          length = "32"
                          />

                         <property name="repassword"
                          type="java.lang.String"
                          update="false"
                          insert="false"
                          access="property"
                          column="password"
                          length = "32"
                          />
解决的方法:
将repassword的insert和update设为false。
3、
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Initialization of bean failed;
nested exception is org.hibernate.PropertyNotFoundException: Could not find a getter for ID in class
错误原因:hibernate的映射文件中ID是大写的,而pojo的类中id是小写的
注意事项:每个pojo的类都要继承abstractEntity,其中abstractEntity类有个ID的属性要重写
public abstract class AbstractEntity
    implements Entity, BaseDTO {
    abstract public long getID();
    abstract public void setID(long id);
    public int hashCode() {
        return (int)this.getID();
    }
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (obj instanceof Entity) {
            return this.getID() == ( (Entity) obj).getID();
        }
        return false;
    }
}
4、
org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.NEVER) - turn your Session into FlushMode.AUTO or remove 'readOnly' marker from transaction definition
错误原因:
在application.xml文件中deleteRegister方法以delete开头,并没有被设定为可更改的,应如下设置:
<!--为事物创建代理类,并指定方法的事物类型-->
<bean id="baseTxProxy" lazy-init="true" abstract="true" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
    <property name="transactionManager">
      <ref bean="transactionManager"/>
    </property>
    <property name="transactionAttributes">
      <props>
        <prop key="add*">PROPAGATION_REQUIRED</prop>
        <prop key="cancel*">PROPAGATION_REQUIRED</prop>
           </props>
    </property>
</bean>
加上一行
<prop key="delete*">PROPAGATION_REQUIRED</prop>
5、
   ERROR org.apache.struts.util.RequestUtils - Error creating form bean of class com.xindeco.business.web.form.GraAppInfoForm
public class GraAppInfoForm
extends ActionForm 错误写成
public abstratic class GraAppInfoForm
extends ActionForm
6、
2006-04-25 08:56:38,495 ERROR com.xindeco.business.web.action.GraAppAction - com.xindeco.business.web.action.GraAppAction@8e2fb5
java.lang.ClassCastException: $Proxy0
at com.xindeco.business.web.action.GraAppAction.newone(GraAppAction.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:274)
at com.xindeco.core.web.action.BaseAction.dispatchMethod(BaseAction.java:153)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:194)
actioin类中的newone方法如下:
public class GraAppAction
    extends BaseAction {
    public ActionForward newone(ActionMapping mapping, ActionForm form,
                              HttpServletRequest request,
                              HttpServletResponse response) throws Exception {
       GraAppService graservice = (GraAppService) this.getBean("GraAppService");
}
applicationcontext中的GraAppService的配置如下:
    <bean id="GraAppDAO" class="com.xindeco.business.dao.impl.GraAppDAOImpl">
    <property name="support">
      <ref local="support"/>
    </property>
    <property name="sessionFactory">
      <ref local="sessionFactory"/>
    </property>
</bean>
<bean id="GraAppService" parent="baseTxProxy">
    <property name="target">
      <bean class="com.xindeco.business.service.impl.GraAppServiceImpl" autowire="byName">
        <property name="baseDAO">
          <ref bean="GraAppDAO"/>
        </property>
      </bean>
    </property>
</bean>
因此this.getBean("GraAppService");是为了得到GraAppServicImpl类的实现。GraAppService是interface
public class GraAppServiceImpl extends BaseServiceImpl
    implements GraAppService{
}
7、org.hibernate.hql.ast.QuerySyntaxException: Demand is not mapped. [from Demand where unitid = ? and needNum > usedNeedNum]
hibernate.cfg.xml没有配置Demand.hbm.xml文件的目录
8、org.springframework.jdbc.BadSqlGrammarException: Bad SQL grammar [] in task 'Hibernate operation'; nested exception is java.sql.SQLException: 列名 'id' 无效。
java.sql.SQLException: 列名 'name' 无效。
因为hibernate声明的id,name的columnid属性没有与数据库的字段对应,所以id,name无效。
9、java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:415)
at java.lang.Integer.parseInt(Integer.java:497)
at com.xindeco.business.service.impl.DemandServiceImpl.findDemandListByUnitId(DemandServiceImpl.java:33)
错误语句为
needNum = Integer.parseInt(demand.getNeedNum());
usedNeedNum = Integer.parseInt(demand.getUsedNeedNum());
因为demand.getUsedNeedNum()==null,无法转化为string 类型,
10、rg.apache.jasper.JasperException: /GraAppInfo/GraAppInfoNew.jsp(343,29) According to TLD, tag bean:write must be empty, but is not
错误的原因:
       <select name="politicsID" >
             <option value="">请选择</option>
       <logic:notEmpty name="politicsList">
                <logic:iterate id="politics" name="politicsList">
       </logic:notEmpty>
       <option value="<bean:write name="politics" property="codeID"/>"><bean:write name="politics" property="codeName"/></option>
       </logic:iterate>
</select>
就因为少了/>
以后懂得通过查找字数,来检查错误
11、2006-04-26 13:27:54,812 ERROR com.xindeco.core.util.BeanUtils - bean property [Nation] copy failed
com.xindeco.core.exception.ConvertException: org.springframework.orm.hibernate3.HibernateSystemException: Unknown entity: java.lang.String; nested exception is org.hibernate.MappingException: Unknown entity: java.lang.String
beanUtil.beanCopy(grapojo,form,BizConstants.CONVERTER);
要求:
1、pojo类的属性只有与form属性名字相同,才能beancopy成功
2、pojo中属性是实体,在form中一定要用int,long表示
出现这错误的原因是pojo中的属性不是实体,而错误写成:
string
private String nation;应改成 private Syscode nation;
12、
2006-04-26 14:38:37,843 ERROR com.xindeco.business.web.action.GraAppAction - com.xindeco.business.web.action.GraAppAction@fa1b2d
java.lang.NullPointerException
at com.xindeco.business.web.action.GraAppAction.newone(GraAppAction.java:43)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
hibernate配置文件没改,程序找不到相应的类
        <many-to-one
            name="FSUnit"
            class="com.xindeco.business.pojo.EmployUnitBaseInfo"
            cascade="none"
            outer-join="auto"
            update="true"
            insert="true"
            access="property"
            column="fSUnit"
        />
其实FSUnit对应的类应该是FSUnit
        <many-to-one
            name="FSUnit"
            class="com.xindeco.business.pojo.FSUnit"
            cascade="none"
            outer-join="auto"
            update="true"
            insert="true"
            access="property"
            column="fSUnit"
        />
13、
org.hibernate.MappingException: An association from the table GraAppInfo refers to an unmapped class: com.xindeco.business.pojo.FSUnit
错误原因:hibernate.cfg.xml没有配置fsunit.hbm.xml文件的位置
14、
java.lang.ClassCastException: com.xindeco.business.dao.impl.GraAppDAOImpl
at com.xindeco.business.service.impl.GraAppServiceImpl.addGraduateApp(GraAppServiceImpl.java:16)
GraAppServiceImpl.java:16
第16行: GraAppDAO dao = (GraAppDAO) this.getBaseDAO();//其实得到的是GraAppDAOImpl
错误的原因是
public class GraAppDAOImpl
    extends BaseDAOImpl {

}
没有实现GraAppDAO接口,正确的做法是
public class GraAppDAOImpl
    extends BaseDAOImpl implements GraAppDAO {
}
先继承后实现
15、2006-04-27 08:38:54,078 ERROR com.xindeco.business.web.action.GraAppAction - com.xindeco.business.web.action.GraAppAction@1d6399b
java.lang.ClassCastException: com.xindeco.business.pojo.SysCode
at org.hibernate.type.StringType.set(StringType.java:26)
at org.hibernate.type.NullableType.nullSafeSet(NullableType.java:63)
at org.hibernate.type.NullableType.nullSafeSet(NullableType.java:40)
一般是因为hibernate声明类型和pojo类声明的类型不一样,并且前面已经出现了Hibernate: insert into TGraAppInfo (name, whereFrom, degree, college, speciality, studentRelTel, remark, higherEduLength, highSchool, studyResume, normalOrNot, proxyUnit, workPost, workPlace, studentAddress, studentPostNumber, nation, appStatus) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
的操作提示,查出错误的原因有:
        <many-to-one
            name="demand"
            class="com.xindeco.business.pojo.Syscode"
            cascade="none"
            outer-join="auto"
            update="true"
            insert="true"
            access="property"
            column="demandID"
        />
         <property
            name="appStatus"
            type="int"
            update="true"
            insert="true"
            access="property"
            column="appStatus"
            length="10"
        />
应改为   
        <many-to-one
            name="demand"
            class="com.xindeco.business.pojo.Demand"
            cascade="none"
            outer-join="auto"
            update="true"
            insert="true"
            access="property"
            column="demandID"
        />
<many-to-one
            name="nation"
            class="com.xindeco.business.pojo.SysCode"
            cascade="none"
            outer-join="auto"
            update="true"
            insert="true"
            access="property"
            column="nation"
        />

16、
org.springframework.dao.InvalidDataAccessApiUsageException: object references an unsaved transient instance - save the transient instance before flushing: com.xindeco.business.pojo.SysCode
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:626)
at org.springframework.orm.hibernate3.HibernateTransactionManager.convertHibernateAccessException(HibernateTransactionManager.java:570)
at
org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:482)
pojo类为:
public class GraAppInfo{
    private College college;
}
action 类为
public class GraAppAction
    extends BaseAction {
       public ActionForward add(ActionMapping mapping, ActionForm form,
                             HttpServletRequest request,
                             HttpServletResponse response) throws Exception {

        graInfo.setCollege(new College());\\必须从数据库找到college这个对象,而不能新生成
        graInfo.getCollege().setID(graForm.getCollegeID());
        graInfo.

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics