Category Archives: Business English

EasyCriteria on Maven

Hello, how are you?

We are happy to announce that EasyCriteria is now on Maven Repository.

To use it just add the line below in the pom.xml:

<dependency>
	<groupId>uaihebert.com</groupId>
	<artifactId>EasyCriteria</artifactId>
	<version>2.1.0</version>
</dependency>

Simple and easy. The version 2.1.0 was released to adapt the pom.xml to the Maven requirements.

I hope you like this news! =D

http://easycriteria.uaihebert.com

EasyCriteria 2.0 – JPA Criteria should be easy

Hello, how are you?

It has been a long time since my last post, but I was not doing nothing during this time.

In the post today we will see about the new version of the framework named EasyCriteria. At the end of this post we will see what is to come here in the blog.

Unfortunately the JPA criteria has a huge problem that is its verbosity. Why not make easier? Thinking like this that EasyCriteria framework were born and now it is on version 2.0.

To do a simple JPQL with the JPA Criteria the following code would be needed:

CriteriaQuery<Person> criteriaQuery = criteriaBuilder.createQuery(Person.class);
Root<Person> root = criteriaQuery.from(Person.class);
criteriaQuery.select(root);
TypedQuery<Person> query = entityManager.createQuery(criteriaQuery);
query.getResultList();

Notice all the code needed to do the query: select p from Person p.

Check below how easy it is to do the same Criteria with EasyCriteria:

EasyCriteria<Person> easyCriteria = EasyCriteriaFactory.createQuery(entityManager, Person.class);
easyCriteria.getResultList();

The difference between version 1.0 and the 2.0 version is in the reduction of methods into generic methods. To compare methods with =, >=, <, <=, and other methods just use the API like below:

easyCriteria.andGreaterThan("hairSize", 10.4f); // >

easyCriteria.andGreaterOrEqualTo("height", 11.00d); // >=

easyCriteria.andLessThan("totalBooksOwned", 30L); // <

easyCriteria.andLessOrEqualTo("firstJobDate", firstJobDate); // <=

easyCriteria.andJoinEquals("dogs", "age", 15); // =

easyCriteria.andJoinStringIn("dogs", "name", names); // value in (x, i, z, ...)

easyCriteria.andJoinStringLike("dogs", "name", "%y");

One of the ideals of the EasyCriteria framework is to expose the lower number possible of API to the user. Thinking like this, EasyCriteria added the “OR” condition to its API without new classes.

Take a look below to see how to do queries with OR:

select s from Song s where s.id = 1 or s.length = 40 or s.artist = 'Group 1 Crew'
easyCriteria.orEquals("id", 1).orEquals("length", 40).orEquals("artist", "Group 1 Crew");

Another type of OR could be done:

select s from Song s where (s.id = 1) or (s.id = 2) or (s.length = 40) or (s.artist = 'Group 1 Crew')
easyCriteria.orEquals("id", 1, 2).orEquals("length", 40).orEquals("artist", "Group 1 Crew");

And it is possible to do complexes queries cases like:

select s from Song s where (s.totalDownloads = 20 or s.weight = 10.00) and (s.price = 20.00 or s.type = :type)
easyCriteria.orEquals(1, "totalDownloads", 20L).orEquals(1, "weight", 10.00f).orEquals(2, "price", 20.00d).orEquals(2, "type", SongType.PRAISE);

The idea of index were added to the API to be used with a group of OR. The first OR group is composed of “totalDownloads” and “weight”, the second group has “price” and “type” as elements.

As default index the value 1 is always used. The criteria above could be written as:

easyCriteria.orEquals("totalDownloads", 20L).orEquals("weight", 10.00f).orEquals(2, "price", 20.00d).orEquals(2, "type", SongType.PRAISE);

It is possible create a query to do the inverse of the query above, AND separated by OR:

select s from Song s where (s.id = 1 and s.name = 'Sing Out') or (s.id = 2 and s.name = 'Alive')
easyCriteria.addAndSeparatedByOr(1, "id", 1).addAndSeparatedByOr(1, "name", "Sing Out").addAndSeparatedByOr(2, "id", 2).addAndSeparatedByOr(2, "name", "Alive");

That is all for today, I hope you like the new version. It will take a long time to consider this framework complete. Helping with the OR functionality I could count with João Neves (http://about.me/joaonevesfilho) and Sasaki (http://curriculum.rodrigosasaki.com/).

Here it is possible to see the framework official page: http://easycriteria.uaihebert.com/. And the best, it is open source (http://code.google.com/p/easy-criteria/).

Other fact about the framework is that it is 100% covered with tests using Cobertura. EasyCriteria was tested with OpenJPA, EclipseLink and Hibernate. Now it is time to ask for your help. It was found bugs in the tested implementations; it would be wonderful if you spare 5 minutes of your time voting in the bugs. With your vote the bug could be corrected faster.

EclipseLink: https://bugs.eclipse.org/bugs/show_bug.cgi?id=386354
OpenJPA: https://issues.apache.org/jira/browse/OPENJPA-2333
Hibernate: https://hibernate.onjira.com/browse/HHH-7985

What is to come in the blog? It took so much time for me to write this post because I am finishing my first book. If God’s will, the book will be released in March.

In this pause of new posts here, I have studied a lot of Maven and I want my next post to be about a mini book about a basic Maven and full web applications. Yes, I said “applications” in plural. [=

See you soon. \o_

JPA Mini Book – First Steps and detailed concepts

Hello, how are you?

Today we will see about JPA: what is the persistence.xml file used for, how to create an entity, mapping easy and complex ids, creating relationships between the entities, automatically entity persistence and more.

Today we will see:

  • Page 02: Reasons that led to the creation of JPA
  • Page 03: What is JPA? What is a JPA Implementation?
  • Page 04: What is the persistence.xml file used for? And its configurations?
  • Page 05: Entity definitions. What are the Logic and Physical annotations?
  • Page 06: Id Generation: Definition, using Identity or Sequence
  • Page 07: Id Generation: TableGenerator and Auto
  • Page 08: Simple Composite Key
  • Page 09: Complex Composite Key
  • Page 10: How to get an EntityManager
  • Page 11: Mapping two or more tables in one entity
  • Page 12: Mapping Hierarchy: MappedSuperclass
  • Page 13: Mapping Hierarchy: Single Table
  • Page 14: Mapping Hierarchy: Joined
  • Page 15: Mapping Hierarchy: Table per Concrete Class
  • Page 16: Pros/Cons of each hierarchy mapping approach
  • Page 17: Embedded Objects
  • Page 18: ElementCollection – how to map a list of values into a class
  • Page 19: OneToOne unidirectional and bidirectional
  • Page 20: OneToMany/ManyToOne unidirectional and bidirectional
  • Page 21: ManyToMany unidirectional and bidirectional
  • Page 22: ManyToMany with extra fields
  • Page 23: How the Cascade functionality works? How should a developer use the OrphanRemoval? Handling the org.hibernate.TransientObjectException
  • Page 24: How to delete an entity with relationships. How to know which relationships are raising the exception
  • Page 25: Creating one EntityManagerFactory by application
  • Page 26: Understanding how the Lazy/Eager option works
  • Page 27: Handling the “cannot simultaneously fetch multiple bags” error

Just one more observation: I will not create a PDF file of this post. Just to create this material I already take several hours of code formatting, images production, translate all text to the English language and texts adjusts in this blog page. I am sorry, but there is no way to create a PDF file, maybe sometime later but I will not promise.

EasyCriteria 1.0 released

Hello, how are you?

This post will talk about the new functionalities of EasyCriteria.

EasyCriteria is a tool (Open Source) to make easier the JPA Criteria code for any kind of JPA implementation. EasyCriteria has 100% of coverage on its tests with JUnit and it is tested with: Hibernate, OpenJPA and EclipseLink.

If you want to understand the Criteria ideal and how to apply it to your code check this post: EasyCriteria – An easy way to use the JPA Criteria

The new EasyCriteria functionalities are:

  • Join with conditions
  • Query Pagination

Now it is possible to do a Join and add parameters to it:

EntityManager em = emf.createEntityManager();
EasyCriteria<Person> easyCriteria = EasyCriteriaFactory.createQueryCriteria(em, Person.class);

easyCriteria.innerJoin("dogs", Dog.class);
easyCriteria.whereJoinEquals("dogs", "name", "Dark");
easyCriteria.whereJoinStringNotIn("dogs", "name", names); // names is a List<String>
easyCriteria.whereJoinStringLike("dogs", "name", "M%");
easyCriteria.whereJoinListIsEmpty("dogs", "cars");
easyCriteria.whereJoinAttributeIsNull("dogs", "nickName");
easyCriteria.whereJoinStringBetween("dogs", "name", "A", "L");

The query can be paginated:

EasyCriteria<Dog> easyCriteria = EasyCriteriaFactory.createQueryCriteria(getEntityManager(), Dog.class);
easyCriteria.setFirstResult(0);
easyCriteria.setMaxResults(5);

This new version also has 100% of code coverage.

Click here to download the code of this post with EasyCriteria. With this code you can test EasyCriteria as you like.

In the project page (http://easycriteria.uaihebert.com/) you will find all documentation.

If you have any doubt, just post it.

See you soon! \o_

EasyCriteria – An easy way to use the JPA Criteria

Hello, how are you?

Today we will see about this tool that make easier to use the JPA Criteria. The application that uses this library will be cleaner, easier to use and portable across the JPA implementations.

At the end of this post you will find the source code to download.

What is Criteria? Currently is the best solution to create dynamic queries. Imagine a page that allows the user to do several types of queries; the requested query could be by name, by age or with both. Take a look bellow in how the query would look like if we concatenate a String:

EntityManager em = emf.createEntityManager();
String hql = "select p from Person p where 1=1 ";

if(parameters[0].equals("name")){
	hql += " and p.name = '" + values[0] + "'";
}

if(parameters[1].equals("age")){
	hql += " and p.age = " + values[1];
}

TypedQuery<Person> query = em.createQuery(hql, Person.class);

System.out.println(query.getResultList());

Notice that in the code above a String concatenation is made; remember that this practice is a bad and dangerous practice because it allows “SQL Injection” hacker attack. To avoid this attack we should use a query with parameters:

EntityManager em = emf.createEntityManager();
String hql = "select p from Person p where 1=1 ";

if(parameters.contains("name")){
	hql += " and p.name = :name";
}

if(parameters.contains("age")){
	hql += " and p.age = :age";
}

TypedQuery<Person> query = em.createQuery(hql, Person.class);

if(parameters.contains("name")){
	query.setParameter("name", values[0].toString());
}

if(parameters.contains("age")){
	query.setParameter("age", Integer.valueOf(values[1].toString()));
}

System.out.println(query.getResultList());

Notice that the SQL Injection problem were solved but now the code must check parameters to add it to the query and later to pass its values; the code needs of two “parameters searches” to complete the task.

The Java/Oracle developers had the brilliant idea when they created the Criteria concept that is perfect to this kind of situation. Check bellow how the code would look like with the native JPA Criteria:

EntityManager em = emf.createEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Person> cq = cb.createQuery(Person.class);
Root<Person> root = cq.from(Person.class);
cq.select(root);

if(parameters.contains("name")){
	Path<String> name = root.get("name");
	cq.where(cb.and(cb.equal(name, values[0])));
}

if(parameters.contains("age")){
	Path<Integer> name = root.get("age");
	cq.where(cb.and(cb.equal(name, Integer.valueOf(values[1].toString()))));
}

TypedQuery<Person> query = em.createQuery(cq);

System.out.println(query.getResultList());

Is possible to see that to pass the parameters values is easier. There is no need to concatenate the String or to check the parameters list values to populate the values.

Unfortunately the Criteria API is to complex and verbose to the extreme. If you want to do only a “select p from Person p” you would need to create the criteria bellow:

EntityManager em = emf.createEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Person> cq = cb.createQuery(Person.class);
Root<Person> root = cq.from(Person.class);
cq.select(root);

TypedQuery<Person> query = em.createQuery(cq);
System.out.println(query.getResultList());

Is to much code to do something so easy, list all persons from a table.

To avoid all this verbosity the Open Source project named EasyCriteria were created. If a developer uses the EasyCriteria the query above would look like bellow:

EntityManager em = emf.createEntityManager();
EasyCriteria<Person> easyCriteria = EasyCriteriaFactory.createQueryCriteria(em, Person.class);

if(parameters.contains("name")){
	easyCriteria.whereEquals("name", values[0]);
}

if(parameters.contains("age")){
	easyCriteria.whereEquals("age", values[1]);
}

System.out.println(easyCriteria.getResultList());

Notice that the all JPA verbosity is gone. Now it is possible to have a clean code, easier to create dynamic queries. About the code above is worth to talk about:

  • Line 2: An instance of the EasyCriteria is created through a “factory”. This factory exists to do the abstraction of the every needed steep to create an object of the EasyCriteriaImp type. In the future verions new types of the EasyCriteria will be added, e.g. “Tuple”.
  • Lines 5 and 9: It is easier to pass the parameters. To pass the parameters to compare values (“name = :name”) just use the equals method that take as first parameter the attribute name; the second parameter will be the value that will be equaled.
  • Line 12: To run the query it will not be necessary to use the Query interface. The EasyCriteria itself takes this responsibility. It is possible to extract the query result through the EasyCriteria. There are two methods available to get the query result: EasyCriteria.getSingleResult(), EasyCriteria.getResultList().

In the EasyCriteria web page it is available several code samples and the methods that can be used. Other advantage of the EasyCriteria is the ability to “link” all methods:

easyCriteria.whereEquals("name", values[0]).whereEquals("age", values[1]).getResultList();

It is an light weight library because the only dependency is the JPA that the system will need to have. Attention: your application will need to have a JPA implementation up and running.

This library was developed with JUnit and tested with Hibernate, OpenJPA and EclipseLink. The JUnit also uses the Cobertura framework to check if all code lines (or most of it) are covered by the tests, so far we got 100% of coverage.

EasyCriteria still in Beta but the development team already got planed some releases and functionalities.

Other EasyCriteria advantage is that your software code in no long “coupled” to any kind of JPA implementation. Today the Hibernate has a good criteria tool, but your code must stay “attached” to it. With the EasyCriteria you will be able to use any kind of JPA implementation. The proof of this decoupled library is that the EasyCriteria has been tested with 3 implementations quoted earlier.

The EasyCriteria has the methods: in, like, empty and others. The developer will be able to do join (just simple joins without parameter), distinct or even order by all with Criteria.

Here you will find the EasyCriteria to download and have access to all its documentation.

Click here to download the source code of this post.

I hope that this post/tool may help you.

If you have any doubt/question/comment just post it.

See you soon! \o_

How to test your JPQL / HQL without a Deploy

Hello, how are you?

Have you ever wanted to test your JPQL / HQL without doing a full deploy of your application?

What we will see here today is simple solution that works for any JPA implementation: Hibernate, OpenJPA, EclipseLink and others.

The base source code found in this post came from this book: “Pro JPA 2: Mastering the Java™ Persistence API – Mike Keith, Merrick Schincariol”. This post will add to the original code: query parameters and NamedQuery test.

The post contents:

  • Page 02: Model classes and data Generation
  • Page 03: Abstract test class
  • Page 04: Dynamic Query test
  • Page 05: NamedQuery test
  • Page 06: Running the application
  • Page 07: Using this post code with your application code
  • Page 08: Proposals

You will find the source code of this post in the last page.

In the page 07 you will see how to apply the code of this post to the code of your application.

Four solutions to the LazyInitializationException

Hello, how are you?

In the post today we will talk about the common LazyInitializationException error. We will see four ways to avoid this error, the advantage and disadvantage of each approach and in the end of this post, we will talk about how the EclipseLink handles this exception.

To see the LazyInitializationException error and to handle it, we will use an application JSF 2 with EJB 3.

Topics of the post:

  • Page 3: Understanding the problem, Why does LazyInitializationException happen?
  • Page 4: Load collection by annotation
  • Page 5: Load collection by Open Session in View (Transaction in View)
  • Page 6: Load collection by Stateful EJB with PersistenceContextType.EXTENDED
  • Page 7: Load collection by Join Query
  • Page 8: EclipseLink and lazy collection initialization

At the end of this post you will find the source code to download.

Attention: In this post we will find an easy code to read that does not apply design patterns. This post focus is to show solutions to the LazyInitializationException.

The solutions that you will find here works for web technology like JSP with Struts, JSP with VRaptor, JSP with Servlet, JSF with anything else.

The only page code that does not apply to JSE (usually Desktop applications) is the Page 6 with EJB.

JPA Queries and Tips

Hello, how are you?

There are several JPAs “how to” that we can find on the internet, here in this blog, that teaches how to do several tasks with JPA.

Usually I see some people asking questions about Queries with JPA; usually to answer this kind of questions several links are provided trying to find a solution to the question.

Until today I could not find a blog post that puts together a good subject about queries with JPA, tips about performance/utilization, source code to download…
Challenge Accepted

Today we will see:

  • Page 2: Model classes and a class  that will generate database data
  • Page 3: Find method; Use the getReference method to get a better performance, displaying query parameters in the console with the log4j
  • Page 4: JPQL: Queries with simple parameters or objects, Joins, Order By, Navigating through relationships
  • Page 5: JPQL: Functions: AVG, COUNT, MAX, MIN, TRIM, SUM, UPPER, LOWER, MOD, LENGHT, SQRT; Using HAVING, GROUP BY
  • Page 6: JPQL: Filtering Conditions: LIKE, IN, DISTINCT, EMPTY, BETWEEN, NULL, MEMBER OF, EXISTS (Subqueries), ANY, ALL, SOME, CONCAT, CURRENT_DATE, CURRENT_TIME, CURRENT_TIMESTAMP, LOCATE, SIZE, SUBSTRING
  • Page 7: JPA: NamedQuery, querying with dates, warnings about the getSingleResult method
  • Page 8: JPA: NativeQuery, NamedNativeQuery
  • Page 9: JPA: Complex Native Queries
  • Page 10: JPA: Optimizing queries with EJB
  • Page 11: JPA: Pagination
  • Page 12: JPA: Database Hints
  • Page 13: JPA: Creating a object from a query
  • Page 14: JPQL: Bulk Update and Delete
  • Page 15: JPA: Criteria

You will see that in every main class we will invoke the method “CodeGenerator.generateData()”. This class method only creates data in the database; with this data our queries will find the correct results.

In the last page of this post you will find the link to download the source code of this post.

In this post we will use JPA 2.0 with Hibernate as the provider. The database will be the HSQLDB and will be attached to this project. You can download the source code and run the project without the need of any extra configuration. We will not talk about how to set up the HSQLDB because the focus of this post is how to query data of the database.

This post will not use best practices of development in some points. The focus of this post will be to display how the JPA queries works.

Full WebApplication JSF EJB JPA JAAS

Hello, how are you?

This post will be the biggest so far in my blog! We will see a full web application. It will be done will the newest technologies (until today), but I will give some hints to show how to adapt this post to older technologies.

In the end of this post you will find the source code to download. You can use it as you wish. Just go to the last page and do the download. \o/

If you downloaded the code and did not understand something, in this post I will explain every detail found in the code. Just read the subject inside this post that you want.

I will list bellow the technologies that I will use in this post:

  • JSF 2.0 Mojarra – With ManagedBeans as RequestScope and SessionScope.
  • Message Internationalization – File that will have all the messages of our system; it will be easier to translate you pages.
  • Default CSS file that will be imported as a library.
  • EJB 3 – Our DAOs and Façades will be @Stateless.
  • Generic DAO – A generic DAO that will have the CRUD actions to make our life easier.
  • JPA 2 – To map our classes in the DB
  • JAAS – To control the login and the user access to the pages.
  • MVC – I will use this pattern with small modifications.
  • Postgres as database, but I will show how to set up your app to MySQL also.

I will not use TDD – JUnit to test our View/Model/Classes, but in the following link you can see a technique to use the JUnit to test your ManagedBeans: JUnit with HSQLDB, JPA and Hibernate.

Tools that we will use:

This post will have several pages; this first page is just to show the technical details of the post today.

I will not code to interface my model/DAO, just to save space. Remember that you should always code to interfaces (Design Pattern – Strategy).

Before you go to the next pages be sure that you installed the JBoss Tools and the JBoss 7 in this exactly order.

JPA One Table Per SubClass

THERE IS A NEW VERSION OF THIS POST.
CLICK HERE: http://uaihebert.com/?p=1674&page=14

Hello, how are you?

Let us talk today about how to create a database table per subclass of your hierarchy; each table will have only the data of its class. In the last post we had seen how to persist all hierarchy in one table.

I will use the same code from the last post but with the code already edited.

In the end of this post, you will find the source code of the application.

In the following links you can find the last post about this subject and the others post about JPA: JPA Single Table per Class Hierarchy, @ManyToMany Unidirectional and Bidirectional, @OneToMany and @ManyToOne Unidirectional and Bidirectional, OneToOne Unidirectional and Bidirectional, Mapping two Tables in one Class, Mapping Date and Enum, Composite Primary-Key, SequenceGenerator, TableGenerator – Simple Primay Key, Auto Create Schema Script with: Ant, Hibernate 3 and JPA 2, Tutorial Hibernate 3 with JPA 2.

Take a look and see how the code has to be:

package com.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;

@Entity
@Table(name="CAR")
@Inheritance(strategy=InheritanceType.JOINED)
public abstract class Car {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}
package com.model;

import javax.persistence.Entity;

@Entity
public class Beetle extends Car {
    private int gasCapacity;

    public void talk(){
        System.out.println("Herbie!");
    }

    public int getGasCapacity() {
        return gasCapacity;
    }

    public void setGasCapacity(int gasCapacity) {
        this.gasCapacity = gasCapacity;
    }
}
package com.model;

import javax.persistence.Entity;

@Entity
public class Ferrari extends Car {
    private int model;

    // The newest new models will fly... some day! =P
    public void fly() {

    }

    public int getModel() {
        return model;
    }

    public void setModel(int model) {
        this.model = model;
    }
}

After we run the Main class let us take a look and see how our tables will look like:

Now each table has the data of its respective class.

I would like to call your attention to a situation.

Notice that every class of our hierarchy has the id with the same name “id”. If your subclass has a different id attribute name, you will have to map this with a different annotation.

Imagine that the Beetle class has its table id named as “beetleId”; we need to add an annotation in the Beetle class:

package com.model;

import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;

@Entity
@PrimaryKeyJoinColumn(name="beetleId")
public class Beetle extends Car {

    private int gasCapacity;

    public void talk() {
        System.out.println("Herbie!");
    }

    public int getGasCapacity() {
        return gasCapacity;
    }

    public void setGasCapacity(int gasCapacity) {
        this.gasCapacity = gasCapacity;
    }
}


Notice that the primary key now has a different name than Car and Ferrari.

Remember this: if your subclass id field has a name that is not the same of your super class, you will need to use the @PrimaryKeyJoinColumn annotation; the “name” parameter indicates which column will be mapped. If you need to set up the Super Class id column you can use the parameter: “referencedColumnName”.

Let us see now the advantages and the disadvantages of this approach:

  • Advantage: You will be able to have null attributes in your subclasses; you would not be able to do this if you use the one table for all hierarchy strategy. There is a good sql performance over the next pattern that we will see: “One table with all fields per Subclasses”. In the book “Enterprise JavaBens 3.0” the author says that this approach is better than “One table with all fields per Subclasses” only if the database SQL Union is not supported by your database.
  • Disadvantage: It has a lower performance than “One table to all hierarchy strategy”.

Click here to download the source code of this post. Just do not forget to change the user/password.

I hope this post may help you.

If you have any comments/questions just post it.

See you later! \o_