JPA, nativeQuery The value is shown above - html

The code below is repository
#Query
(
value = "select min(id) as id, coalesce (sum(case when points > 0 then points end), 0) as points, userid" +
" from books" +
" where userid = ?1" +
" group by userid", nativeQuery = true
)
JamInfo findPlus(Long userid);
#Query
(
value = "select min(id) as id, coalesce(sum(case when points < 0 then points*-1 end),0)as points, userid" +
" from books" +
" where userid = ?1" +
" group by userid", nativeQuery = true
)
JamInfo findMinus(Long userid);
The code below is controller
JamInfo jamplus = jamInfoRepository.findPlus(id);
JamInfo jamminus = jamInfoRepository.findMinus(id);
model.addAttribute("jamplus", jamplus);
model.addAttribute("jamminus", jamminus);
If you print it like this, it will be unified with the value of jamplus written first. How can the two values ​​be output differently?

Related

HibernateException: Errors in named queries: FindPostWithComments

In my Spring 4 application I have an issue with named native query:
#NamedNativeQuery(name = "FindPostWithComments", query =
" SELECT * FROM ("
+ " SELECT p.*, "
+ " MATCH (description) AGAINST ('text') AS score "
+ " FROM posts as p"
+ " WHERE MATCH (description) AGAINST ('text') > 0 "
+ " LIMIT 0, 10 "
+ " ) p LEFT JOIN ( "
+ " SELECT c.*, "
+ " #rownumber := CASE WHEN #post_id = post_id THEN #rownumber + 1 ELSE 1 END AS n, "
+ " #post_id := post_id "
+ " FROM comments c, "
+ " (SELECT #rownumber := 0, #post_id := 0) r "
+ " WHERE MATCH (content) AGAINST ('text') > 0 "
+ " ORDER BY c.last_edited DESC, post_id DESC "
+ " ) c ON p.post_id = c.post_id "
+ " WHERE c.post_id IS NULL OR n BETWEEN 1 and 3 "
+ " ORDER BY score DESC "
, resultSetMapping = "PostWithComments")
#SqlResultSetMappings({
#SqlResultSetMapping(
name = "PostWithComments",
entities = {
#EntityResult(entityClass = Post.class, fields = {
#FieldResult(name = "id", column = "p.post_id"),
#FieldResult(name = "userId", column = "p.user_id"),
#FieldResult(name = "type", column = "p.type_id"),
#FieldResult(name = "description", column = "p.description"),
#FieldResult(name = "link", column = "p.link"),
#FieldResult(name = "dateCreated", column = "p.date_created"),
#FieldResult(name = "lastEdited", column = "p.last_edited"),
#FieldResult(name = "totalVotes", column = "p.total_votes"),
#FieldResult(name = "totalComments", column = "p.total_comments")
}
),
#EntityResult(entityClass = Comment.class, fields = {
#FieldResult(name = "id", column = "c.comment_id"),
#FieldResult(name = "post", column = "c.post_id"),
#FieldResult(name = "userId", column = "c.user_id"),
#FieldResult(name = "dateCreated", column = "c.date_created"),
#FieldResult(name = "lastEdited", column = "c.last_edited"),
#FieldResult(name = "content", column = "c.content"),
#FieldResult(name = "totalVotes", column = "c.total_votes")
}
)
}
)
})
It fails during the application startup with a following exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Errors in named queries: FindPostWithComments
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1566)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:747)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4728)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5162)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1399)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.HibernateException: Errors in named queries: FindPostWithComments
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:545)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1859)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:852)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:845)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:398)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:844)
at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:152)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:338)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1625)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1562)
... 21 more
What is the possible cause?
This query perfectly works from MySQL workbench.
I found the reason by myself. I need to add double slashes before each colon sign, so the final query must look like:
" SELECT * FROM ("
+ " SELECT p.*, "
+ " MATCH (description) AGAINST (:term) AS score "
+ " FROM posts as p"
+ " WHERE MATCH (description) AGAINST (:term) > 0 "
+ " LIMIT 0, 10 "
+ " ) p LEFT JOIN ( "
+ " SELECT c.*, "
+ " #rownumber \\:= CASE WHEN #post_id = post_id THEN #rownumber + 1 ELSE 1 END AS n, "
+ " #post_id \\:= post_id "
+ " FROM comments c, "
+ " (SELECT #rownumber \\:= 0, #post_id \\:= 0) r "
+ " WHERE MATCH (content) AGAINST (:term) > 0 "
+ " ORDER BY c.last_edited DESC, post_id DESC "
+ " ) c ON p.post_id = c.post_id "
+ " WHERE c.post_id IS NULL OR n BETWEEN 1 and 3 "
+ " ORDER BY score DESC "

SQL multiple ORDER BY columns sort by Desc and Asc

This is what I've tried so far:
SELECT M.ID, M.NAME, M.SEQ
FROM M JOIN MCA
ON M.ID = MCA.M_ID
JOIN MC
ON MCA.CAT_ID = MC._ID
WHERE MCA.CAT_ID = "
+ inputCategoryID
+ " AND (M.NAME LIKE '"
+ inputSearch.replace("'", "''")
+ "%' OR M.NAME LIKE '%"
+ inputSearch.replace("'", "''")
+ "%' ) AND M.START_DATE <= CURRENT_DATE " +
AND M.EXPIRY_DATE >= CURRENT_DATE " +
ORDER BY M.SEQ DESC, M.NAME ASC
SAMPLE RESULTS:
ID NAME SEQ
1 Tes1 0
2 Arj2 0
3 Jfa3 1
4 Pof4 0
DESIRED RESULTS:
ID NAME SEQ
3 Jfa3 1
2 Arj2 0
4 Pof4 0
1 Tes1 0
But if the same SEQ value (i.e., 0, 0), it should display Name alphabetically. Any ideas how to do that? Thanks.

CASE statement not updating Temp Table

In the UPDATE statement below, the InspectionChg, MileageChg, FuelChg and FreightChg columns are not updating to temp table. Goal is to aggregate charges. I have tried several variations and I cannot get Temp Table Columns to update.
UPDATE #TTable
SET ChargeCode = id.cht_itemcode,
InspectionChg = CASE WHEN LEFT(id.cht_itemcode, 3) = 'INS' THEN
InspectionChg+id.ivd_charge ELSE InspectionChg+0 END,
MileageChg = CASE WHEN LEFT(id.cht_itemcode, 4) = 'MILE' THEN MileageChg+id.ivd_charge
ELSE MileageChg+0 END,
FuelChg = CASE WHEN LEFT(id.cht_itemcode, 4) = 'FUEL' THEN
FuelChg+id.ivd_charge ELSE FuelChg+0 END,
FreightChg = CASE WHEN LEFT(id.cht_itemcode, 2) = 'LH' THEN FreightChg+id.ivd_charge
ELSE FreightChg+0 END,
Rate = 1
FROM #TTable
INNER JOIN invoicedetail as id
on #TTable.OrderNumber = id.Ord_hdrnumber
What is wrong?
UPDATE TT
SET TT.ChargeCode = id.cht_itemcode ,
TT.InspectionChg = ( CASE WHEN LEFT(id.cht_itemcode, 3) = 'INS'
THEN InspectionChg + id.ivd_charge
ELSE InspectionChg + 0
END ) ,
TT.MileageChg = ( CASE WHEN LEFT(id.cht_itemcode, 4) = 'MILE'
THEN MileageChg + id.ivd_charge
ELSE MileageChg + 0
END ) ,
TT.FuelChg = ( CASE WHEN LEFT(id.cht_itemcode, 4) = 'FUEL'
THEN FuelChg + id.ivd_charge
ELSE FuelChg + 0
END ) ,
TT.FreightChg = ( CASE WHEN LEFT(id.cht_itemcode, 2) = 'LH'
THEN FreightChg + id.ivd_charge
ELSE FreightChg + 0
END ) ,
TT.Rate = 1
FROM #TTable AS TT
INNER JOIN invoicedetail AS id ON TT.OrderNumber = id.Ord_hdrnumber

Subquery returns more than 1 row sql query

I had such an error can explain what I did wrong?
I only add this sql query:
(? = (select travel_region_id from relationships where travel_id = travels.id))
error
ActiveRecord::StatementInvalid (Mysql::Error: Subquery returns more than 1 row: select count(*) from travel_start_days, cars, travels
where travels.id = travel_start_days.travel_id and travels.id = travel.car_id and travel_start_days.day > adddate(curdate(), interval '2' day) and (7 = (select travel_region_id from relationships where travel_id = travels.id)) and '2013-08-16' <= travel_start_days.day):
Update Whis is method create query
def conditions
where = ''
param = []
if #region && #region != ''
where += 'travels.region_id = ?'
param += [#region.to_i]
end
if #car && #car != ''
where += ' and ' if where != ''
where += 'cars.id = ?'
param += [#car.to_i]
end
if #relation && #relation != ''
where += ' and ' if where != ''
where += '(? = (select travel_region_id from relationships where travel_id = travels.id))'
param += [#relation.to_i]
end
if #start_port && #start_port != ''
where += ' and ' if where != ''
where += '(? = (select location_id from travel_days where travel_id = travel_start_days.travel_id and day_no = 1 order by arrival asc limit 1))'
param += [#start_port.to_i]
end
return where == '' ? nil : ["travel_start_days.day > adddate(curdate(), interval ? day) and " + where] + [#criteria[5]] + param
end
The issue in this part of conditions:
(7 = (select travel_region_id from relationships where travel_id = travels.id))
Obviously this subquery returns more than one travel_region_id just replace = with IN
(7 IN (select travel_region_id from relationships where travel_id = travels.id))
If you are getting more than 1 row from subquery, then add group by clause to your subquery
SELECT travel_region_id FROM relationships
WHERE travel_id = travels.id
GROUP BY travel_region_id

MYSQL: Can you pull results that match like 3 out of 4 expressions?

Say I have a query like this:
SELECT * FROM my_table WHERE name = "john doe" AND phone = "8183321234" AND email = "johndoe#yahoo.com" AND address = "330 some lane";
But say I only need 3 out of the 4 to match, I know I can write a very long query with several ORs but I was wondering if there was a feature for this?
Thanks.
SELECT
*
FROM
my_table
WHERE
CASE WHEN name = "john doe" THEN 1 ELSE 0 END +
CASE WHEN phone = "8183321234" THEN 1 ELSE 0 END +
CASE WHEN email = "johndoe#yahoo.com" THEN 1 ELSE 0 END +
CASE WHEN address = "330 some lane" THEN 1 ELSE 0 END
>= 3;
Side note: this will very likely not be using indexes efficiently. On the other hand, there will very likely be no indexes on these kinds of columns anyway.
Holy overcomplexity, Batman.
SELECT *
FROM my_table
WHERE (
(name = "john doe") +
(phone = "8183321234") +
(email = "johndoe#yahoo.com") +
(address = "330 some lane")
) >= 3;
Same thing using indexes:
SELECT *
FROM (
SELECT id
FROM (
SELECT id
FROM mytable _name
WHERE name = 'john doe'
UNION ALL
SELECT id
FROM mytable _name
WHERE phone = '8183321234'
UNION ALL
SELECT id
FROM mytable _name
WHERE email = "johndoe#yahoo.com"
UNION ALL
SELECT id
FROM mytable _name
WHERE address = '330 some lane'
) q
GROUP BY
id
HAVING
COUNT(*) >= 3
) di, mytable t
WHERE t.id = di.id
See the entry in my blog for performance details.
I like the IF construct:
SELECT * FROM my_table
WHERE
( IF(name = 'john doe', 1, 0) +
IF(phone = '8183311234', 1, 0) +
IF(email = 'johndoe#yahoo.com', 1, 0) +
IF(address = '330 some lane', 1, 0)
) >= 3
Modifying Tomalak's query slightly so that it will use indexes if they are present. Although unless there is an index on each field, a full table scan will happen anyway.
SELECT
*,
(
IF(name="john doe", 1, 0) +
IF(phone = "8183321234", 1, 0) +
IF(email = "johndoe#yahoo.com", 1, 0) +
IF(address = "330 some lane", 1, 0)
) as matchCount
FROM my_table
WHERE
name = "john doe" OR
phone = "8183321234" OR
email = "johndoe#yahoo.com" OR
address = "330 some lane"
HAVING matchCount >= 3