开发者

Hibernate transaction end example

开发者 https://www.devze.com 2023-02-14 20:24 出处:网络
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 immedi

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.

public String createObject() {
    PersistentTransact开发者_如何学JAVAion 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. 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.

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.

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:-

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消