转到正文

存档

分类: JAVA

问题描述:

在Spring中使用hibernate进行事务处理时,如果出现以下情形,会报“org.hibernate.SessionException: Session is closed!”错误:

类A中的函数A1调用类B的函数B1,函数B1调用非事务函数B2和事务函数B3。类B和函数B1都没有进行事务声明(@Transactional(propagation=Propagation.REQUIRED,readOnly=false ))。

解决方案:

在一个类中,如果它的顶层函数下面有调用事务函数,则必须有Hibernate事务声明,否则就会有session closed exception. 而且,propagation是可以继承并重载的。

因此,一个类是一个session,如果想一劳永逸,就直接在类上方添加事务声明。或者,在含有事务函数的顶层函数上方添加事务声明。

通过Spring,你可以通过指定自己的@Transactional来覆盖从接口或超类自动继承的事务设置。

在用hibernate以lazy的策略来读数据库,在A文件中将数据objectA list读出,它是一个list,List的每个元素objectA与objectB是一对多的关系。然后在B文件中,遍历objectA list,对于每个objectA,读取它的objectB列表。用函数来表示如下:

A文件中:

List getObjectAList()
{
	......
	return objectAList;	

}

B文件中:

{
.....

List objectAList = getObjectAList();
for(objectA item: objectAList )
{
	List objectBList = item.getObjectList();  // ********* hibernate will get error at this line
}

然而,这里出现错误:我们虽然可以正常遍历objectA list,但是在对于每个objectA,想要读取它的objectB列表时,就出现错误:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role:, no session or session was closed..

Solution:

继续阅读

用java在Linux环境下执行shell命令,可以使用如下方法:

import java.io.IOException;
public class JavaShell
{
        /**
         * @param args
         * @throws IOException
         * @throws InterruptedException
         */
        public static void main(String[] args) throws IOException, InterruptedException
        {
                Process p;
                p = Runtime.getRuntime().exec("md5sum a.c > a.c.md5"});
                if(0==p.waitFor())
                {
                        System.out.println("Command execute result is OK!");
                }
                else
                {
                        System.out.println("Command execute result is fail......");
                }
        }
}

但上述程序执行起来是有问题的。程序运行后,并没有正确的生成.md5文件。Runtime.getRuntime().exec的执行结果都是非0。出现这种错误的原因是因为 额外的参数(">") 被直接传送到了md5sum命令而不是送到实际的命令行。
解决这一问题的办法是将cmd串弄成一个字符串数组,并且将你想运行的程序传送到命令shell。如下面的程序所示:

继续阅读

www.liaoqiqi.com网站PR查询 博客简洁版 博客Google_Site_Map 博客Baidu_Site_Map ?