Mostrando entradas con la etiqueta java persistence. Mostrar todas las entradas
Mostrando entradas con la etiqueta java persistence. Mostrar todas las entradas

lunes, abril 21, 2014

JPA Tip: Inject EntityManager instead of using PersistenceContext


Almost all projects you develop with Java EE will contain a persistence layer and probably you will use JPA for dealing with SQL systems. One way to get an EntityManager is using @PersistenceContext. In this post we are going to explore the advantages of injecting EntityManager instead of using PersistenceContext annotation.

I have written the example and the explanation on github using Docstract.  You can read on https://github.com/tomitribe/community/tree/master/injecting-entitymanager.

We keep reading,
Alex
Pistol shots ring out in the bar-room night, Enter Patty Valentine from the upper hall, She sees a bartender in a pool of blood, Cries out, "My God, they killed them all" (Hurricane - Bob Dylan)

Music: https://www.youtube.com/watch?v=hr8Wn1Mwwwk

lunes, julio 04, 2011

Umetxoak Ikusirik Lorea Ezin Bizirik Arantzak Kendu Nahi Dizkio Bizi Berri Bat Eman (Loretxoa - Benito Lertxundi)



EJP (or Easy Java Persistence) is a powerful and easy to use relational database persistence API for Java. It has no need for mapping Annotations or XML configuration, and there is no need to extend any classes or implement any interfaces. In it is site we can find the following statement: "EJP is, by far, the easiest persistence API available for Java."

From my point of view EJP is a mixture of some features between myBatis and Spring Jdbc Template Row Mapper.

An example of EJP from its website:


and Customer and Support classes are simple POJOs without annotations or any special tag, and no configuration file.

What I am going to explain in this post is how integrate EJP with Spring.

First of all, we are going to create an interface which defines all permitted operations:


This is an example of common operations provided by EJP. Methods that should be clarified are:

  • newDatabase method is used for returning a Database object. This object is a facade that implements all operations supported by EJP. It is the main class of EJP project with permission of DatabaseManager class.
  • loadAssociations are responsible (as its name suggests) to load an object associations.
  • queryForObject methods execute a "query by example" queries.
  • queryForInt is a method used for queries that return numerical results like count(*), avg(...), ...
EjpJdbcTemplate is the implementation of previous interface, and makes use of JdbcTemplate class as core.

Getting a new Database:


Remember that Database object is the core of EJP, and is required to execute all EJP operations. This method creates one Database with given Connection. databaseName is not mandatory, but for no reason is a constructor attribute. A null can be passed without any problem. In this implementation database name is a class attribute.

Deleting:


No secret in deleting an object. Using ConnectionCallback, connection is provided, and Database object is created.

Loading Associations:


If you want to load explicitly all associations of an object, load associations method must be called. The only integration difficult is that database.loadAssociations returns void, and ConnectionCallback should always return a result. In this case void.TYPE is used.

Executing Queries:


In this case most important line is where Database executeQuery method is called. This method returns a class of type Result. This class is a wrapper of ResultSet class but also can deal directly with beans (implicit wrapping), instead of getting one-by-one each parameter. But for following JdbcTemplate strategy and use a row mapper, ResultSet is used for mapping results.

Querying for Int:



See that follows the same schema as executeQuery, but instead of using RowMapperResultSetExtractor, a SingleColumnRowMapper is used. This mapper is used when the query result returns a single result.

Now I am going to show how to use this template into a DAO implementation.


Not much secret in this DAO. Only two methods requires special review findAllCustomersOrderedByName() and findCustomerByExample()

The first one:


this.template.queryForObject(Customer.class, "ORDER BY first_name",BeanPropertyRowMapper.newInstance(Customer.class)) 

 is converted by EJP to SELECT * FROM Customer ORDER BY first_name.

The second one:

this.template.queryForObject(customer, BeanPropertyRowMapper.newInstance(Customer.class)) 

instead of receiving a Class it receives an instance itself to execute the query. In case that first name field was set to alex, the equivalent SQL query would be SELECT * FROM Customer WHERE first_name='alex'


Now I have explained a strategy to integrate EJP with Spring. Because I have followed same structure as Spring-Data Jdbc-Extension project, rather than create a "HelloWorld" project, I decided to fork Spring-Data project into my Github account, and uploaded the code as a new extension for the project. Moreover a Jira issued has been created with id DATAJDBC-11. If you want to watch full code and unit tests go to git@github.com:maggandalf/spring-data-jdbc-ext.git and review spring-data-jdbc-ext/spring-data-jdbc-core/src/main/java/org/springframework/data/jdbc/ejp directory.

I wish you have found this post useful.


Music: http://www.youtube.com/watch?v=PlEknDUSRc0&feature=fvwrel

miércoles, enero 05, 2011

Deep Inside, You Cry Cry Cry, Don’t Let Your Hopes, Die Die Die

JPA2 is present in major ORM vendors (EclipseLink, Hibernate, OpenJPA). Main features are present like multiple levels of embedded objects, ordered lists, support for validation, new criteria query API.

Now it time to talk (with an example) about new criteria query API. For this example I will use Hibernate and its Hibernate Metamodel Generator.

New Criteria API allows criteria queries to be constructed in a strongly-typed manner, using metamodel objects to provide type safety. As is mentioned in Hibernate site: "For developers it is important that the task of the metamodel generation can be automated".

And that's is what Hibernate Metamodel Generator does. This metamodel generator is an annotation processor that is run each time an annotated @Entity bean is compiled, and generates its metamodel class.

Let's see an example:

A class like:

@Entity
public class Pizza {

@Id
@GeneratedValue
private Integer id;
public Integer getId() {return id;}
public void setId(Integer id) {this.id = id;}


@Column
private String name;
public String getName() {return name;}
public void setName(String name) {this.name = name;}
@OneToMany(cascade= CascadeType.PERSIST, mappedBy="pizza")
private Set ingredients = new HashSet();
public Set getIngredients() {return ingredients;}
public void setIngredients(Set ingredients) {this.ingredients = ingredients;}

//Constructor, Transient Methods, ...
}

generated metamodel will look:

@StaticMetamodel(Pizza.class)
public abstract class Pizza_ {

public static volatile SetAttribute ingredients;
public static volatile SingularAttribute id;
public static volatile SingularAttribute name;

} 

Easy to understand, each persistent attribute has its type and which entity belongs. For example field "name" belongs to Pizza and is a "String", and thats so important because precisely that will allow Criteria API to be typesafely.

Ok, now we know that new Criteria API is typesafely and this is acquired with metamodel programming. How about starting from the start?

First of all is configuring Eclipse for compiling using Annotation Processor (in Hibernate site is explained for using in other IDEs or Maven).


Only configure annotations processor output directory and which annotation processor is required, in our case hibernate-jpamodelgen and hibernate-jpa-2.0.

Next step is create our entity class:

@Entity
public class Pizza {

@Id
@GeneratedValue
private Integer id;

public Integer getId() {return id;}
public void setId(Integer id) {this.id = id;}

@Column
private String name;
public String getName() {return name;}
public void setName(String name) {this.name = name;}
@OneToMany(cascade= CascadeType.PERSIST, mappedBy="pizza")
private Set ingredients = new HashSet();
public Set getIngredients() {return ingredients;}
public void setIngredients(Set ingredients) {this.ingredients = ingredients;}

public Pizza(String name) {
super();
this.name = name;
}

protected Pizza() {
}
}

Nothing different here. Same is applied for Ingredient entity (not showed here).

But wait go to target/metamodel, refresh the directory and what you see there? The metamodel classes. Ok if you have arrived successful here, then no problem you have done the complicated thing. Now let's write our first new Criteria query.



CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder();
CriteriaQuery pizzaQuery = criteriaBuilder.createQuery(Pizza.class);
SetJoin ingredientsNode = pizzaQuery.from(Pizza.class).join(Pizza_.ingredients);
pizzaQuery.distinct(true).where(criteriaBuilder.equal(ingredientsNode.get(Ingredient_.name), ingredient));
TypedQuery typedQuery = this.entityManager.createQuery(pizzaQuery);
return typedQuery.getResultList();


This method returns all pizzas that are produced with given ingredient. If you analyze line per line, first of all is created the query about pizza, then is created the join relationship ingredientsNode and "woop" metamodel class starts the game, we are making a join with Pizza_.ingredients, this is the representation of ingredients class. Also we are telling to filter ingredients where the name is the given one criteriaBuilder.equal(ingredientsNode.get(Ingredient_.name), ingredient), and you see that Ingredient_.name is used. This information is crucial because we are telling to Criteria API that the field is the one defined as Ingredient.name. If name attribute is deleted, metamodel class is modified too and our code does not compile.

Take a look the same criteria query but in Hibernate Criteria:


Criteria criteria = session.createCriteria(Pizza.class);
criteria.createAlias("ingredients", "i")
.add(Restrictions.eqProperty("id", "i.pizza"))
.add(Restrictions.eq("i.name", ingredient));
return (List)criteria.list();

For me it is easy to understand first one than second one, it is like more natural, and does not required any cast.

In Hibernate site more examples of new Criteria API can be found. I encourage you to start using JPA2, not only for new Criteria API but for using all new features.