JPA search query using Criteria Builder for multiple columns - jpa

I am trying to make a universal search for my entity with criteria builder where a given text is matched with all the columns in the entity.
String likeSearchText = "%" + searchText + "%";
List<Customer> searchedCustomers = null;
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery query = builder.createQuery(Customer.class);
Root <Customer> root = query.from(Customer.class);
ArrayList<Predicate> conditions = new ArrayList<>();
conditions.add(builder.like(root.<String>get("firstName"), likeSearchText));
conditions.add(builder.like(root.<String>get("lastName"), likeSearchText));
conditions.add(builder.like(root.<String>get("middleName"), likeSearchText));
conditions.add(builder.like(root.<String>get("companyName"), likeSearchText));
conditions.add(builder.like(root.<String>get("industry"), likeSearchText));
query.where(builder.or(conditions.toArray(new Predicate[conditions.size()])));
query.select(root);
searchedCustomers = entityManager.createQuery(query).getResultList();
return searchedCustomers;
When I run this method I always get an empty list. I tried changing the like to notLike and that works perfectly fine by giving me a list containing elements which are not like the given search text so I am really confused as to what's wrong with my like method.
Any kind of help would be appreciated!

I had similar problems when I made some testing and had entities with the same (simple)name in the classpath. So for example there were entities like:
org.example.one.Customer
org.example.two.Customer
If you do not have explicitly set different table names like:
package org.example.one;
#Entity("customer_one")
public class Customer { ...
and
package org.example.two;
#Entity("customer_two")
public class Customer { ...
hibernate might:
mix stuff in the same table in db
try to find field from wrong table when constructing the query
Also I thibk you do not need this:
query.select(root);

Related

Spring Data JPA: Work with Pageable but with a specific set of fields of the entity

I am working with Spring Data 2.0.6.RELEASE.
I am working about pagination for performance and presentation purposes.
Here about performance I am talking about that if we have a lot of records is better show them through pages
I have the following and works fine:
interface PersonaDataJpaCrudRepository extends PagingAndSortingRepository<Persona, String> {
}
The #Controller works fine with:
#GetMapping(produces=MediaType.TEXT_HTML_VALUE)
public String findAll(Pageable pageable, Model model){
Through Thymeleaf I am able to apply pagination. Therefore until here the goal has been accomplished.
Note: The Persona class is annotated with JPA (#Entity, Id, etc)
Now I am concerned about the following: even when pagination works in Spring Data about the amount the records, what about of the content of each record?.
I mean: let's assume that Persona class contains 20 fields (consider any entity you want for your app), thus for a view based in html where a report only uses 4 fields (id, firstname, lastname, date), thus we have 16 unnecessary fields for each entity in memory
I have tried the following:
interface PersonaDataJpaCrudRepository extends PagingAndSortingRepository<Persona, String> {
#Query("SELECT p.id, id.nombre, id.apellido, id.fecha FROM Persona p")
#Override
Page<Persona> findAll(Pageable pageable);
}
If I do a simple print in the #Controller it fails about the following:
java.lang.ClassCastException:
[Ljava.lang.Object; cannot be cast to com.manuel.jordan.domain.Persona
If I avoid that the view fails with:
Caused by:
org.springframework.expression.spel.SpelEvaluationException:
EL1008E:
Property or field 'id' cannot be found on object of type
'java.lang.Object[]' - maybe not public or not valid?
I have read many posts in SO such as:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to
I understand the answer and I am agree about the Object[] return type because I am working with specific set of fields.
Is mandatory work with the complete set of fields for each entity? Should I simply accept the cost of memory about the 16 fields in this case that never are used? It for each record retrieved?
Is there a solution to work around with a specific set of fields or Object[] with the current API of Spring Data?
Have a look at Spring data Projections. For example, interface-based projections may be used to expose certain attributes through specific getter methods.
Interface:
interface PersonaSubset {
long getId();
String getNombre();
String getApellido();
String getFecha();
}
Repository method:
Page<PersonaSubset> findAll(Pageable pageable);
If you only want to read a specific set of columns you don't need to fetch the whole entity. Create a class containing requested columns - for example:
public class PersonBasicData {
private String firstName;
private String lastName;
public PersonBasicData(String firstName, String lastName) {
this.firstName = fistName;
this.lastName = lastName;
}
// getters and setters if needed
}
Then you can specify query using #Query annotation on repository method using constructor expression like this:
#Query("SELECT NEW some.package.PersonBasicData(p.firstName, p.lastName) FROM Person AS p")
You could also use Criteria API to get it done programatically:
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<PersonBasicData> query = cb.createQuery(PersonBasicData.class);
Root<Person> person = query.from(Person.class);
query.multiselect(person.get("firstName"), person.get("lastName"));
List<PersonBasicData> results = entityManager.createQuery(query).getResultList();
Be aware that instance of PersonBasicData being created just for read purposes - you won't be able to make changes to it and persist those back in your database as the class is not marked as entity and thus your JPA provider will not work with it.

JPA 2.1 / Eclipselink: Reuse Criteria Queries as Named Queries

i am trying to reuse a dynamic query as a named query as described here:
https://wiki.eclipse.org/EclipseLink/Release/2.5/JPA21#Add_Named_Query
the goal is to build the criteria-query only once and then reuse it as a namedquery if parameter did not change.
public static List<User>getUserByParameter(ParameterMap parameter){
EntityManager em = getEntityManager();
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<User> criteriaQuery = builder.createQuery(User.class);
Root<User> user = criteriaQuery.from(User.class);
List<Predicate> predicates = new ArrayList<Predicate>();
//...build up the query depending on parameter
if (null != parameter.getStatus()){
predicates.add(builder.equal(user.<Integer>get("status"), parameter.getStatus()));
}
//etc.
criteriaQuery.select(user).where(predicates.toArray(new Predicate[]{}));
Query query = em.createQuery(criteriaQuery);
//now register this query as a namedQuery
em.getEntityManagerFactory().addNamedQuery("userByParameter", query);
return query.getResultList();
}
i thought about something like:
public static List<User>getUserByParameter(ParameterMap parameter){
Query userByParameter = em.createNamedQuery("userByParameter");
if (null != userByParameter){
return userByParameter.getResultList();
}else {
//build the dynamic query as above
}
}
this results in a nullpointer as the namedQuery doesn't exist the first time.
how can i reuse the query in the same method or in other words, how can i check in a clean way (without using try-catch) if a namedquery exists?
I'm not sure I understand the problem you are looking to solve. The getUserByParameter method is something that should be built on the EntityManagerFactory, when it is first initialized or obtained. Feel free to add properties to your factory if you wish to keep track of what you have added already, but these should be done only once, upfront during initialization.
What is confusing is that you are expecting the query results to be reused - named queries are designed to help reduce the cost of parsing and preparing queries. EclipseLink has a query cache feature that can return the results for you if the same parameters are used, without you needing to cache the query, its parameters and the results yourself.

EclipseLink JPA Dynamic model and Criteria Query

i like to create a (crtieria-) query against a dynamic model but i always get the exception
No [EntityType] was found for the key class [demo.DynamicResult] in the Metamodel
at the last line
final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
final CriteriaQuery<Tuple> query = criteriaBuilder.createTupleQuery();
DynamicHelper helper = new DynamicHelper(JpaHelper.getServerSession(emf));
Class<? extends DynamicEntity> rootclass = helper.getType("demo.DynamicResult").getJavaClass();
query.from(rootclass);
The DynamicResult gets generated with following code
ServerSession serverSession = JpaHelper.getEntityManager(entityManager).getServerSession();
DynamicClassLoader dcl = DynamicClassLoader.lookup(serverSession);
JPADynamicHelper jpaDynamicHelper = new JPADynamicHelper(entityManager);
Class<?> dynamicResult = dcl.createDynamicClass("demo.DynamicResult");
JPADynamicTypeBuilder dynamicResultBuilder = new JPADynamicTypeBuilder(dynamicResult, null, "DynamicResult");
dynamicResultBuilder.addDirectMapping("id", String.class, "id");
//Some more addDirectMappings ....
dynamicResultBuilder.setPrimaryKeyFields("id");
type = dynamicResultBuilder.getType();
jpaDynamicHelper.addTypes(false, false, type);
What did I missed ?
Is this kind of query possible at all ?
Regards
You may be hitting https://bugs.eclipse.org/bugs/show_bug.cgi?id=429760 bug. There was a problem with copying newly created dynamic entity metadata into current session.
Check this bug and attached diffs. jpa/eclipselink.jpa.test/src/org/eclipse/persistence/testing/tests/jpa/dynamic/simple/SimpleQueryTestSuite.java test suite contains test which does similar thing - creates dynamic entity and runs JPQL query against it within the same transaction (UnitOfWork).
I would try latest 2.7.0 or 2.6.1 (do not use .WAS) build from https://www.eclipse.org/eclipselink/downloads/nightly.php to see if it works fine for you.

JPA Criteria construct with non-entity parameter

I want to create a list of complex DTO objects with data from several Entities and one non-Entity-parameter. Let's say my DTO class has constructor:
public MyDto(String entityField, String someString) {...}
and I would like to use the CriteriaBuilder.construct method to create my list by doing like this:
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<MyDto> query = builder.createQuery(MyDto.class);
Root<MyEntity> root = query.from(MyEntity.class);
builder.construct(MyDto.class, root.get("entityField"), someString);
...
but I am not allowed to do it, because the construct method wants from me only javax.persistence.criteria.Selection arguments.
The question: is there is a way to do it similar to this (at one blow) with Criteria API? Or I need to load MyEntity objects first and go through them and create a list of DTOs (not so pretty)?
I use this approach each time I've a projection that collect fields from different entities or for privacy reason i must not return some data (for example passwords)
query.select(
builder.construct(
MyDto.class,
root.get("myfield"), // for field
cb.literal(1), // for number
cb.literal("blah blah") // for string
));

Entity Framework IQueryable

I'm having problems querying the entity model to get additional information.
My db has a Program table with a one to many relation with an Events table. The Entity model generates the relationships just fine, but I'm unable to figure out how to query the model to get the progam object with its events.
I can do this:
var foo = from program in entities.ProgramSet
where program.StartDate > DateTime.now
orderby program.StartDate
select program;
No problems there. From what I've found on Microsofts Page (Shaping queries with Entity framework): msdn.microsoft.com/en-us/library/bb896272.aspx, if I wanted to get the child objects, I just do the following:
// Define a LINQ query with a path that returns
// orders and items for a contact.
var contacts = (from contact in context.Contact
.Include("SalesOrderHeader.SalesOrderDetail")
select contact).FirstOrDefault();
However, there is no .Include or Include that I can find on the query.
Any suggestion? I know that I can do a foreach across the results, then run a .Events.Load() on it, but doesn't that force the IQueriable result to execute the sql, instead of optomize it to run only when a .ToList() etc is called on it?
Here is some sample code from my project:
public class ProgramRepository : CT.Models.IProgramRepository
{
CTEntities db = new CTEntities();
public IQueryable<Program> FindAllPrograms()
{
return db.ProgramSet;
}
public IQueryable<Program> FindUpcomingPrograms()
{
var programs = from program in FindAllPrograms()
where program.StartDate > DateTime.Now
orderby program.StartDate
select program;
return programs;
}
With the FindUpComingPrograms I would like to have it also include the Events Data. There is a relationship between the Program and Events model. Program has a List<Events> property, that I would like to fill and return with the IQueryable method.
Thanks again!
The Include Function is part of the ObjectQuery object...
I think you are going to need to re-write your query to look something like this:
var contacts = context.Contact.Include("SalesOrderHeader.SalesOrderDetail").FirstOrDefault();
//Not sure on your dot path you might have to debug that a bit
Here is an Article that has some examples...