How to convert data from query with JPA Repository - sql

I have a query that seems to work fine.
public interface GameRepository extends JpaRepository<Game,Integer> {
#Query(value="SELECT Cast(bifnb as varchar) bifnb , count(*) FROM (SELECT count(fk_game) as nb FROM public.game INNER JOIN score s on game.id_game = s.fk_game WHERE fk_board_game = 2014 GROUP BY fk_game) as bifnb group by bifnb", nativeQuery = true)
List<StatisticDto> nbplayer();
}
But when I try to use it with JPA and type StatisticDTO , I get the following error:
context with path [/api] threw exception [Request processing failed; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap] to type [****.statistics.payload.StatisticDto]] with root cause
So I tried with the same query and : List<Object> nbplayer();
It works but I don't know how to work with a List I prefer to use a StatisticDto.

Assuming StatisticDTO looks like this:
public class StatisticDTO {
private String key;
private Integer value;
// ... getter/setter
}
This query should work:
#Query(value="SELECT Cast(bifnb as varchar) as \"key\" , count(*) as \"value\" FROM (SELECT count(fk_game) as nb FROM public.game INNER JOIN score s on game.id_game = s.fk_game WHERE fk_board_game = 2014 GROUP BY fk_game) as bifnb group by bifnb", nativeQuery = true)
List<StatisticDto> nbplayer();
See this article about transforming results to DTO for more information.
I've quoted the aliases because I think key and value are special keywords.

Related

How to check collection for null in spring data jpa #Query with in predicate

I have this query in my spring data jpa repository:
#Query("SELECT table1 FROM Table1 table1 "
+ "INNER JOIN FETCH table1.error error"
+ "WHERE table1.date = ?1 "
+ "AND (COALESCE(?2) IS NULL OR (table1.code IN ?2)) "
+ "AND (COALESCE(?3) IS NULL OR (error.errorCode IN ?3)) ")
List<Table1> findByFilter(Date date, List<String> codes, List<String> errorCodes);
When I run this query, it shows me this error by console:
org.postgresql.util.PSQLException: ERROR: operator does not exist: character varying = bytea
Hint: No operator matches the given name and argument types. You might need to add explicit type casts.
Position: 1642
However if I run the query without the (COALESCE (?2) IS NULL OR part, just the table1.code IN ?2, it does work
Does anyone know what this error could be due to?
COALESCE with one parameter does not make sense. This is an abbreviated CASE expression that returns the first non-null operand. (See this)
I would suggest you to use named parameters instead of position-based parameters. As it's stated in the documentation this makes query methods a little error-prone when refactoring regarding the parameter position.
As it's stated in documentation related to the IN predicate:
The list of values can come from a number of different sources. In the constructor_expression and collection_valued_input_parameter, the list of values must not be empty; it must contain at least one value.
I would suggest you also avoid to use outdated Date and use instead java 8 Date/Time API.
So, taken into account all above, you should use a dynamic query as it was suggested also in comments by #SimonMartinelli. Particularly you can have a look at the specifications.
Assuming that you have the following mapping:
#Entity
public class Error
{
#Id
private Long id;
private String errorCode;
// ...
}
#Entity
public class Table1
{
#Id
private Long id;
private LocalDateTime date;
private String code;
#ManyToOne
private Error error;
// ...
}
you can write the following specification:
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.CollectionUtils;
public class TableSpecs
{
public static Specification<Table1> findByFilter(LocalDateTime date, List<String> codes, List<String> errorCodes)
{
return (root, query, builder) -> {
root.fetch("error", JoinType.LEFT);
Predicate result = builder.equal(root.get("date"), date);
if (!CollectionUtils.isEmpty(codes)) {
result = builder.and(result, root.get("code").in(codes));
}
if (!CollectionUtils.isEmpty(errorCodes)) {
result = builder.and(result, root.get("error").get("errorCode").in(errorCodes));
}
return result;
};
}
}
public interface TableRepository extends CrudRepository<Table1, Long>, JpaSpecificationExecutor<Table1>
{
default List<Table1> findByFilter(LocalDateTime date, List<String> codes, List<String> errorCodes)
{
return findAll(TableSpecs.findByFilter(date, codes, errorCodes));
}
}
and then use it:
List<Table1> results = tableRepository.findByFilter(date, Arrays.asList("TBL1"), Arrays.asList("ERCODE2")));

SQLNative query returning empty results

I'm trying to execute a query which needs 4 tables :
#Query(value="SELECT e.* FROM erreur e, synop sy, synop_decode sd, station st WHERE e.id_synop = sd.id_synop_decode "
+ "and sd.id_synop_decode = sy.id_synop" + " and DATE(sy.date)= :date and "
+ "sy.id_station = st.id_station and st.id_station= :stationId", nativeQuery=true)
public List<Erreur> recherche(#Param("date") Date date, #Param("stationId") Long stationId);
This query works fine et native sql, i pass an existing stationId and a date like the following :
SELECT e.* FROM erreur e, synop sy, synop_decode sd, station st WHERE e.id_synop = sd.id_synop_decode and sd.id_synop_decode = sy.id_synop
and DATE(sy.date)= '2019-05-27' and sy.id_station = st.id_station and st.id_station= 60355;
This query works fine in Mysql Workbench.
Here's the actual controller i'm using for testing purpose :
#GetMapping("/station/{stationId}/erreurs/today")
public List<Erreur> getTodayErreurByStationId(#PathVariable Long stationId)
{
List<Erreur> erreurs = new ArrayList<Erreur>();
Optional<Station> stationOptional = stationRepository.findById(stationId);
if(stationOptional.isPresent())
{
return erreurRepository.recherche(new Date(), stationId);
}
return null;
}
The expected results are the actual "Ererur" objects in my array list, but RestClient just returns an empty array [], while the query works just fine in mysql like i described it above.
So my question is : How can i write this query into Hql language so that i can return the right entities. Or how can i map my sql results to my target custom calss "Erreur"?
#Entity
#Getter #Setter #NoArgsConstructor
#Table(name="erreur")
public class Erreur {
public Erreur(int section, int groupe, String info) {
this.section = section;
this.groupe = groupe;
this.info = info;
}
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id_erreur")
private Long id;
#ManyToOne(cascade= {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH},
fetch=FetchType.LAZY)
#JsonIgnore
#JoinColumn(name="id_synop")
private SynopDecode synopDecode;
#OneToOne
#JoinColumn(name="id_controle")
private Controle controle;
#ManyToOne(cascade= {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH},
fetch=FetchType.LAZY)
#JsonIgnore
#JoinColumn(name="id_station")
private Station station;
#Column(name="section")
private int section;
#Column(name="groupe")
private int groupe;
#Column(name="info")
private String info;
}
If you want to use jpa convention directly then you will have to make associations between different entities i.e. how two entities are linked. When we define these associations then spring jpa knows how to convert method name or custom queries into SQL.
Your code will need to be something like
public class Erreur {
...
#ManyToOne
#JoinColumns//define how Erreur and SynopeDecone are linked
private SynopDecode synopDecode;
...
public class SynopDecode {
...
#ManyToOne // or #OneToOne its not mentioned in question how these two are linked
#JoinColumns//define how SynopDecode and Synop are linked
private Synop synop;
...
Then you can write your query like
#Query("select e from Erreur e LEFT JOIN e.synopDecode sy LEFT JOIN sy.synop sy WHERE DATE(sy.date) = :date AND sy.id_station = :stationId")
List<Erreur> getByDateAndStationId(#Param("date") Date date, #Param("stationId") Long stationId)
You can't use method name based query because you want to use SQL function to match only "date" part of your date and not the whole timestamp.
You can use jpa methods by conventions.
Assuming SynopDecode has property like:
//SynopDecode class
#ManyToOne
private Synop synop;
//repository interface
List<Erreur> findByStationIdAndSynopDecodeSynopDate(Long stationId, Date date);
//or
//List<Erreur> findByStationIdAndSynopDecode_Synop_Date(Long stationId, Date date);
UPDATE
As Punit Tiwan (#punit-tiwan) note that, the above methods used for a specific datettime.
You can use methods below for just DATE.
//repository interface
List<Erreur> findByStationIdAndSynopDecodeSynopDateBetween(Long stationId, Date startOfDate, Date endOfDate);
//or
//List<Erreur> findByStationIdAndSynopDecode_Synop_DateBetween(Long stationId, Date startOfDate, Date endOfDate);
I figured a way to get the same results as my SQL Query using the #Query annotation and accessing object properties like this :
#Query("from Erreur e where e.synopDecode.synop.station.id = :stationId and "
+ "DATE(e.synopDecode.synop.date) = :date")
public List<Erreur> recherche(#Param("date") Date date, #Param("stationId") Long stationId);
I think it solves my problem, thanks for the help

Retrieving entities by checking a filtered subset of childen

I have entities of the following structure:
#Entity
public Class MyObject {
...
public List<Status> statuses;
...
}
#Entity
public Class Status {
...
public Long creationTime;
public Double range;
#JoinColumn(name = "myObject",
nullable = false,
unique = false,
updatable = false)
#ManyToOne(optional = false)
#NotNull
private MyObject myObject;
...
}
I got n entities of the type MyObject which can have m statuses. Ownership lays on the side of the Status entity which cannot be changed. I am currently trying to filter the entities that are greater-equal than a certain range. My current query retrieves a result for every status that has a range that is greater-equal than the one given as a parameter:
final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
final CriteriaQuery<MyObject> cq = cb.createQuery(MyObject.class);
final Root<MyObject> myObject = cq.from(MyObject.class);
final Root<Status> statuses = cq.from(Status.class);
final Predicate[] predicates = {
cb.equal(myObject.get(MyObject_.id), statuses.get(Status_.myObject).get(MyObject_.id)),
cb.ge(statuses.get(Status_.range), range)
};
cq.select(myObject).where(predicates);
return entityManager.createQuery(cq).getResultList();
Desired is, that I only get the entities of MyObject, for which the most current status that has a range is greater-equal than the one given as a paramter. I am pretty sure that I have to group the list of statuses first and sort by creation time but I am not really sure how to combine all of this, especially not in the Criteria API.
EDIT:
At least I was able to create a SQL query that does what I want:
SELECT * FROM MyObject O INNER JOIN (SELECT * FROM Status WHERE Status.CREATIONTIME IN (SELECT MAX(Status.CREATIONTIME) FROM Status WHERE (Status.RANGE IS NOT NULL AND Status.RANGE >= 30) GROUP BY Status.myObject)) S ON O.ID = S.myObject;
I am trying to rebuild this query using the Criteria API but don't really know how to include the embedded SELECT in the JOIN. Any help would be appreciated!

Hql query using dot´s in the response parameters

I am accesing to the database using a Dto with some entities and I want to improve the request without modifing my dto and removing the fetch so hibernate don´t return all the data from all the entities (hibernate is set to lazy), I tried with the next, but it´s not working:
StringBuilder hql = new StringBuilder();
hql.append(" select d.id as id, ce.cod as clasification.cod ");
hql.append(" from Document d");
hql.append(" join d.clasificacionEntity ce");
The working hql request:
StringBuilder hql = new StringBuilder();
hql.append(" select d");
hql.append(" from Document d");
hql.append(" join fetch d.clasificacionEntity ce");
The problem is when I try to use "ce.cod as clasification.cod" the second dot gives me a error, there is other way to do that? , thanks a lot!!!
My dto result is:
DocumentDto{
private id
private clasificacionEntityDto;
}
And
clasificacionEntityDto {
private cod
}
When you write this code:
hql.append(" select d.id as id, ce.cod as clasification.cod ");
You tell on parser d.id named id and ce.cod named clasification.cod
The last alias is wrong! A correct name is clasification or cod.
If you want to point properties of ce.cod (cod which data type has?) you can point after extraction of your result.
You don't mention how you are transforming the query result into your DTO entities. One simple solution that does not require you to alter your DTO classes.
// select only the fields you need from your query
StringBuilder hql = new StringBuilder();
hql.append(" select d.id as id, ce.cod as cod ");
hql.append(" from Document d");
hql.append(" join d.clasificacionEntity ce");
// ... etc. Then get back your results as raw type
List<Object[]> rows = crit.list();
Then loop through your results and create your DTOs manually. Note that this example assumes that your document has a single classification.
List<DocumentDTO> documents = new ArrayList<DocumentDTO>();
for ( Object[] row: rows ) {
Long id = (Long)row[0];
String cod = (String)row[1];
ClassificationEntityDTO ce = new ClassificationEntityDTO(cod);
DocumentDTO d = new DocumentDTO(id, ce);
documents.add(d);
}
See this question
AliasToBeanResultTransformer(MyDTO.class) fails to instantiate MyDTO
At the end I just create a dto like this:
DocumentDto{
private id
private String clasificacionEntityDtoCod;
}
and set it like this:
StringBuilder hql = new StringBuilder();
hql.append(" select d.id as id, ce.cod as clasificacionEntityDtoCod ");
hql.append(" from Document d");
hql.append(" join d.clasificacionEntity ce");

Is there a way to do a "in" statment in javax.persistence.Query [duplicate]

I have the following parametrised JPA, or Hibernate, query:
SELECT entity FROM Entity entity WHERE name IN (?)
I want to pass the parameter as an ArrayList<String>, is this possible? Hibernate current tells me, that
java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.lang.String
Is this possible at all?
ANSWER: Collections as parameters only work with named parameters like ":name", not with JDBC style parameters like "?".
Are you using Hibernate's Query object, or JPA? For JPA, it should work fine:
String jpql = "from A where name in (:names)";
Query q = em.createQuery(jpql);
q.setParameter("names", l);
For Hibernate's, you'll need to use the setParameterList:
String hql = "from A where name in (:names)";
Query q = s.createQuery(hql);
q.setParameterList("names", l);
in HQL you can use query parameter and set Collection with setParameterList method.
Query q = session.createQuery("SELECT entity FROM Entity entity WHERE name IN (:names)");
q.setParameterList("names", names);
Leaving out the parenthesis and simply calling 'setParameter' now works with at least Hibernate.
String jpql = "from A where name in :names";
Query q = em.createQuery(jpql);
q.setParameter("names", l);
Using pure JPA with Hibernate 5.0.2.Final as the actual provider the following seems to work with positional parameters as well:
Entity.java:
#Entity
#NamedQueries({
#NamedQuery(name = "byAttributes", query = "select e from Entity e where e.attribute in (?1)") })
public class Entity {
#Column(name = "attribute")
private String attribute;
}
Dao.java:
public class Dao {
public List<Entity> findByAttributes(Set<String> attributes) {
Query query = em.createNamedQuery("byAttributes");
query.setParameter(1, attributes);
List<Entity> entities = query.getResultList();
return entities;
}
}
query.setParameterList("name", new String[] { "Ron", "Som", "Roxi"}); fixed my issue