Issue
I've been reading up on several articles what is JPA (Java Persistent API)
and which vendor supporting it (DataNucleus, JBoss Hibernate etc)
I don't have experience with ORM (object relational mapping).
What I have done so far is to write my own Database classes using DTO and DAO. So far I'm happy about what I have but would like to know why people use JPA over Java file which contains SQL.
To me I feel like writing DAO class would be ok something like below.
public class DAOUsers {
public void insertNewUser(DTO DtoUser) {
String query = "INSERT INTO users(username, address) " +
"VALUES(DtoUser.username , DtoUser.address)";
Executor.run(query);
}
}
I've learned JPA uses JPQL, Java persistent query language and it operates against entity object rather than directly with db tables.
My understanding (correct me if Im wrong) is that entity object here is same as my DTO object (kind of like bean?)
But anyhow.. what really benefit JPA gives over writing pure SQL in my file? Seems like using annotations required by JPA and make SQL not readable feels not really attractive to me..
please let me know if you need more clarification, I'm new to this topic and would like to hear some opinion.
Solution
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
Answered By - Vineet Reynolds
Answer Checked By - Willingham (JavaFixing Volunteer)