简体   繁体   English

休眠事务结束示例

[英]Hibernate transaction end example

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. 这是java中休眠用法的一个非常简单的示例:一个函数,当它被调用时,它将在数据库中创建一个新对象。 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. 如果发生故障,应还原数据库,就像从未调用此函数一样。

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? 你会改变/改善任何东西吗?

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. 正如@Vinod所说,我们依靠像Spring这样的框架来处理乏味的样板代码。 After all, you don't want code like this to exist in every possible DAO method you have. 毕竟,您不希望这样的代码存在于每种可能的DAO方法中。 They makes things difficult to read and debug. 它们使事情难以阅读和调试。

One option is to use AOP where you apply AspectJ's "around" advice on your DAO method to handle the transaction. 一种选择是使用AOP,您可以在DAO方法上应用AspectJ的“ around”建议来处理事务。 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不满意,那么如果不使用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";
}

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 {
   //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来管理该样板文件,并且只担心保存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM