java Hibernate 事务结束示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5166698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:46:54  来源:igfitidea点击:

Hibernate transaction end example

javahibernatepersistence

提问by Hectoret

This is a very simple example of hibernate usage in java: a function that when it's called, it creates a new object in the database. If everything goes fine, the changes are stored and visible immediately (no cache issues). If something fails, the database should be restored as if this function was never called.

这是java中hibernate用法的一个非常简单的例子:一个函数,当它被调用时,它会在数据库中创建一个新对象。如果一切顺利,更改将被存储并立即可见(无缓存问题)。如果出现故障,则应恢复数据库,就好像从未调用过此函数一样。

public String createObject() {
    PersistentTransaction t = null;
    try {
        t = PersistentManager.instance().getSession().beginTransaction();
        Foods f = new Foods(); //Foods is an Hibernate object
        //set some values on f
        f.save();
        t.commit();
        PersistentManager.instance().getSession().clear();
        return "everything allright";
    } catch (Exception e) {
        System.out.println("Error while creating object");
        e.printStackTrace();
        try {
            t.rollback();
            System.out.println("Database restored after the error.");
        } catch (Exception e1) {
            System.out.println("Error restoring database!");
            e1.printStackTrace();
        }
    }
    return "there was an error";
}

Is there any error? Would you change / improve anything?

有什么错误吗?你会改变/改进什么吗?

回答by limc

I don't see anything wrong with your code here. As @Vinod has mentioned, we rely on frameworks like Spring to handle the tedious boiler plate code. After all, you don't want code like this to exist in every possible DAO method you have. They makes things difficult to read and debug.

我在这里看不到您的代码有任何问题。正如@Vinod 所提到的,我们依靠 Spring 等框架来处理繁琐的样板代码。毕竟,您不希望这样的代码存在于您拥有的每个可能的 DAO 方法中。它们使阅读和调试变得困难。

One option is to use AOP where you apply AspectJ's "around" advice on your DAO method to handle the transaction. If you don't feel comfortable with AOP, then you can write your own boiler plate wrapper if you are not using frameworks like Spring.

一种选择是使用 AOP,您可以在 DAO 方法上应用 AspectJ 的“around”建议来处理事务。如果您对 AOP 不满意,那么如果您不使用 Spring 等框架,则可以编写自己的样板包装器。

Here's an example that I crafted up that might give you an idea:-

这是我精心制作的一个例子,它可能会给你一个想法:-

// think of this as an anonymous block of code you want to wrap with transaction
public abstract class CodeBlock {
    public abstract void execute();
}

// wraps transaction around the CodeBlock
public class TransactionWrapper {

    public boolean run(CodeBlock codeBlock) {
        PersistentTransaction t = null;
        boolean status = false;

        try {
            t = PersistentManager.instance().getSession().beginTransaction();

            codeBlock.execute();

            t.commit();
            status = true;
        }
        catch (Exception e) {
            e.printStackTrace();
            try {
                t.rollback();
            }
            catch (Exception ignored) {
            }
        }
        finally {
            // close session
        }

        return status;
    }
}

Then, your actual DAO method will look like this:-

然后,您实际的 DAO 方法将如下所示:-

TransactionWrapper  transactionWrapper  = new TransactionWrapper();

public String createObject() {
    boolean status = transactionWrapper.run(new CodeBlock() {
        @Override
        public void execute() {
            Foods f = new Foods();
            f.save();
        }
    });

    return status ? "everything allright" : "there was an error";
}

回答by Vinod R

The save will be through a session rather than on the object unless you have injected the session into persistent object.

除非您已将会话注入持久对象,否则保存将通过会话而不是在对象上进行。

Have a finally and do a session close also

有一个 finally 并关闭一个会话

finally {
   //session.close()
}

Suggestion: If this code posted was for learning purpose then it is fine, otherwise I would suggest using Spring to manage this boiler plate stuff and worry only about save.

建议:如果发布的此代码是出于学习目的,那很好,否则我建议使用 Spring 来管理这些样板文件,而只担心保存。