Milos
Milos

Reputation: 27

Hibernate is ignoring my persist calls?

i have one weird problem. No matter what i do, i cant put new record in database via hibernate. I'm using Hibernate with Tapestry and MySQL. Please someone help me!

I have UserDAO class with this piece of code:

@CommitAfter
public boolean saveUser(User user){
    try {
        session.persist(user);
        return true;
    }catch(Exception e){
        return false;
    }
}

And then i call it here:

@OnEvent(component="add")
Object onAdd(){
    if(username!=null && password!=null){
        User user = new UserBean();
        user.setUsername(username);
        user.setPassword(password);
        userService.saveUser(user);
    }
    if(eventName!=null){
        Event event = new EventBean();
        event.setName(eventName);
        eventService.saveEvent(event);
    }
    return this;
}

But its not working, i dont know why, please help!

Here is full project: http://www.mediafire.com/?pqb2aaadhbukuav


I added this piece of code in AppModule.java and now it works

@Match("*DAO")
public static void adviseTransactions(HibernateTransactionAdvisor advisor, MethodAdviceReceiver receiver) {
    advisor.addTransactionCommitAdvice(receiver);
}

Can anyone explain to me what is this code doing? This is not my first time working with hibernate and tapestry, and i never saw this before, so i don't understand? Please anyone

Upvotes: 1

Views: 754

Answers (2)

Martin
Martin

Reputation: 38299

The @CommitAfter annotation only works in page/component classes by default. To get the same behaviour in service objects, you need that extra piece of code. This is covered by the second half of this page from the user guide.

Can anyone explain to me what is this code doing

That code looks for @CommitAfter annotations in any services having a name that matches @Match("*DAO"). It then applies the HibernateTransactionAdvisor, which adds a commit() call if the annotated method exits successfully. This is done using some of Tapestry's AOP-like meta-programming features.

Upvotes: 3

gkamal
gkamal

Reputation: 21000

Can you log the exception in the saveUser method - if something is going wrong in the persist you won't know about it because you are ignoring the exception. If an exception is being thrown it might help find the problem.

The other problem could be transaction management - if you are using hibernate directly you will need to call the persist method inside a transaction. Without it the changes might be ignored.

Upvotes: 2

Related Questions