简体   繁体   中英

Hibernate not executing queries until response is commited

I am doing few hibernate save operations in spring's transactional service class. My expectation is that by the time method execution finishes hibernate should write data to database. But hibernate is actually executing those queries only when controller is about to return a response.

My sample code is as follows.

@Controller
public class TestController {
    @Autowired
    private SaveService saveService;

    @RequestMapping(value = "saveData", method = RequestMethod.POST)
    public String saveData(HttpServletRequest request, Model model) {
        try {       
        saveService.saveData(object1, object2, object3); // LINE 1
        sendEmail();                                     // LINE 2
        //some code here                 // LINE 3  
        } catch(Exception e) {
            //log exception
            //return error message      
        }
    }
}


@Service("saveService")
@Transactional
public class SaveServiceImpl implements SaveService {
    @Autowired
    private SaveDAO saveDAO;

    public void saveData(Object objec1, Object objec2, Object objec3) {
        saveDAO.save(object1);
        saveDAO.save(object2);
        saveDAO.save(object3);  
    }   
}

In above code I am calling SaveService.saveData() method from controller. And if save is successful I want to go ahead and send an email. But if for some reason SaveService.saveData() throws an exception i don't want to send the email.
When I performed some tests it was observed that even if SaveService.saveData() throws an exception it's not thrown until the email is sent from controller.
I want that if a call to saveService.saveData() at 'LINE 1' in controller throws an exception the next line that sends email should not get executed.
I wanted to know if this is expected hibernate behavior and if it is what can I do to tell hibernate to execute queries before exiting service methods.
Thank you.

This behavior is due to hibernate optimizations. Hibernate will wait until the last time possible to execute the sentences.

You can avoid this with session.flush() , Flushing the session forces Hibernate to synchronize the in-memory state of the Session with the database (ie to write changes to the database).

The problem here is when an exception occurs, your the variables/objects are not initialized in the catch block and you are accessing it.

As it looks like you have just added a snippet of the code in question, so I guess the variables object1, object2, object3 needs to initalized to null .
for example: object1=null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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