Mark Estrada
Mark Estrada

Reputation: 9201

How to return result of transaction in JPA

Just a background since I am used to using JDBC since I worked on an old project. When saving into database, I always set the value to -1 for any unsuccessful insert

public class StudentDao{
    //This dao method returns -1 if unsuccessful in saving
    public int save(Student stud){
        Statement st = con.createStatement();
        try{
            int val = st.executeUpdate("INSERT student VALUES(.......)");
        }catch(Exception e){
            return -1;
        }
    }
}

Based on the return I could could tell if the insert is successful so that I could do the exact logic. (Tell the user that the transaction is incomplete...)

Now, I used EJB in persisting entity. Most of the tutorials that I am seeing only have this construct. Netbeans is generating this code also with a 'void' return.

@Stateless
public class StudentFacade{
    @PersistenceContext(unitName = "MyDBPU")
    private EntityManager em;

    public void save(Student student){
        em.persist(student);
    }
}

When saving entity on a servlet, it just call the method like this code.

@WebServlet(name = "StudentServlet",
loadOnStartup = 1,
urlPatterns = {
    "/addStudent",})
public class StudentServlet extends HttpServlet {
    @EJB
    private StudentFacade studentFacade;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //extract HTTP form request parameters then set 
        Student stud = Util.getStudent(request);

        studentFacade.save(stud);

    }
}

But how will I know if the insert is successful? (Dont catch the exception and then just let it propagate. I have configured my error page so obviously this would catch the error???)

Sorry I am getting confused on integrating my EJB components but I am seeing its benefits. I just need some advise on some items. Thanks.

Upvotes: 1

Views: 800

Answers (1)

Kris
Kris

Reputation: 5792

The container will propagate the exception to the caller (if you don't do anything with it inside the EJB). That would be probably the SQLException I guess. You can catch it on the servlet and do whatever you want with it. If you use Container Managed Transactions (CMT) the transaction will be rolled back for you automatically by the container and the student object won't be added. As you said, you can of course leave the exception on the web layer as well and then prepare a special error page for it. All depends on your usage scenario.

Upvotes: 2

Related Questions