Why use JPA instead of directly
writing SQL query on Java File (i.e.
directly to JDBC) ?
Certain projects require engineers to focus more on the object model rather than on the actual SQL queries used to access data stores. The question can actually be interpreted as
Why should one use an ORM framework ?
which can have different answers in different contexts.
Most projects can benefit from having a domain model, with persistence being a second concern. With JPA (implementations) or most other ORM frameworks, it is possible to have all entities i.e. tables in your database, modelled as classes in Java. Additionally, it also possible to embed behavior into these classes and therefore achieve a behaviorally rich domain model. The entities in this model can have multiple purposes, including the purpose of replacing DTOs for transporting data across tiers.
That said, there are places where ORM frameworks may not be a direct fit to the problem, especially when the data model is already established, or when one is working with legacy systems where mapping database tables to Java classes is a non-trivial exercise. And in certain cases, if one needs to absolutely tune the heck out of the SQL generated by the ORM framework, then ORM frameworks are usually a bad fit.
Related Questions
- Java EE Architecture – Are DAO’s still recommended when using an ORM like JPA 2?
- Using an ORM or plain SQL?
- ORM vs Handcoded Data Access Layer