I have following very straightforward code.
#SqlResultSetMapping(name="getTestTable", classes = {
#ConstructorResult(targetClass = someEntity.class,
columns = {
#ColumnResult(name="some_date", type=Date.class)
})
})
Query:
getEntityManager().createNativeQuery("SELECT distinct some_date from test " );
List<someList > list=query. getResultList();
Entity:
someEntity
#Column(name = "some_date")
#JsonFormat(pattern="dd/MM/yyyy")
private Date someDate;
public someEntity(java.util.Date someDate) {
super();
this.someDate= someDate;
}
There is data in 'someDate' column and query is working fine on Sql-Editor, but when running above code "some_date" is always null.
What is wrong in this code? How should I get value for date?
I even converted the date format and declared field String in code but nothing worked.
1) As you are using java.util.Date you should mark your date field with temporal type:
#Column(name = "some_date")
#Temporal(TemporalType.DATE)
#JsonFormat(pattern="dd/MM/yyyy")
private Date someDate;
2) Define your native query as NamedNativeQuery:
#NamedNativeQuery(name = "testTableNativeQuery",
query = "SELECT distinct some_date from test",
resultSetMapping = "getTestTable")
3) Update your query execution:
getEntityManager().createNamedQuery("testTableNativeQuery", someEntity.class).getResultList();
Related
I have a parent table and a child table where I am only getting 1 record from child table but not getting case insensitive matched record which is a mixed string. I am expecting it should return 2 records.
Below is the code for the same.
//parent Table
#Entity
#Table(name = "employee")
public class Employee implements Serializable {
#Id
#Column(name = "employeeID")
private String employeeID;
#Column(name = "name_first")
private String nameFirst;
#Column(name = "name_last")
private String nameLast;
}
//Child Table
#Entity
#Table(name = "employee_salary")
public class EmployeeSalary implements Serializable {
#EmbeddedId
private EmployeeSalaryPK employeeSalaryPKCompositeKey;
#Column(name = "salaryBracket")
private String salaryBracket;
}
#Embeddable
public class EmployeeSalaryPK implements Serializable {
#Column(name = "employeeID")
private String employeeID;
#Column(name = "salary")
private String salary;
}
In employee_salary table I have two records (as shown below) but while fetching it using HQL only one record is coming with an actual match but case insensitive record is not coming.
Employee Record:- ABC John Kramer
employee_salary table record:-
ABC 100900
aBc 76770
I am using simple HQL query (see below code) but getting only first record whenever I want to get both record as employeeID is abc.
String hqlQuery = " FROM " + Employee.class.getName() + " E WHERE E.employeeID= :EMPLOYEEID";
Session session = entityManager.unwrap(Session.class);
List<?> responseList = session.createQuery(hqlQuery).setParameter("EMPLOYEEID", "ABC").list();
To get all entities by case insensetive String id you have to convert id to same case (lowercase or uppercase) on both sides of the WHERE clause equality operator
String hqlQuery = " FROM " + Employee.class.getName() + " E WHERE lower(E.employeeID) = :EMPLOYEEID";
Session session = entityManager.unwrap(Session.class);
List<?> responseList = session.createQuery(hqlQuery).setParameter("EMPLOYEEID", "ABC".toLowerCase()).list();
I am trying to get the max value of a column in a table using a native query with the #Query annotation
I tried to derive it from the examples here: https://www.baeldung.com/spring-data-jpa-query
#Query(value = "SELECT max(i.sequence) " +
"FROM invoices as i " +
"WHERE i.fleet_id = ?1", nativeQuery = true)
Long findMaxSequence(String fleetId);
i ve also tried:
#Query(value = "SELECT max(i.sequence) " +
"FROM invoices as i " +
"WHERE i.fleet_id = :fleetId", nativeQuery = true)
Long findMaxSequence(#Param("fleetId") String fleetId);
When i call my method as :
long maxSeq = invoiceRepository.findMaxSequenceForFleetId(invoice.getFleetId());
I get a NullPointerException. Any ideas why?
Invoice entity looks like this :
#Entity
#Table(name = "invoices"}
public class Invoice implements Serializable {
#Id
private String id;
#Column
private long sequence;
#Column(length = 12)
private String fleetId;
// ...
}
The issue was due to the fact that the database was empty so the query was returning null
and basic types such as long cannot be assigned to null values. Weirdly the compiler did not complain..
I modified my code as below:
Long maxSeq = invoiceRepository.findMaxSequenceForFleetId(invoice.getFleetId());
if(maxSeq == null){
maxSeq = 0L;
}
i would like some help trying to do the following.I want to get the number of purchases of each user in the database grouped by his name and id.But it's very hard to do compared to simple sql.
I have the following code in my PurchaseRepository that extends CrudRepository
#Query("SELECT p.user.name as Name,p.user.id as Id,Count(p) as Purchases from Transaction p GROUP BY p.user.id")
List<Object> purchaseNumOfEachUser();
First of all im not sure if this is the right query because i wanted to do Count(*) but says its not valid.
Secondly , the object i get returned when converted to Json via a controller is like
0:{
0:"John",
1:2, //id
2:5 //purchases
}
What i would like to get is
0:{
"Name" : "John",
"Id" : 1 ,
"Purchases" : 2
},
1:{
....
}
Any ideas?
1) The query:
SELECT p.user.name as Name, p.user.id as Id, Count(p) as Purchases
from Transaction p GROUP BY p.user.id
should be
SELECT p.user.name as Name, p.user.id as Id, Count(p) as Purchases
from Transaction p GROUP BY p.user.name, p.user.id
You must group by all rows you are selecting.
2) the result
The result of the query is List if you want to have something meaningful you should consider the constructor expression that let's you create your own objects.
For example
package mypackage;
public class PurchaseInfo {
private final String name;
private final Integer id;
private final Long count;
public PurchaseInfo(String name, Integer id, Long count) {
this.name = name;
this.id = id;
this.cound = count;
}
// getters
}
This class can then be use in the query (please notice the fully qualified class name after NEW):
SELECT NEW mypackage.PurchaseInfo(p.user.name, p.user.id, Count(p))
from Transaction p GROUP BY p.user.name, p.user.id
The result will then be List and you will get it nicely serialized to JSON.
Read more about the Constructor Expression here:
https://vladmihalcea.com/the-best-way-to-map-a-projection-query-to-a-dto-with-jpa-and-hibernate/
I´m doing a Web-Application with a Spring Boot Backend and an AngularJS frontend.
Database is MySQL.
I try do get the Top 5 Items out of my database. I´m doing this through the
#Query Annotation. I tried my SQL Statement directly onto the DB and i get the expected values.
SQL Statement:
select item
from work_item
group by item
order by count(*) desc
limit 3
#Query:
#Query(value="SELECT WORK_ITEM_ITEM FROM WORK_ITEM GROUP BY WORK_ITEM_ITEM ORDER BY COUNT( *) DESC LIMIT 5", nativeQuery = true)
List< String > find5MostUsedItems();
When i try to access the related URL i´m getting the following error:
java.lang.IllegalArgumentException: PersistentEntity must not be null!
Would be glad if someone could push me into the right direction.
In case you need more information, plz ask. (My first question :) )
Edit: my Entity:
#Entity
public class WorkItem {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "workItem_ID")
private long id;
#Column(name = "workItem_date")
private LocalDate date;
#Column(name = "workItem_mitarbeiterNummer")
private int mitarbeiterNummer;
#Column(name = "workItem_startTime")
private LocalTime startTime;
#Column(name = "workItem_endTime")
private LocalTime endTime;
#Column(name = "workItem_workDuration")
private int workDuration;
#Column(name = "workItem_item")
private String item;
#Column(name = "workItem_itemDescription")
private String itemDescription;
Greetings!
I think you should try SELECT WORKITEM_ITEM instead of SELECT WORK_ITEM_ITEM
I want to to retrieve data from table in the order of the database table's column order.
Suppose my sql query is
String sql_string = "select * "
+ "from CUSTOMER_INFO "
+ "order by customer_last_name, customer_first_name";
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
List<Map<String,Object>> results = session.createSQLQuery(sql_string)
.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE)
.list();
In database, the table's column order is like A,B,C,D.
But when I retrieve the data and iterate through it, the entrySet is like C,A,D,B. (int,float,float,String)
I think the data is being retrieved based on its datatype.
I need the retrieved entrySet in the same order as it exists in database's table.
I also tried specifying the column names in select query which was of no use.
CUSTOMER_INFO is model class mapped to sqllite through hibernate.
#Entity
#Table(name = "CUSTOMER_INFO")
public class CustomerInfo{
#Column
private int C;
#Column
private float A;
#Column
private String B;
#Column
private float D;
//getters and setters
}
Using Sqllite 3.6, hibernate, JSP.
Any help is appreciated.