I am using hql with hibernate. I've tried to write a query over three tables. The tables are Medientyp, RaumMedientyp and Raum. I wanna read all Medientyp's from the whole table and all RaumMedientyp's from a specific raumId.
The realtions between the tables are:
Medientyp 1 <--> mc RaumMedientyp mc <--> 1 Raum
I need all as RaumMedientyp Entity.
The query i tried is:
String hql = "from RaumMedientyp rm right join rm.medientyp m inner join rm.raum r where r.id = :raumId";
Query query = getSession().createQuery(hql);
query.setInteger(":raumId", raumId);
But if i'm executing
query.list();
i've got a empty list as return.
Related
tl;dr I have a long native query in Hibernate, that is split in multiple queries (with table as ...). This Query use inner joins that not work in hibernate (empty result), but work excellent in the SQL Console. Also if I copy/paste the query from the hibernate logs into the console.
with params as (select ca.id as calculation_id, chart_id, range_size, range_size * interval '1' minute as size
from calculation ca
inner join chart c on c.id = ca.chart_id
inner join time_range tr on tr.id = c.time_range_id
where ca.id = :calculationid),
tuple_diff as (select t.calculation_id,
t.id,
t.ohlc_id,
t.time, t.time - lag(t.time, 1) over (order by t.time) as diff
from tuple t inner join params p
on t.calculation_id = p.calculation_id),
ohlc_diff as (select o.chart_id,
o.id,
o.time,
o.time - lag(o.time, 1) over (order by o.time) as diff
from ohlc o inner join params p on o.chart_id = p.chart_id),
tuple_filtered as (select id, ohlc_id, time, diff, p.size, p.range_size
from tuple_diff t
inner join params p on chart_id = p.chart_id
where diff <> p.size),
ohlc_filtered as (select o.chart_id, o.id as ohlc_id, time
from ohlc_diff o
inner join params p on o.chart_id = p.chart_id
where o.diff <> p.size)
select t.time as time, t.range_size as size
from tuple_filtered t
left join ohlc_filtered o on t.time = o.time
where o.ohlc_id is null
order by t.time;
The long version, I have a microservice, generated with jhipster and the project runs productive with PostgreSQL and in development mode with a H2 Database. I have ohlc stockexchange time series and calculate calculations with an other microservice and store the computation in a tuple table. Sometimes I have holes in the timeline and want to recalculate them. I need to get the time difference to the last calculation. This is not an easy SQL Query, because you need to access the previous row like in Excel. I use the lag function to solve this problem. But the lag function is not the reason.
I generate a test project with an integration test to analyze the problem. The Junit Test is de.bitc.se.service.CalculationServiceIT and run with a Postgresql Testcontainer. The test also fill the SQL tables with testdata. I start to split the query in small parts.
with params as (select ca.id as ca_id,
chart_id, range_size,
range_size * interval '1' minute as size
from calculation ca
inner join chart c on c.id = ca.chart_id
inner join time_range tr on tr.id = c.time_range_id
where ca.id = :calculationid)
select ca_id, chart_id, range_size
from params
order by ca_id;
This part works like the console.
with tuple_diff as (select t.calculation_id,
t.id,
t.ohlc_id,
t.time,
t.time - lag(t.time, 1) over (order by t.time) as diff
from tuple t
where calculation_id = :calculationid)
select calculation_id, time
from tuple_diff
order by calculation_id;
The second query too, but when I try to join the query's, I got an empty result:
with params as (select ca.id as ca_id,
chart_id,
range_size, range_size * interval '1' minute as size
from calculation ca
inner join chart c on c.id = ca.chart_id
inner join time_range tr on tr.id = c.time_range_id
where ca.id = :calculationid),
tuple_diff as (select t.calculation_id,
t.id,
t.ohlc_id,
t.time,
t.time - lag(t.time, 1) over (order by t.time) as diff
from tuple t
inner join params p on p.ca_id = t.calculation_id
where calculation_id = ca_id)
select calculation_id
from tuple_diff
order by calculation_id;
When I try to join the param query (one result) with the tuple table I got no result. In the SQL console I got a result of multiple lines. I used the EntityManager to exclude Spring Data code in the splitted queries in the integration test.
I have no idea why I got no result. Is it a bug in Hibernate or a mistake?
I'm using queryDSL to get users with some additional data from base:
public List<Tuple> getUsersWithData (final SomeParam someParam) {
QUser user = QUser.user;
QRecord record = QRecord.record;
JPQLQuery = query = new JPAQuery(getEntityManager());
NumberPath<Long> cAlias = Expressions.numberPath(Long.class, "cAlias");
return query.from(user)
.leftJoin(record).on(record.someParam.eq(someParam))
.where(user.active.eq(true))
.groupBy(user)
.orderBy(cAlias.asc())
.list(user, record.countDistinct().as(cAlias));
}
Despite it's working as desired, it generates two COUNT() in SQL:
SELECT
t0.ID
t0.NAME
to.ACTIVE
COUNT(DISTINCT (t1.ID))
FROM USERS t0 LEFT OUTER JOIN t1 ON (t1.SOME_PARAM_ID = ?)
WHERE t0.ACTIVE = true
GROUP BY t0.ID, to.NAME, t0.ACTIVE
ORDER BY COUNT(DISTINCT (t1.ID))
I want to know if it's possible to get something like this:
SELECT
t0.ID
t0.NAME
to.ACTIVE
COUNT(DISTINCT (t1.ID)) as cAlias
FROM USERS t0 LEFT OUTER JOIN t1 ON (t1.SOME_PARAM_ID = ?)
WHERE t0.ACTIVE = true
GROUP BY t0.ID, to.NAME, t0.ACTIVE
ORDER BY cAlias
I failed to understand this from documentation, please, give me some directions if it's possible.
QVehicle qVehicle = QVehicle.vehicle;
NumberPath<Long> aliasQuantity = Expressions.numberPath(Long.class, "quantity");
final List<QuantityByTypeVO> quantityByTypeVO = new JPAQueryFactory(getEntityManager())
.select(Projections.constructor(QuantityByTypeVO.class, qVehicle.tipo, qVehicle.count().as(aliasQuantity)))
.from(qVehicle)
.groupBy(qVehicle.type)
.orderBy(aliasQuantity.desc())
.fetch();
select
vehicleges0_.type as col_0_0_, count(vehicleges0_.pk) as col_1_0_
from vehicle vehicleges0_
group by vehicleges0_.type
order by col_1_0_ desc;
I did something like that, but I did count first before ordering. Look the query and the select generated.
That's a restriction imposed by SQL rather than by queryDSL.
You may try to run your suggested query in a DB console - I think it won't execute, at least not on every DB.
But I don't think this duplicated COUNT() really creates any performance overhead.
I create dao layer using spring data as follow
#Query(value="SELECT p FROM Products p INNER JOIN FETCH p.categoriesProducts cp INNER JOIN FETCH cp.categoryId c INNER JOIN FETCH p.mediasList ml ")
public List<Products> getAllProduct(Pageable pageable);
and I call it as follow
PageRequest pr = new PageRequest(0,100) ;
List<Products> ls = this.repo.getProductRepo().getAllProduct(pr) ;
my issue is I dont see the limit key word in the printed SQL in the log which is shown as follow
select products0_.id as id1_8_0_, categories1_.product_id as product_1_2_1_, categories2_.id as id1_1_2_, mediaslist3_.id as id1_4_3_, products0_.description as descript2_8_0_, products0_.discount_price as discount3_8_0_, products0_.price as price4_8_0_, products0_.prod_condition as prod_con5_8_0_, products0_.prod_number as prod_num6_8_0_, products0_.qty as qty7_8_0_, products0_.title as title8_8_0_, categories1_.category_id as category2_2_1_, categories2_.cat_name as cat_name2_1_2_, categories2_.description as descript3_1_2_, categories2_.keywords as keywords4_1_2_, categories2_.parent_id as parent_i5_1_2_, mediaslist3_.big_image_file as big_imag2_4_3_, mediaslist3_.media_type as media_ty3_4_3_, mediaslist3_.product_id as product_6_4_3_, mediaslist3_.thumb_image_file as thumb_im4_4_3_, mediaslist3_.video_file as video_fi5_4_3_, mediaslist3_.product_id as product_6_8_0__, mediaslist3_.id as id1_4_0__ from products products0_ inner join categories_products categories1_ on products0_.id=categories1_.product_id inner join categories categories2_ on categories1_.category_id=categories2_.id inner join medias mediaslist3_ on products0_.id=mediaslist3_.product_id
I am not sure what I do wrong the previous query is return 1000 rows from mysql and then it get the first 100 with the spring data but I need it to append limit 0,100 in the end of query, not sure how to do that
When i try to execute the following query in mysql , it works perfectly. But when we try it via Hibernate(3.2) ,hibernate is not differentiating m.NAME and o.NAME. It is returning the same result for both as m.NAME.
SELECT m.NAME, m.SCREENNAME, rm.ADDRESS, o.NAME FROM remoteunit rm LEFT JOIN mo m ON rm.MOID = m.ID JOIN overallcustomfields ocf ON m.ID = ocf.MOID LEFT JOIN organization o ON ocf.ORGID = o.ID WHERE m.DOMAINID = 2
Iam using the following code
Transaction transaction = session.beginTransaction();
SQLQuery query = session.createSQLQuery(queryString);
query.setLong("customId", customId);
remoteUnitList = (ArrayList<Object[]>)query.list();
transaction.commit();
Note: Forced to use SQLQuery in Hibernate since the columns are dynamically populated and more constraints.
Did you try SELECT m.NAME as m_name, o.NAME as o_name.... I faced the same problem and it went of with this change.
I need to report data from 3 different tables in form of a report.
The various search combinations a user can search with are..
INS_USER_ID and DateRange
CUST_ACCT_ID
CUST_ACCT_ID and DateRange
Query..
select DISTINCT W.CUST_ACCT_ID, W.INS_USER_ID, WS.STTI_DATE, WS.STTI_AMT, WC.CMMT from T_WRK W
INNER JOIN T_WRK_STTI WS ON W.WRK_STTI_ID = WS.WRK_STTI_ID
INNER JOIN T_WRK_CMMT WC ON W.WRK_ID = WC.WRK_ID
WHERE W.CUST_ACCT_ID = 90610194 AND WS.STTI_DATE BETWEEN '01-JAN-12' AND '31-DEC-12'
select DISTINCT W.CUST_ACCT_ID, W.INS_USER_ID, WS.STTI_DATE, WS.STTI_AMT, WC.CMMT from T_WRKCS W
INNER JOIN T_WRKCS_STTI WS ON W.WRKCS_STTI_ID = WS.WRKCS_STTI_ID
INNER JOIN T_WRKCS_CMMT WC ON W.WRKCS_ID = WC.WRKCS_ID
WHERE W.INS_USER_ID = 231 AND WS.STTI_DATE BETWEEN '01-JAN-12' AND '31-DEC-12'
All are existing tables are already mapped using Hibernate/JPA.
I have read enough on the various approaches in google, can someone tell me which one of the following hibernate approaches is best suited for my scenario.
NamedQuery
NativeQuery
Criteria API
I am thinking NamedQuery, but have not seen a NamedQuery spanning across multiple tables, an example would be great. Thank you.
Example
#Entity
#NamedQuery(name="findSalaryForNameAndDepartment",
query="SELECT e.salary " +
"FROM Student e" +
"WHERE e.department.name = :deptName AND " +
" e.name = :empName")
You can as well put there an join to the department table and change the query a little bit
For date use parameters
em.createNamedQuery("xxx").setParameter("srtartDate", ...).setParameter("endDate",..)