简体   繁体   中英

JPA JPQl or Stored Procedures in MySQL

I am developing an application that uses JPA 2.0 with MySQL 5 database.

I know that JPA hides the calls to the DB queries and makes it underthehood, and all i use is JPQL,

now does this makes the need for stored procedures less ? and how can i use stored procedures with JPA 2.0 ?

Stored procedures have mostly gone out of favor (you can read some ideas on why here: http://www.codinghorror.com/blog/2004/10/who-needs-stored-procedures-anyways.html ).

In general unless you have performance issues or are working with legacy systems, it's advised not to use stored procedures. Object Relational Mapping solutions, such as JPA, are now the industry standard, mostly because they let you write less, and are easier to maintain then other methods (such as using the DAO pattern and JDBC directly).

For example consider adding a new column to a table you are using CRUD (Create,retrieve,update,delete) with:

  • Using a JPA you add the column to the table and add the property to the class with an annotation, that's it.
  • With stored procedures, you'll also need to add the parameter to the procedures to update or create a new entity, you'll need to add the column to the insert or update statement inside the procedure, in some cases you'll need to add the column to the select clause inside the procedure.

In regards to using stored procedures, JPA doesn't have support for stored procedures per se, but there are two way you can work around it:

  • Some JPA implementation (such as EclipseLink or Hibernate) support stored procedures, and you can use their implementation directly , you'll have to see what implementation you are using.
  • You can use the "native query" feature, that let's you write an sql in the Native database query language, for instance for mySQL you can write something like this:

     Query query = entityManager.createNativeQuery("{ CALL procedure(?) }"); query.setParameter(1, parameterName); 

    You need to also remember that the procedure must return a result set and you can't use out parameters.

if you use EclipseLink JPA, you can use @NamedStoredProcedureQuery annotation for your stored procedures.

Example :

@NamedStoredProcedureQuery(
    name="findAllEmployees", 
    procedureName="EMP_READ_ALL", 
    resultClass=Employee.class, 
    parameters = {
        @StoredProcedureParameter(
            queryParameter="result", 
            name="RESULT_CURSOR",
            direction=Direction.OUT_CURSOR
        )
    }
)
@Entity
public class Employee {
  ...
}

You can reference here .

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