logo

JPA 2.0 (Hibernate, Eclipselink) hello world

JPA 2.0 (Hibernate, Eclipselink) hello world. How to generate entities and using EntityManager read some data. Presented on MySQL database.

First you must have fully configured JPA project. It doesn't matter if you downloaded libraries and associated them with your project or if you used Maven. It even doesn't matter which implementation of JPA specification you have, be it Eclipselink, Hibernate or something else entirely.

Next you must create entities. They are Java classes, that are mapped to database tables. Usually they are very similar to database tables and with Eclipse I can generate them. To do that right click and choose "JPA Entities from Tables", select tables, click Next. Here are associations between tables, click Next, here you can choose how to generate primary keys and set package where will be generated classes. Click Finish.

To retrieve some data from database create a Main class and type:

EntityManager entityManager = Persistence.createEntityManagerFactory(
"testJpaEclipselink").createEntityManager();
List<Customer> list = entityManager.createQuery("select c from Customer c", Customer.class)
.getResultList();
for (Customer customer : list) {
System.out.println(customer.getName());
}


comments powered by Disqus

rss

Free online Java web application examples

Want to develop whole web applications which use database, security and more? See my github account, where are lot's of example projects:
github

Search