Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to Call Stored Procedure using Entity Manager in JPA

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 3.40k
    Comment on it

    Call stored procedure in JPA : Here I am going to tell you that how you can call the stored procedure using JPA entity manager. Following is the example to call stored procedure using entity manger.

    Suppose we have a stored procedure called 'get_login_info' which will give you the user information by searching his/her username. Following the example code for calling stored procedure in JPA:

    Example of calling stored procedure in JPA : First create a db stored procedure using following command in mysql.

    1. #-- create db stored procedure
    2. # Stored procedure to give user details when login
    3. DELIMITER $$
    4.  
    5. CREATE DEFINER='root'@'localhost' PROCEDURE 'get_login_info'(IN userName varchar(300))
    6. BEGIN
    7. SET @SQLQuery = CONCAT("SELECT * FROM userInfo WHERE user_name ='" ,userName,"'");
    8. PREPARE stmt FROM @SQLQuery;
    9. EXECUTE stmt;
    10. END

    In your DAO code write the following code snipped :

    1. @SuppressWarnings("unchecked")
    2. public UserInfo findUserByName(String username){
    3. UserInfo user =null;
    4. try{
    5. entityManager.getTransaction().begin();
    6. List<UserInfo> results = entityManager
    7. .createNativeQuery("{call get_login_info(?)}", UserInfo.class)
    8. .setParameter(1, username)
    9. .getResultList();
    10. if(results.size()>0)user = (UserInfo) results.get(0);
    11. entityManager.getTransaction().commit();
    12. }catch (Exception e) {
    13. logger.error("Error at findUserByName funtion ", e);
    14. if (entityManager.getTransaction() != null) {
    15. entityManager.getTransaction().rollback();
    16. throw new ApplicationException("Database Exception.");
    17. }
    18. }
    19. return user;
    20. }

    So finally, in the above code "{call get_login_info(?)}" will call the stored procedure and return the result.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: