Usng java I can make a recursive tree parent child .
But usint this java traitement it consumes too much process and memory.
I want to simplify this method using a recursive postgres method and use the result in the java method.
I work with Spring boot version 2 and I use JPA and hibernate version 5.2
the #RestController class
#GetMapping("/collegeBook")
#Timed
public ResponseEntity<List<CollegeDTO>> getAllCollegeBook(Pageable pageable, #RequestParam(name="lang", required=false) String lang) {
Page<CollegeDTO> page = collegeService.findAllCollege(pageable, lang);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/collegeBook");
return ResponseEntity.ok().headers(headers).body(page.getContent());
}
and this is the method in service class
public Page<CollegeDTO> findAllCollege(Pageable pageable, String lang) {
List<CollegeDTO> list=collegeRepository.findCollegeList(pageable, lang);
List<CollegeDTO> unitChildList=getChildrenList(list,lang,pageable);
return new PageImpl<CollegeDTO>(unitChildList);
}
private List<CollegeDTO> getChildrenList(
List<CollegeDTO> collegeList, String lang,Pageable pageable) {
for(CollegeDTO collegeDTO : collegeList) {
List<CollegeDTO> childrenListEntity = collegeRepository.findCollegeByParentId(pageable, lang,CollegeDTO.getValue());
collegeDTO.setChildren(getChildrenList(childrenListEntity,lang,pageable));
}
return collegeList;
}
this is the Repository method
public List<CollegeDTO> findCollegeList(Pageable pageable, String lang) {
String querystr = "SELECT ";
querystr += " collegelang.name AS text ,";
querystr += " college.id AS value ,";
querystr += " (select count(*) from student where student.college_id = college.id) as nbr ";
querystr += " FROM college college ";
querystr += " LEFT OUTER JOIN collegelang collegel ON collegelang.college_id = college.id ";
querystr += " Where collegelang.lang = :lang and college.status ='1' and parentid is null order by app_order asc";
log.debug("-- Query:" + querystr);
Query query = em.createNativeQuery(querystr, "CollegeDTOMap");
query.setParameter("lang", lang);
List<CollegeDTO> collegeDTOs = query.getResultList();
return collegeDTOs;
}
public List<CollegeDTO> findCollegeByParentId(Pageable pageable, String lang, String idParent) {
String querystr = "SELECT ";
querystr += " collegelang.name AS text ,";
querystr += " college.id AS value ,";
querystr += " (select count(*) from student where student.college_id = college.id) as nbr";
querystr += " FROM college college ";
querystr += " LEFT OUTER JOIN collegelang collegelang ON collegelang.college_id = college.id ";
querystr += " Where collegelang.lang = :lang and college.status ='1' and un.parentid = :idParent ";
log.debug("-- Query:" + querystr);
Query query = em.createNativeQuery(querystr, "CollegeDTOMap");
query.setParameter("lang", lang);
query.setParameter("idParent", idParent);
List<CollegeDTO> collegeDTOs = query.getResultList();
return collegeDTOs;
}
CollegeDTO class
public class CollegeDTO{
private String text;
private String value;
private String nbr;
private List<CollegeDTO> children;
public CollegeDTO(String text,String value,String nbr, List<CollegeDTO> children) {
super();
this.text = text;
this.value = value;
this.nbr = nbr;
this.children = children;
}
//getter and setter .......
}
College class
#SqlResultSetMapping(
name = "CollegeDTOMap",
classes = #ConstructorResult(
targetClass = CollegeDTO.class,
columns = {
#ColumnResult(name = "text"),
#ColumnResult(name = "value"),
#ColumnResult(name = "nbr")
}
)
)
public class College {
..............
..............
}
Updated :
I try with this query but I didn't find the way to use the result in java traitement .
My goals is to return Page<CollegeDTO>
which contain child having CollegeDTO as a type
with recursive nodes as (
select college.id AS value, CAST(collegelang.name AS varchar) AS text,
(select count(*) from student where student.college_id = college.id) as nbr,
ARRAY[college.id,collegelang.name,(select count(*) from student where student.college_id = college.id)]
as parents,college.app_order
FROM college college
LEFT OUTER JOIN collegelang collegelang ON collegelang.college_id = college.id
Where collegelang.lang = 'AR' and college.status ='1' and parentid is null
union all
select o.id AS value, CAST(collegelang.name AS varchar) AS text,(select count(*) from student where student.college_id = college.id) as nbr
,parents || ARRAY[o.id,collegelang.name,(select count(*) from student where student.college_id = college.id)]
,o.app_order
FROM college o
join nodes n on n.value = o.parentid
LEFT OUTER JOIN collegelang collegelang ON collegelang.unit_id = o.id and collegelang.lang='AR'
where o.status ='1'
)
select CAST(text AS varchar) as text,value as value,nbr as nbr, parents as children from nodes
order by app_order asc
I try to modify College class
#SqlResultSetMapping(
name = "CollegeDTOMap",
classes = #ConstructorResult(
targetClass = CollegeDTO.class,
columns = {
#ColumnResult(name = "text"),
#ColumnResult(name = "value"),
#ColumnResult(name = "nbr"),
#ColumnResult(name = "children") // add this line
}
)
)
public class College {
..............
..............
}
but I have this error using the previous query
Caused by: org.hibernate.HibernateException: Could not resolve column name in result set [children]
Caused by: org.hibernate.MappingException: No Dialect mapping for JDBC type: 2003
Related
I used postgresql 10 and spring boot
I try with success to load tree using loop in java.
in the loop I call each time the query
but it consumes cpu in application server and cpu in database server and takes time to load the tree which contain 5000 unit.
I want using only one query to load the tree without loop in java.
the result from java is ResponseEntity<List<UnitDTO>>
this is my code :
#GetMapping("/unitsBook")
#Timed
public ResponseEntity<List<UnitDTO>> getAllUnitsBook(Pageable pageable, #RequestParam(name="lang", required=false) String lang,
#RequestParam(name="emp", required=false) String empID) {
log.debug("REST request to get a page of Units");
Page<UnitDTO> page = unitService.findAllUnitBook(pageable, lang,empID);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/unitsBook");
return ResponseEntity.ok().headers(headers).body(page.getContent());
}
the java code which contains the loop is :
public List<UnitDTO> getUnitBookList(Pageable pageable, String lang,String empID) {
List<UnitDTO> list=unitRepository.findUnitList(pageable, lang,empID);
List<UnitDTO> unitChildList=getChildrenUnitList(list,lang,pageable,empID);
return unitChildList;
}
private List<UnitDTO> getChildrenUnitList(
List<UnitDTO> unitList, String lang,Pageable pageable,String empID) {
for(UnitDTO UnitDTO : unitList) {
List<UnitDTO> childrenListEntity = unitRepository.findUnitByParentId(pageable, lang,UnitDTO.getValue(),empID);
UnitDTO.setChildren(getChildrenUnitList(childrenListEntity,lang,pageable,empID));
}
return unitList;
}
and the code which call query is :
public List<UnitDTO> findUnitList(Pageable pageable, String lang,String empID) {
String querystr = "SELECT ";
querystr += " unl.name AS text ,";
querystr += " un.id AS value ,";
querystr += " ,cast( 0 as varchar(10) ) as favoriteNbr,cast( null as varchar(10) ) as favoriteId ";
querystr += " FROM public.unit un ";
querystr += " LEFT OUTER JOIN public.unitlang unl ON unl.unit_id = un.id ";
querystr += " Where unl.lang = :lang parentid is null order by app_order asc";
log.debug("-- Query:" + querystr);
Query query = em.createNativeQuery(querystr, "UnitDTOMap");
query.setParameter("lang", lang);
List<UnitDTO> unitDTOs = query.getResultList();
if (pageable.isUnpaged()) {
return unitDTOs;
}
return unitDTOs;
}
#Override
public List<UnitDTO> findUnitByParentId(Pageable pageable, String lang, String idParent,String empID) {
log.debug("-- pageable:" + pageable.getPageNumber() + ", Size:" + pageable.getPageSize() + ", isUnpaged:" + pageable.isUnpaged() + ", lang:" + lang);
lang = lang.toUpperCase();
String querystr = "SELECT ";
querystr += " unl.name AS text ,";
querystr += " un.id AS value ,";
querystr += " (case when cast((select count(*) from employee where employee.unit_id = un.id) as varchar(10)) != '0' then cast(1 as Boolean) else cast(0 as BOOLEAN) end) as disabled";
querystr += " ,cast( 0 as varchar(10) ) as favoriteNbr,cast( null as varchar(10) ) as favoriteId ";
querystr += " FROM unit un ";
querystr += " LEFT OUTER JOIN unitlang unl ON unl.unit_id = un.id ";
querystr += " Where unl.lang = :lang and un.parentid = :idParent order by app_order asc ";
log.debug("-- Query:" + querystr);
Query query = em.createNativeQuery(querystr, "UnitBookDTOMap");
query.setParameter("lang", lang);
query.setParameter("idParent", idParent);
List<UnitDTO> unitDTOs = query.getResultList();
log.debug("-- unitDTOs Size:" + unitDTOs.size());
if (pageable.isUnpaged()) {
return unitDTOs;
}
return unitDTOs;
}
Updated :
I try to use the recursive query but the problem is that the tree does not display correctly.
all the unit are in same level.
I think the problem in this line WHERE id = :idParent I comment it because I didn't find how can I send it
public List<UnitDTO> getUnitBookList(Pageable pageable, String lang) {
List<UnitDTO> list=unitRepository.findUnitList(pageable, lang);
// List<UnitBookDTO> unitChildList=getChildrenUnitList(list,lang,pageable);
return list;
}
#Override
public List<UnitDTO> findUnitList(Pageable pageable, String lang) {
log.debug("-- pageable:" + pageable.getPageNumber() + ", Size:" + pageable.getPageSize() + ", isUnpaged:" + pageable.isUnpaged() + ", lang:" + lang);
lang = lang.toUpperCase();
String querystr = "WITH RECURSIVE un_id AS ( ";
querystr += " SELECT id";
querystr += " FROM unit ";
// querystr += " WHERE id = :idParent";
querystr += " UNION";
querystr += " SELECT unit.id";
querystr += " FROM unit JOIN un_id ON unit.parentid = un_id.id ) ";
querystr += " SELECT unl.name AS text, un.id AS value, (case when cast((select count(*) from employee where employee.unit_id = un.id) as varchar(10)) != '0' ";
querystr += " then cast(1 as Boolean) else cast(0 as BOOLEAN) end) as disabled , cast(0 as varchar(10)) as favoriteNbr,";
querystr += " cast(null as varchar(10)) as favoriteId FROM un_id JOIN unit un USING (id) LEFT OUTER JOIN unitlang unl ON unl.unit_id = un.id Where unl.lang = :lang order by app_order asc";
log.debug("-- Query:" + querystr);
Query query = em.createNativeQuery(querystr, "UnitDTOMap");
query.setParameter("lang", lang);
List<UnitDTO> unitDTOs = query.getResultList();
log.debug("-- unitDTOs Size:" + unitDTOs.size());
if (pageable.isUnpaged()) {
return unitDTOs;
}
return unitDTOs;
}
The usual way to fetch a tree in SQL is to use a recursive Common Table Expression (CTE):
WITH RECURSIVE un_id AS (
SELECT id
FROM unit
WHERE id = :idParent -- or parentid if you want to exclude the parent itself
UNION
SELECT unit.id
FROM unit
JOIN un_id
ON unit.parentid = un_id.id
)
SELECT unl.name AS text,
un.id AS value,
(case
when cast((select count(*) from employee where employee.unit_id = un.id) as varchar(10)) != '0'
then cast(1 as Boolean)
else cast(0 as BOOLEAN) end) as disabled
,
cast(0 as varchar(10)) as favoriteNbr,
cast(null as varchar(10)) as favoriteId
FROM un_id -- reference to the CTE
JOIN unit un
USING (id)
LEFT OUTER JOIN unitlang unl ON unl.unit_id = un.id
Where unl.lang = :lang
order by app_order asc
Recursively fetch all the IDs and then join the rest of the needed data.
I want to split XML response into pages because I have too many XML items to send back. I tried this:
XML request:
<?xml version="1.0" encoding="UTF-8"?>
<reconcile>
<start_date>2018-04-08T11:02:44</start_date>
<end_date>2019-10-08T11:02:44</end_date>
<page>1</page>
</reconcile>
JAXB:
#XmlRootElement(name = "reconcile")
#XmlAccessorType(XmlAccessType.FIELD)
public class Reconcile {
#XmlElement(name = "start_date")
#XmlJavaTypeAdapter(LocalDateTimeXmlAdapter.class)
private LocalDateTime start_date;
#XmlElement(name = "end_date")
#XmlJavaTypeAdapter(LocalDateTimeXmlAdapter.class)
private LocalDateTime end_date;
#XmlElement(name = "page")
private String page;
...../// getters and setters
}
SQL query:
public List<PaymentTransactions> transactionsByDate(LocalDateTime start_date, LocalDateTime end_date, Merchants merchant, Terminals terminal) throws Exception {
String hql = "select e from " + PaymentTransactions.class.getName() + " e where e.created_at >= ? and e.created_at <= ?";
Query query = entityManager.createQuery(hql).setParameter(0, start_date).setParameter(1, end_date);
List<PaymentTransactions> paymentTransactions = (List<PaymentTransactions>) query.getResultList();
return paymentTransactions;
}
Return XML:
List<PaymentTransactions> paymentTransactions = transactionsService
.transactionsByDate(reconcile.getStart_date(), reconcile.getEnd_date(), merchant, terminal);
ReconcilePaymentResponses pr = new ReconcilePaymentResponses();
pr.setPage("1");
pr.setPages_count("10");
pr.setPer_page("4");
pr.setTotal_count(String.valueOf(paymentTransactions.size()));
for (int e = 0; e < paymentTransactions.size(); e++) {
PaymentTransactions pt = paymentTransactions.get(e);
ReconcilePaymentResponse obj = new ReconcilePaymentResponse();
obj.setTransaction_type(pt.getType());
pr.getPaymentResponse().add(obj);
}
return pr;
XML Response:
<?xml version='1.0' encoding='UTF-8'?>
<payment_responses page="1" per_page="4" total_count="5" pages_count="10">
<payment_response>
<transaction_type>Type</transaction_type>
</payment_response>
<payment_response>
<transaction_type>Type</transaction_type>
</payment_response>
<payment_response>
<transaction_type>Type</transaction_type>
</payment_response>
.........
</payment_responses>
I would like somehow to split <payment_response>....</payment_response> into pages in order to reduce memory overhead. For example when I send 1 I would like to return the first 10.
How I can implement this?
What do you think about something like this? I'm sorry it is untested code but something like this should work.
I created a new PageInfo class to store the paging info. Added a query to get the total number of rows and set my page_info. Then limited the number of results from your query. Finally set the values to ReconcilePaymentResponse.
Class PageInfo {
int current_page;
int page_count;
int per_page;
int total_page;
//constructor
public PageInfo(int current_page, int page_count, int per_page) {
//assign them
}
//getters
//setters
}
SQL Query:
public List<PaymentTransactions> transactionsByDate(LocalDateTime start_date, LocalDateTime end_date, Merchants merchant, Terminals terminal,
PageInfo pageInfo) throws Exception {
//figure out number of total rows
String count_hql = "select count(*) from " + PaymentTransactions.class.getName() + " e where e.created_at >= ? and e.created_at <= ?";
Query count_query = entityManager.createQuery(count_hql);
int count = countQuery.uniqueResult();
//figure out total pages
int total_page = (int)Math.ceil(count/(double)pageInfo.getPerPage());
pageInfo.setTotal_Page(total_page);
String hql = "select e from " + PaymentTransactions.class.getName() + " e where e.created_at >= ? and e.created_at <= ?";
Query query = entityManager.createQuery(hql)
//set starting point
.setFirstResult((pageInfo.getCurrentPage()-1) * pageInfo.getPerPage)
//set max rows to return
.setMaxResults(pageInfo.getPerPage)
.setParameter(0, start_date).setParameter(1, end_date);
List<PaymentTransactions> paymentTransactions = (List<PaymentTransactions>) query.getResultList();
return paymentTransactions;
}
Return XML:
//initialize PageInfo with desired values
PageInfo page_info = new PageInfo(1,10,4);
List<PaymentTransactions> paymentTransactions = transactionsService
.transactionsByDate(reconcile.getStart_date(), reconcile.getEnd_date(), merchant, terminal, page_info); // pass in page_info
ReconcilePaymentResponses pr = new ReconcilePaymentResponses();
pr.setPage(page_info.getCurrentPage());
pr.setPages_count(page_info.getPageCount());
pr.setPer_page(page_info.getPerPage());
pr.setTotal_count(String.valueOf(paymentTransactions.size()));
for (int e = 0; e < paymentTransactions.size(); e++) {
PaymentTransactions pt = paymentTransactions.get(e);
ReconcilePaymentResponse obj = new ReconcilePaymentResponse();
obj.setTransaction_type(pt.getType());
pr.getPaymentResponse().add(obj);
}
return pr;
I've made a search tool in java.
String query = "SELECT * FROM Customer WHERE 1 = 1 ";
if (!firstname.isEmpty()) query += "AND cName = '" + firstname + "' ";
if (!lastname.isEmpty()) query += "AND cLastName = '" + lastname + "' ";
if (!epost.isEmpty()) query += "AND cEpost = '" + epost + "' ";
if (!phonenumber.isEmpty()) query += "AND cPhonenumber '" + phonenumber + "' ";
That ouput this if all of those paramerets has values:
SELECT * FROM Customer WHERE 1 = 1
AND cName = 'test'
AND cLastName = 'test1'
AND cEpost = 'test2'
AND cPhonenumber 'test3'
This way I can get better results by filling in more data, but i can still choose to not do.. I need a solution for JPA for this.. any tips?
Thanks!
EDIT: End result based on the answer below:
public static List<Customer> searchCustomersByParameters(String firstname, String lastname,
String epost, String phonenumber) {
String sql = "SELECT c FROM Customer c WHERE 1 = 1 ";
if (!firstname.isEmpty()) sql += "AND c.cName = :firstname ";
if (!lastname.isEmpty()) sql += "AND c.cLastName = :lastname ";
if (!epost.isEmpty()) sql += "AND c.cEpost = :epost ";
if (!phonenumber.isEmpty()) sql += "AND c.cPhonenumber = :phonenumber";
Query q = em.createQuery(sql);
if (!firstname.isEmpty()) q.setParameter("firstname", firstname);
if (!lastname.isEmpty()) q.setParameter("lastname", lastname);
if (!epost.isEmpty()) q.setParameter("epost", epost);
if (!phonenumber.isEmpty()) q.setParameter("phonenumber", phonenumber);
return q.getResultList();
}
While it is of course possible to create dynamic SQL using string concatenation as suggested in this answer, a more type safe and less risky (in terms of SQL injection) approach is to use the JPA criteria API
public static List<Customer> searchCustomersByParameters(String firstname, String lastname,
String epost, String phonenumber) {
var qb = em.getCriteriaBuilder();
var query = qb.createQuery(Customer.class);
var root = query.from(Customer.class);
query.select(root);
if (!firstname.isEmpty()) query.where(qb.equal(root.get("cName"), firstName));
if (!lastname.isEmpty()) query.where(qb.equal(root.get("cLastName"), lastname));
if (!epost.isEmpty()) query.where(qb.equal(root.get("cEpost "), epost ));
if (!phonenumber.isEmpty()) query.where(qb.equal(root.get("cPhonenumber "), phonenumber));
return em.createQuery(query).getResultList();
}
... or if you don't strictly need to use JPQL you could also use a third party SQL builder like jOOQ:
public static List<Customer> searchCustomersByParameters(String firstname, String lastname,
String epost, String phonenumber) {
return
ctx.selectFrom(CUSTOMER)
.where(!firstname.isEmpty() ? CUSTOMER.CNAME.eq(firstname) : noCondition())
.and(!lastname.isEmpty() ? CUSTOMER.CLASTNAME.eq(lastname) : noCondition())
.and(!epost.isEmpty() ? CUSTOMER.CEPOST.eq(epost) : noCondition())
.and(!phonenumber.isEmpty() ? CUSTOMER.CPHONENUMBER.eq(phonenumber) : noCondition())
.fetchInto(Customer.class);
}
Disclaimer: I work for the company behind jOOQ
use ? and set Parameters for preventing sql injection and in JPA you can use native sql as old way you do and also JPQL.Generate your sql by conditions and set your parameters.I use here where 1=1 condition to easy append next conditions by and.Otherwise you will have difficulties for appending "where" to your sql.
by native:
public static List<YourEntity> getFromTable(String name,String surname) {
EntityManager em = PersistenceManager.instance().createEntityManager();
try {
String sql = " select * from table where 1=1 ";
if(name!=null && !name.trim().isEmpty()){
sql +=" and name = :name";
}
if(surname!=null && !surname.trim().isEmpty()){
sql +=" and surname = :surname";
}
Query q = em.createNativeQuery(sql);
if(name!=null && !name.trim().isEmpty()){
q.setParameter("name", name);
}
if(surname!=null && !surname.trim().isEmpty()){
q.setParameter("surname", surname);
}
List<YourEntity> l = q.getResultList();
return l;
} finally {
em.close();
}
}
By jpql:
public static List<YourEntity> getFromTable(String name,String surname) {
EntityManager em = PersistenceManager.instance().createEntityManager();
try {
String sql = " select e from YourEntity e where 1=1 ";
if(name!=null && !name.trim().isEmpty()){
sql +=" and e.name = :name";
}
if(surname!=null && !surname.trim().isEmpty()){
sql +=" and e.surname = :surname";
}
Query q = em.createQuery(sql);
if(name!=null && !name.trim().isEmpty()){
q.setParameter("name", name);
}
if(surname!=null && !surname.trim().isEmpty()){
q.setParameter("surname", surname);
}
List<YourEntity> l = q.getResultList();
return l;
} finally {
em.close();
}
}
I have an entity (StockKeepingUnit) with NamedNativeQuery:
#NamedNativeQuery(name = StockKeepingUnit.NQ_FINDBY_ARTICLE_AND_SIZE, resultClass = StockKeepingUnit.class, hints = {
#QueryHint(name = "org.hibernate.cacheable", value = "false"),
#QueryHint(name = "org.hibernate.fetchSize", value = "1"),
#QueryHint(name = "org.hibernate.readOnly", value = "true") }, query = "SELECT * "
+ "FROM StockKeepingUnit sku " + "WHERE sku.article = :articleNumber "
+ "AND sku.size = :size " + "AND sku.deleted = 0")
Call in Java:
Query query = em.createNamedQuery(StockKeepingUnit.NQ_FINDBY_ARTICLE_AND_SIZE);
query.setParameter(StockKeepingUnit.NQ_PARAM_ARTICLE_NR, articleNumber);
query.setParameter(StockKeepingUnit.NQ_PARAM_SIZE, size);
return (StockKeepingUnit) query.getSingleResult();
With this query I want only select the sku.stockKeepingUnitNumber and get an Integer-Value as result when I execute this query.
I tried something like this, but this did not work...
#NamedNativeQuery(name = StockKeepingUnit.NQ_FINDBY_ARTICLE_AND_SIZE, resultClass = Integer.class, hints = {
#QueryHint(name = "org.hibernate.cacheable", value = "false"),
#QueryHint(name = "org.hibernate.fetchSize", value = "1"),
#QueryHint(name = "org.hibernate.readOnly", value = "true") }, query = "SELECT sku.stockKeepingUnitNumber "
+ "FROM StockKeepingUnit sku " + "WHERE sku.article = :articleNumber "
+ "AND sku.size = :size " + "AND sku.deleted = 0")
Call in Java:
Query query = em.createNamedQuery(StockKeepingUnit.NQ_FINDBY_ARTICLE_AND_SIZE);
query.setParameter(StockKeepingUnit.NQ_PARAM_ARTICLE_NR, articleNumber);
query.setParameter(StockKeepingUnit.NQ_PARAM_SIZE, size);
return (Integer) query.getSingleResult();
Can anybody help me?
I solved the problem wit ResultSetMapping :-)
#SqlResultSetMapping(name = StockKeepingUnit.NQ_FIND_ONLY_SKU, columns = {
#ColumnResult(name = StockKeepingUnit.NQ_RESULT_SKU_NAME)}
in NamedQuery you can refer to this mapping with the attribute
#NamedNativeQuery(name = StockKeepingUnit.NQ_FINDBY_ARTICLE_AND_SIZE, resultSetMapping = StockKeepingUnit.NQ_FIND_ONLY_SKU, query = "SELECT sku.stockKeepingUnitNumber as "
+ StockKeepingUnit.NQ_RESULT_SKU_NAME
+ " FROM StockKeepingUnit sku " + "WHERE sku.article = :articleNumber "
+ "AND sku.size = :size")
I am studying Hibernate and in a exercise I must do this query
"SELECT count(id) as numero_utenti, imc
FROM Utenti
WHERE azienda = '" + id + "' GROUP BY imc"
the problem is that, I don't know as view the result and to save the result in a string.
Thanks.
This is the function
public String getStat(int id) {
String stat = "";
int count = 0;
try {
Query query = session.createQuery("SELECT count(id) as numero_utenti, imc FROM Utenti WHERE azienda = '" + id + "' GROUP BY imc");
// as I extract the values?
tx.commit();
} catch (HibernateException he) {
throw he;
}
return stat;
}
If you are looking how to execute query using hibernate session.
query = session.createQuery("semect * from temp");
and query instance
Long.valueOf(query.fetchCountOfRows()).intValue();
It'll give you no. row count.
If they are not unique, get the list.
List<String> imcs= null;
int count = 0;
Query query = session.createQuery("SELECT imc FROM Utenti WHERE azienda = '" + id + "' GROUP BY imc");
imcs = query.list();
count = imcs.size();