|Image NOT related :)|
If you have ever done any amount of Java EE development you have probably come across JPA (The Java Persistance API) a few times. In this article I will write a high level overview on JPA and what tools the API provides.
JPA consists of three main areas of functionality: Object Relational Mapping (ORM), The Entitiy Manager and the Query Interface (JPQL and native queries). Each of these sections deserves an entire post on it's own, for now I will only be providing an overview and as I get time I will write the more detailed posts.
1. Object Relational Mapping (ORM)
On a high level ORM is a way of working with objects in your program that represent data inside your database. The beauty of this is that developers are abstracted from the database level and can work with what they know best, objects. The only difficulty is the initial work required to map your Java Entities to your database tables, columns and relationships between tables (This step is very difficult because doing this incorrectly can create massive performance issues, consider yourself warned). This mapping is done using annotations. There is a lot to ORM, in this post I will only cover the basics.
These are the most frequently used annotations in ORM, learn them well:
@Entity - Marks this class as an Entity.
@Id - Marks a specific column as the Identifier.
@Column - Marks a variable as a column in your database, most frequently used when your Java instance variable names don't match your column names, along with the
@Basic - Mostly
Field Level: Relationships
@OneToOne - Marks a typical One to One relationship.
@OneToMany - Marks a typical One to Many relationship.
@ManyToOne - Marks a typical Many to One relationship.
@ManyToMany - Marks a Many to Many relationship.
Using those annotations you should be able to map your classes to your tables pretty easily, doing this efficiently however takes some experience, don't get discouraged. There are other things I would like to talk about, like JPA Entity LifeCycle Listeners, mapping Compound Keys and Inheritance, but that will have to wait for another time.
One final thing on ORM, I would highly recommend you read up on Domain Modeling. This knowledge will make you a better/more rounded developer, not only when working with JPA but overall.
2. The Entitiy Manager (EM)
This is the workhorse of JPA, on a high level the entity manager is used for the CRUD operations in your application. The EM also manages your entities at long as those enties are within scope of the EM. Management of entities and the two persistance contexts (Transaction-scoped Persistence context and Extended Persistence context) will be covered in the detailed article but if you really can't wait feel free to read up on them. :)
JPA can be used outside of a container, because of this there are two ways for an EM to be created and managed. The EM can be container managed or application managed. If you really can't use a container then you can create a EnityManager using an EntityFactory. I won't be covering application managed EMs but it's useful to know you can use JPA when a container is not available.
Using a container you can inject an EM into your bean with the @PersistenceContext annotation once you have access to the EM the following methods should interest you most:
find: look up provided entity by pk
merge: updates an entity to the database (almost like a database UPDATE statement)
persist: saves a new entity to the database (almost like a database INSERT statement)
remove: deletes provided entity from the database
The EM has other interesting methods like clear and flush but I encourage you to look them up yourself. I am going to cover some more EM methods in the next section.
3. Query Interface
I covered the find method in the entity manager but that method is pretty one dimensional, it's not often that you lookup data only on the primary key. JPA therefore provides us with another useful object, Query. You create a Query object using your EM and since I'm sure that you read the Java docs on EM I provided earlier you'll know that I am talking about createNamedQuery, createNativeQuery and createQuery methods.
Let me speak about Dynamic Queries and Named Queries quickly. A Dynamic Query is created as part of your createQuery method you type the JPQL or native SQL as part of the method invocation so for example em.createQuery("Select c from Customer"); or em.createNativeQuery("Select * from Customer"); Named Queries on the other hand are defined in the Enity class itself (using the @NamedQuery annotation) and are available everywhere that has access to that Entity. Good candidates for Named Queries are queries that will be used by different parts of your application.
Now for Native Queries and JPQL Queries (Java Persistence Query Language), JPA allows you to create a Query object by writing the native SQL of your DBMS provider. This is discouraged as one of the big benefits of JPA is that is allows you to swap out DBMS providers with little to no code changes, using native SQL in your application will greatly limit this ability. Rather write JPQL, this is a more generic Query Language that your persistence provider then translates to native sql.
Using the Query Interface you can retrieve data from your database based on a multitude of different conditions. If you are going to be working in JPA for a significant amount of time I suggest you learn JPQL well.
Final Word Before The Conclusion
There is a bit of confusion about the difference between JPA, Hibernate and Persistence Providers so let me see if I can clear it up a bit. JPA is the specification that has been defined by the Java EE guys, this is basically a document that tells application servers (or in this case Persistence Providers) what they have to do to be considered compliant. Application Servers use what is termed as Persistence Providers that implement the JPA specification, although persistence providers can and do exist outside of the container. Finally what is Hibernate, well in the beginning the JPA was pretty cumbersome to use (or so I've heard I was lucky that I only started developing when EJB 3.0 and JPA 2.0 was available) and the smart people at Hibernate saw an opportunity to do a better job than the JPA was doing and that's when Hibernate came into existence. I hope that clears things up a bit.
This article got a lot bigger than I expected, and there are lots of interesting topics that I did not cover, but I have taken note of them and will do so when I have the time. Overall JPA is a really cool API and it provides lots of powerful tools for the developer to use, if you are looking to write an application with database interactions I would highly recommend JPA, but be a word of warning JPA can cause performance issues if you don't know how to use it correctly so my suggestion would be to first research the topic and maybe even read a few chapters on a good JPA book.