Hibernate calls the mysql Stored Procedure

Source: Internet
Author: User

Create two stored procedures in mysql as follows:

1. Search for a data entry by id:

   `findEmpById`( id (          emp  empId ;


2. Search for a field by id and return

   `getNameById`( id (),out eName (        empName  eName  emp  empId ;

In the parameter list of stored procedures, the in parameter represents the input parameter, and the out parameter represents the output parameter.

Use hibernate to call the preceding two stored procedures:

(1) call the first Stored Procedure

                                    main(String[] args)          Configuration cfg =          SessionFactory factory =         Session session =         Connection con =         String sql = "{call findEmpById(?)}"         CallableStatement cs =         cs.setObject(1, 2         ResultSet rs =                       id = rs.getInt("empId"             String name = rs.getString("empName"             System.out.println(id+"\t"+    }

The SQL statement used to call a stored procedure is the name of the call stored procedure (parameter...). However, in java, {} is usually used to call the stored procedure {}. CallableStatement is used to call the stored procedure.

(2) call the second Stored Procedure

                          main(String[] args)          Configuration config =          SessionFactory sessionFactory =         Session session =         Connection conn =         String sql = "{call getNameById(?,?)}"         CallableStatement cs =         cs.setObject(1, 3);          cs.registerOutParameter(2, java.sql.Types.VARCHAR);          cs.execute();          String name = cs.getString(2);    }

If there are output parameters, you must note that 22 rows of code above are required.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.