SELECT NEW Map (PRODUCT_CATEGORY, COUNT(PRODUCT_CATEGORY) AS COUNTER) from Product WHERE USER_ID = (SELECT USER_ID FROM USERS WHERE USERNAME='burak123'
Hi everyone,
As hibernates document says here: https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html#queryhql-select
I am trying to map the query result into a hash map like this
#Query(value = "SELECT NEW Map( PRODUCT_CATEGORY , COUNT(PRODUCT_CATEGORY) AS COUNTER ) from Product WHERE USER_ID=(SELECT USER_ID FROM USERS WHERE USERNAME=(:username)) ",nativeQuery = true)
HashMap<Integer,Integer> getCategoryCountsWithUsername(#Param("username")String username);
But it throws an JdbcSyntaxErrorException. I am trying to solve this for like 1 hours already. Can someone help?
You are using a native query, not an HQL query. Check your SQL syntax.
With a native query, your named parameter won't work. You need to remove the nativeQuery = true
Related
I'm relatively new to Spring JPA CriteriaQuery. Im trying to convert my old native query in my program to criteria query and haven't been successful on join query for multiple table with conditions. I need help converting native SQL query into Criteria Query for these query below :
select * from student s inner join (
select distinct on (student_id) * from class where status = 'Active' order by
student_id,date_register desc) c on s.id = c.user_id
inner join teacher t on t.subject_id = c.subject_id
where t.status = 'Active' and s.status='Active' order by s.name desc
Update :
Below code is as far as I can go cause I dont really know much. Am i in the right direction? I'm opting for Expression because i dont know how to use Join.
CriteriaQuery<Student> query = cb.createQuery(Student.class);
Root<Student> sRoot= query.from(Student.class);
query.select(sRoot);
Subquery<Integer> subquery = query.subquery(Integer.class);
Root<Class> cRoot= subquery.from(CLass.class);
Expression<Integer> max = cb.max(cRoot.get("dateRegister"));
subquery.select(max);
subquery.groupBy(cRoot.get("student"));
query.where(
cb.and(
cb.in(cRoot.get("dateRegister")).value(subquery)
)
);
Thanks in advance!
I'm new using hibernate, I have query like :
select count(1) from (
SELECT COUNT (1)
FROM USR_BASE
WHERE ST_CD = 1
group by USR_NO)
How can I implement that query in Hibernate using criteria ?
Because, I already implement with method :
public int totalUser(UsrBase usrBase) {
Criteria criteria = createCriteria();
String stCd = usrBase.getStCd();
criteria.setProjection(Projections.projectionList())
.add(Projections.property("usrNo"))
.add(Projections.property(stCd))
.add(Projections.groupProperty("usrNo")));
return((Long)criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();
}
the result not same with my query... Please help me.
select count(1) from (
SELECT COUNT (1)
FROM USR_BASE
WHERE ST_CD = 1
group by USR_NO)
I think it will be more easily with
select count(distinct(USR_NO)) from USR_BASE WHERE ST_CD = 1
let's say i have 2 queries and 2 ResultSet. the first one is members table query, while the second query is for other member datas. now i want to join the first resultset with the second one. for example it looks like this
ResultSet rsMember = psMembers.executeQuery();
ResultSet rsCustomValues = psCustomValues.executeQuery();
// object for mapping query results
MembersMapper memberMapper = new MembersMapper();
while (rsMember.next()) {
memberMapper.setId(rsMember.getString("id"));
memberMapper.setName(rsMember.getString("name"));
memberMapper.setUsername(rsMember.getString("username"));
memberMapper.setGroup(rsMember.getString("group_id"));
List strCustomValues = new ArrayList<>();
while(rsCustomValues.next()){
// map the custom values
Map<String, Object> mapTemp = new HashMap<String, Object>();
mapTemp.put(FIELD_ID, rsCustomValues.getString("custom_field_id"));
mapTemp.put(INTERNAL_NAME,
rsCustomValues.getString("custom_field_internalname"));
mapTemp.put(NAME,rsCustomValues.getString("custom_field_name"));
strCustomValues.add(mapTemp);
}
memberMapper.setCustomvalues(strCustomValues);
}
the problem is the second (inner while) query. what connects data between first and second resultset is member id, which is primary key in first table (first query) and foreign key in second query. so the second query will have member id in random order.
so how can i order the second query without having to put 'order by member_id' in the second query? i will have to avoid 'order by member_id' because it will take time to process.
Edit: here's the scripts
First script
select
mbr.*, usr.username, grp.name as groupname, grp.status
from members mbr
join users usr on mbr.id = usr.id
join groups grp on mbr.group_id = grp.id
where mbr.id > #id#
order by id asc
limit #limit#
Second script
select
cfv.member_id as 'member_id', cf.id as 'custom_field_id',
cf.internal_name as 'custom_field_internalname',
cf.name as 'custom_field_name', cfv.string_value as 'cfv_stringvalue',
cfv.possible_value_id as 'cf_possiblevalueid', cfvp.value as 'cfvpvalue'
from custom_field_values cfv
join custom_fields cf on cf.id = cfv.field_id
left join custom_field_possible_values cfvp on cfv.possible_value_id = cfvp.id
where exists(
select * from (select id from members where id > #id#
limit #limit#
) result where result.id = cfv.member_id)
and cf.subclass = #subclass#
order by cfv.member_id asc
It is better to fetch the second result set to an object representation and sort it out.
See a similar question here How can I sort ResultSet in java?
I have 2 tables, I want to fetch data from these tables where their foreign key is same. I have written a sql query first by using union:
SELECT jw.widget_name,jw.user_id FROM dashboard.jira_widget as jw WHERE jw.user_id = '1'
UNION ALL
SELECT uw.widget_name,uw.user_id FROM dashboard.unit_test_widget as uw WHERE uw.user_id = '1'
But Jpa doesn't support UNION at all.
Is there any other way to write this query in jpa?
I would suggest to try this query :
EntityManager em;
Query query = em.createQuery('SELECT jw, uw FROM JiraWidget as jw, UnitTestWidget as uw WHERE jw.userId = uw.userId AND jw.userId=:user');
query.setParameter('user', user);
Since multiple Select expression are used, the result is of type Object[]:
List<Object[]> results query.getResultList();
for (Object[] myUnion: results) {
JiraWidget jw = (JiraWidget) myUnion[0];
UnitTestWidget uw = (UnitTestWidget) myUnion[1];
//etc...
}
I'm new to hibernate and I've this SQL query which works perfectly
SELECT count(*) as posti_disponibili from occupazione t inner join
(select id_posto_park, max(date_time) as MaxDate from occupazione
group by id_posto_park) tm on t.id_posto_park = tm.id_posto_park and
t.date_time = tm.Maxdate and t.isOccupied = 0
which gives me all the last items with isOccupied = 0
I was porting it into Hibernate, I've tried to use
result = ( (Integer) session.createSQLQuery(query).iterate().next() ).intValue()
to return posti_disponibili but i got this exception
java.lang.UnsupportedOperationException: SQL queries do not currently support iteration
How can i solve this? I cannot find the equivalent HQL query
Thank you
I would suggest you to use
Query#uniqueResult()
which will give you single result.
select count(*) .....
will always return you a single result.
Hibernate support it's own iterator-like scroll:
String sqlQuery = "select a, b, c from someTable";
ScrollableResults scroll = getSession().createSQLQuery(sqlQuery).scroll(ScrollMode.FORWARD_ONLY);
while (scroll.next()) {
Object[] row = scroll.get();
//process row columns
}
scroll.close();