uaiMockServer – Create a Mock Rest Server with a single command line

Hello how are you?

Have you ever needed to invoke a REST service, but this service was not created yet?

Imagine that you are developing an APP that needs to invoke an inexistent REST service. You will need to create a fake code that will be replaced once that the real code is finished. No matter if you are working with Java, .NET, PHP, Ruby, Python, etc. You will always need to create a fake invocation method if the REST service is not ready yet.

When we are programming in our unitary test we face the same problem. We will need to create a Mock code that will be invoked during the tests. The problem with this approach is that the real code is never invoked.

How can we solve this problem? Is there a solution that works for delphi, .NET, PHP, Java, Android, IOS, WindowsPhone, etc?

I present to you now my most recent creation: “uaiMockServer”.

With uaiMockServer you will be create a mock server using only a JAR file and a config file. With this server you will be able to execute real HTTP requests, but using your test data.

There are two ways of using uaiMockServer: Standalone and Unit Tests


To use the uaiMockServer as a Standalone server you will manually type the command that starts it. Run the command in a prompt:

java -jar uaiMockServer-{VERSION}.Standalone.jar

You will only need the config file, that we will talk about very soon.

In the sample config file there is a mapping using the port 1234. If you are using linux, type the command:

curl localhost:1234/uaiMockServer/

The HTTP Response will contain a JSON.

Unit Test

First step is to add the project in your pom:


Now you can create a test code like:

public class YourTest {
    private static UaiMockServer uaiMockServer;
    public static void beforeClass() {
        uaiMockServer = UaiMockServer.start();
    public static void afterClass() {
    public void aTest() {
        final Customer customer = // invoke the URL
        assertTrue(customer != null);

You will be able to invoke the URL using any kind of framework. Below you will see a code sample using the RestEasy framework doing a request mapped in the sample config file (that we will see soon):

public void isGetRootReturning200() {
    final String url = "http://localhost:1234/uaiMockServer/";
    Client client = ClientBuilder.newClient();
    Response response =;
    assertEquals(200, response.getStatus());

What is the gain in the test? You will not need a mock code anymore. You can fire a HTTP request from your JUnit test.


To run the project you will need a config file. A simple sample would be like below:

com.uaihebert.uaimockserver {
    port = 1234
    host = localhost
    fileLog = false
    consoleLog = true
    context = /uaiMockServer
    defaultContentTypeResponse = "text/html;charset=UTF-8"
    routes = [
            request {
                path = "/"
                method = "GET"
            response {
                contentType = "application/json;charset=UTF-8"
                statusCode = 200
                body = """{"mockBody":{"title":"Hello World"}}"""

The file must have the .config extension and is not in the JSON format, but has a superset format of the JSON – HCON – used in configurations files (click here for more details).

With this file you can set up the port that will be invoked, the host, header, queryParm and other several options that are described in the uaiMockServer documentation.

Notice that in the configuration was created a request and a response; with these configurations you can mock every request that you want.

If you are going to use the Standalone version the config file must be in the same directory of the JAR file. You can set a different path with the command:

java -jar uaiMockServer-{VERSION}.Standalone.jar FULL_FILE_PATH

If you will run the project in your Unit Tests (like JUnit) you must put the config file in the “src/test/resources” maven folder. Or you can pass the full path like:

uaiMockServer = UaiMockServer.start(FULL_FILE_PATH);

It is free?

Yes, it is. Use it at your will.

Is open source? Yes:

Where is the documentation?

Where can I find the Standalone and the sample Config file:

It has any automated test? Yes, we have a lot of tests and we got 100% code coverage.

What about performance?

In the GIT there is a test that executes 300 requests in less than 2s.

Thanks to:

EasyCriteria has evolved to uaiCriteria. New name and more features

Hello, how are you?

I am very happy to announce the release of the uaiCriteria, the EasyCriteria evolution.

Was it really needed to change the framework name? Yes, sadly it was. I found another framework with the same name, that is why I decided to change the name (I do not want any kind of legal problems). The difference of the framework is that the other framework works with MetaModel, and uaiCriteria works with strings as parameters.

About the framework name change:

  • Your code will work with this new version without a problem, the code is retro compatible
  • All EasyCriteria classes are annotated with @Deprecated and will be removed in the next version
  • The new classes has all the methods of the old version. If you want to change for the new code just “replace” the text EasyCriteria for UaiCriteria in your code
  • Again, I did not want to change the framework name but I do not want legal problems

The framework now has a mascot:



The new version has a lot of new stuff. Let us talk first about the structural changes:

  • The site has changed, now is
  • The repository has changed, now is on GIT (requested by a lot of develpers)
  • The SONAR plug-in was added to the pom.xml to help with code the code coverage and static analysis:

    uaicriteria cobertura

    uaicriteria cobertura

  • The old site will be deactivated, but all the old documentation was migrated.
  • The current API has some criteria limitations, using HAVING in the criteria is something that is not possible. We will create a new Interface/API to use with complex criteria – I am looking for a new name for the new Interface, could you suggest me one? (:

Let us talk about the new features:

Welcome to Batoo

Batoo is a JPA provider like EclipseLink or Hibernate. In this new version we got a good number of methods tested with Batoo.

Notice that I talked about “a good number of methods” but not most of the methods. Unfortunately Batoo has several problems with JPQL and Criterias, and I could not cover most of the methods with it.

uaiCriteria framework support almost all methods with EclipseLink, Hibernate and OpenJPA.


It is possible to choose which attributes will be returned:

    Person p

If we transform the JPQL above in Criteria:

finalUaiCriteria<Person> uaicriteria =
    UaiCriteriaFactory.UaiCriteriaFactory.createMultiSelectCriteria(entityManager, Person.class);


finalList multiselectList = uaiCriteria.getMultiSelectResult();

Some considerations about the code above:

  • Object will be returned if you select only one attribute
  • Object[] will be returned if you select more than one attribute
  • The JPA provider may return Vector instead of Object[] (with my tests EclipseLink was returning a Vector)


Now it is possible to do a subQuery like below:

select p from Person p 
where in
        (select from Dog dog where dog.cute = true)

I will not talk about the several lines of native JPA criteria needed to do the JPQL above, but with UaiCriteria is very easy to do:

final UaiCriteria<Person> uaiCriteria = UaiCriteriaFactory.createQueryCriteria(Person.class);
final UaiCriteria<Dog> subQuery = uaiCriteria.subQuery("", Dog.class); //
subQuery.andEquals("cute", true);
uaiCriteria.andAttributeIn("id", subQuery); //

All you need to do is to create a subQuery informing its return; then call the method attributeIn of the root criteria.

MapIsEmpty [NOT]

The isEmpty method can be used with maps:


AttributeIn [NOT]

If you want to validate if a value is inside a list like the JPQL:

select p
from Payment p
    p.statusEnum in :enumList

You can create the JPQL above like:

final UaiCriteria<Payment> uaiCriteria = 
                           Arrays.asList(StatusEnum.VALUE_01, StatusEnum.VALUE_02));

The attribute could be a enum, integer, String, etc.

MemberOf [NOT]

The query below:

select d
from Departament d
where :person member of d.employeeList

Could be created like:

final UaiCriteria<Departament> uaiCriteria = 
uaiCriteria.andIsMemberOf(person, "employeeList");

Count and CountRegularCriteria

Now it is possible to do a count with a MultiSelect criteria. The count method was renamed to countRegularCriteria(). It works like the older version, just the name was refactored to make things more distinct.


Sometimes you need to count an attribute instead of an entity:

select count(
from Person p

You can run the JPQL above like:

final UaiCriteria<Person> uaiCriteria = 
final List result = uaiCriteria.getMultiSelectResult();

GroupBy and Aggregate Functions

Now it is possible to do a GroupBy with aggregate functions: sum, diff, divide, module,  etc.

select sum(p.value), p.status
from Payment p
group by p.status

Could be executed like:

final UaiCriteria<Payment> uaiCriteria = 
final List result = uaiCriteria.getMultiSelectResult();

New Maven Import

If you want to use the new version, just add the xml below to your pom.xml:


I hope you liked the news.

Do not forget to visit the new site ———–>

If you have any doubts, questions or suggestions just post it.

See you soon. o_

JPA Hibernate Alternatives. What can I use if JPA or Hibernate is not good enough for my project?

Hello, how are you?

Today we will talk about situations that the use of the JPA/Hibernate is not recommended. Which alternatives do we have outside the JPA world?

What we will talk about:

  • JPA/Hibernate problems

  • Solutions to some of the JPA/Hibernate problems

  • Criteria for choosing the frameworks described here

  • Spring JDBC Template

  • MyBatis

  • Sormula

  • sql2o

  • Take a look at: jOOQ and Avaje

  • Is a raw JDBC approach worth it?

  • How can I choose the right framework?

  • Final thoughts

I have created 4 CRUDs in my github using the frameworks mentioned in this post, you will find the URL at the beginning of each page.

I am not a radical that thinks that JPA is worthless, but I do believe that we need to choose the right framework for the each situation. If you do not know I wrote a JPA book (in Portuguese only) and I do not think that JPA is the silver bullet that will solve all the problems.

I hope you like the post. [=

My new Book – Effective JPA is out! (portuguese only)

Hello, how are you?

I am very happy to announce that my new book was published today, and it can be found in here:


It talks about JPA spec and good practices, BUT Portuguese only. [=

I wish that, before the end of this year, I will be able to write a new post. It is about a subject that was not talked about so detailed in this blog. I hope you guys like it! ;)

See you guys soon! o_

EasyCriteria 3.0 – New Features

Hello, how are you?

It is with a great joy that I announce a new version of the EasyCriteria framework. This new version will make easier and increase the framework utilization (click here if you do not know nothing about the EasyCriteria framework).

2 new features and a huge refactoring are present in this new version, these features/refactoring deserve a new major version in the framework. The new version is now 3.0.

Let us see what is new:

Extreme Refactoring

This refactoring was done to reduce the code complexity, to apply more code patterns, using “final” attribute to make a better memory use and changing “pom.xml” dependences.

Version 3.0

Version 2.2

Notice in the pictures above that the Cyclomatic complexity has been reduced a lot (click here to know more about Cyclomatic complexity). Just the “utils” package that had a small increase of complexity but it had some lines removed.

Multiple Joins! o/

It might look that multiple joins are something easy, but until this version, it was the major feature to be released. Now it is possible to do all the joins that you want, take a look at the code below:

EasyCriteria<Person> easyCriteria = EasyCriteriaFactory.createQueryCriteria(getEntityManager(), Person.class); 
easyCriteria.andEquals("", "ACME");

Looking at the code above it is possible to see that it is possible to do “joins” for every method in the framework. Notice that the “andEquals” method is crossing all possible relationships in the entity Person.

The orderBy method also supports multiple joins.

This change will make the EasyCriteria API simpler, now it will not be necessary to call any method with Join in the name to create a “where”. The andJoinEquals method (or any other method with the word “Join” that creates a condition, e.g.: andJoinGreaterThan, andJoinStringIn), is deprecated and will be removed in future versions.


This method allows doing a count in the query result. Take a look at the code below:

EasyCriteria<Person> easyCriteria = EasyCriteriaFactory.createQueryCriteria(getEntityManager(), Person.class);

The code above would count all Person found in the database. But, what about the complicated queries… would it do the count?

The query below would work without problems:

List<String> names = new ArrayList<String>();

EasyCriteria<Manufacturer> easyCriteria = EasyCriteriaFactory.createQueryCriteria(getEntityManager(), Manufacturer.class);
easyCriteria.andStringNotIn("", names);


List<Manufacturer> manufactures = easyCriteria.getResultList();

Notice in the code above that it is possible to do a count and with the same object execute the query.

One important thing to notice is that the count method ignores the values defined in the methods setFirstResult and setMaxResults. To do a count with firstResult and maxResults it would be necessary to do a SubQuery, and this is not supported yet.

100% of Coverage

This project still with 100% of coverage in the unit tests with OpenJPA, EclipseLink and Hibernate, JUnit and the Cobertura framework.

I hope that this tool will be really useful to you.

To use it with maven, just add to the pom:


To manually download it, click here:

See you later.

EasyCriteria – New Functionalities

Hello, how are you?

I am here to talk about the new version of the EasyCriteria framework.

To those that are not familiar with EasyCriteria, EasyCriteria is a framework that makes easier the JPA Criteria utilization.


select p from Person p

It would be translated to the following JPA Criteria:

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

That is a loot code to do a simple query. But, how do we solve this problem?

Just use the EasyCriteria framework. The query above could be executed like below:

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

With EasyCriteria is very easy to use JPA Criteria. Here are the EasyCriteria advantages:

  1. Allow JPA implementation portability: You could change your implementation to Hibernate, EclipseLink and OpenJPA without a problem.
  2. 100% test coverage test coverage
  3. Easy to use: EasyCriteria has the principle of exposing as little API as possible. The developer will use only the EasyCriteria interface.
  4. Good to be used by JPA rookies. Its methods are well detailed and documented.
  5. It can be found in the Maven repositories.

What is new in EasyCriteria?
The first this is the Criteria Transfer Object (CTO). Now it is possible to create an object in the view layer, without a EntityManager, to load all information related to the query to be executed in the database.
Check the code below to see how the CTO works:

public void controllerMethod(Integer id){
   EasyCriteria easyCTO = EasyCriteriaFactory.createEasyCTO();
   easyCTO.andEquals("id", id);

// and in the method
public void deactivateCar(EasyCriteria easyCTO){
    EasyCriteria<Car> easyCriteria = EasyCriteriaFactory.createQueryCriteria(entityManager, Car.class, easyCTO);
    Car car = easyCriteria.getSingleResult();

It is very simples to build your query at the same layer that has the parameters, and send it to the business layer execute it.

The other new functionality of this version is the LowerCase comparison:

boolean toLowerCase = true;

EasyCriteria<Person> easyCriteria = EasyCriteriaFactory.createQueryCriteria(getEntityManager(), Person.class);
easyCriteria.andEquals(toLowerCase, "name", "MARY");

The LowerCase was a functionality very requested by the framework users. If you want a functionality, just ask for it. [=

If you want to download the jar by the link, here is it:

If you want to use Maven to download it just add the dependency below:


I hope  that these new functions make your guys happy!

See you soon! o_

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:


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

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);;
TypedQuery<Person> query = entityManager.createQuery(criteriaQuery);

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);

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 = 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 ( = 1) or ( = 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 ( = 1 and = 'Sing Out') or ( = 2 and = '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 ( and Sasaki (

Here it is possible to see the framework official page: And the best, it is open source (

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.


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);

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 ( you will find all documentation.

If you have any doubt, just post it.

See you soon! o_