I am trying to retrieve multiple variables in the URL, so I could send a query to database to select a specific object, but it seems that it picks up the first object and others are null.
#RequestMapping(value = "getGroup/{Name}/{StartDate}/{EndDate}/{Status_GroupID}", method = RequestMethod.GET)
public #ResponseBody List<GroupsDetails> getGroupList(
#PathVariable String Name, String StartDate, String EndDate,
Integer Status_GroupID) {
return musicStoreService.getGroupList(Name, StartDate, EndDate, Status_GroupID);
}
The error I am recieving:
Hibernate: select groupsdeta0_.Status_GroupID as Status1_1_, groupsdeta0_.GroupsID as GroupsID1_, groupsdeta0_.EndDate as EndDate1_, groupsdeta0_.Name as Name1_, groupsdeta0_.StartDate as StartDate1_ from Groups groupsdeta0_ where groupsdeta0_.Name=Gamma and (groupsdeta0_.StartDate is null) and (groupsdeta0_.EndDate is null) and (groupsdeta0_.Status_GroupID is null)
Sep 12, 2014 2:41:40 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [SpringDispatcher] in context with path [/ATS] threw exception [Request processing failed; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query] with root cause
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'Gamma' in 'where clause'
The table is named Groups and it has rows : Name, StartDate, EndDate, Status_GroupID and GroupsID
Update:
I am trying to retrieve a primarykey by giving the rows details, but it is not working.
#Override
public List<GroupsDetails> getGroupList(String Name, String StartDate, String EndDate, Integer Status_GroupID) {
SessionFactory sessionFactory=HibernateSessionManager.getSessionFactory();
Session session=sessionFactory.getCurrentSession();
Transaction transaction=session.beginTransaction();
try{
transaction.begin();
#SuppressWarnings("unchecked")
List<GroupsDetails> groupList=session.createSQLQuery("FROM Groups WHERE Name=" + Name + " AND StartDate=" + StartDate + " AND EndDate=" + EndDate + " AND Status_GroupID=" + Status_GroupID).list();
return groupList;
}finally{
session.close();
}
}
But it throws the exception that is badly syntax, even tho I can not see the error in syntax.
The error is :
Hibernate: FROM Groups WHERE Name=Gamma AND StartDate=01-06-2014 AND EndDate=01-09-2014 AND Status_GroupID=1
Sep 12, 2014 3:35:51 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [SpringDispatcher] in context with path [/ATS] threw exception [Request processing failed; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query] with root cause
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM Groups WHERE Name=Gamma AND StartDate=01-06-2014 AND EndDate=01-09-2014 AND' at line 1
As per the error details :
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right syntax to use near
'FROM Groups WHERE Name=Gamma AND StartDate=01-06-2014 AND EndDate=01-09-2014 AND' at line 1
it clearly shows that you are missing quotes, eg: Name=Gamma should be Name='Gamma'
Alternatively you can create the Query by using Parameters for example:
query = sess.createSQLQuery("SELECT * FROM Groups
WHERE NAME=:name AND StartDate=:startDate AND EndDate=:endDate
AND Status_GroupID=:status_GroupID").addEntity(Groups.class);
query.setString("name", name);
query.setDate("startDate", StartDate);
query.setString("endDate", EndDate);
query.setString("status_GroupID", Status_GroupID);
List<GroupsDetails> groupList = query.list();
You need to have #PathVariable infront of all parameters. Like
public #ResponseBody List<GroupsDetails> getGroupList(
#PathVariable String Name, #PathVariable String StartDate, #PathVariable String EndDate,
#PathVariable Integer Status_GroupID)
Related
I have the below #Query in my repository
#Query("select new Foo(id, code, coalesce(properties, '') as properties, env) "
+ "from Foo order by id desc")
public List<Foo> findAll();
I want to return blank for properties when its null.
But when I run the service I am getting below error:
unexpected token: as near line 1, column 87
Any idea on how to resolve this error? Thanks in advance.
The error is coming from trying to declaring an alias in a constructor expression. Remove the as properties.
in my table items has a json column named tag. keeping data like ["tag1", "tag2"] .
i want to select from this table filter with the given tag.
in mysql command line, json_contains works.
select * from items where json_contains(tags, '"tag1"');
but how can i using it in Spring JPA?
#Query(value = "select * from items where json_contains(tags, ?1))", nativeQuery = true)
Page<ItemDO> list(String query, Pageable pageable);
got error
TRACE 21469 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARCHAR] - [desc]
WARN 21469 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1064, SQLState: 42000
ERROR 21469 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') limit 10' at line 1
so how can i using json_contains withing Spring JPA?
There are two issues with your implementation:
There as an extra parenthesis at the end of SQL query ), look at what logs say. Instead, you should write it as follows:
#Query(value = "select * from items where json_contains(tags, ?1)", nativeQuery = true)
Having done that, you also need to wrap the method parameter (your query variable) inside double quotations, to exactly match what you tried in MySQL command line console. So, you will call the method as follows:
yourRepository.list("\"tag1\"", PageRequest.of(,10) );
Alternative solution
You may use Spring Data Specifications API to avoid native queries.
Thus, you could do the following:
#Repository
public interface ItemRepository extends JpaRepository<ItemDao, Integer> , JpaSpecificationExecutor<ItemDao> {
default Page<ItemDao> findItemsByJsonTagValue(String jsonTagValue, Pageable pageable){
return findAll((root, query, builder) -> {
final String CONTAINS_FUNCTION = "JSON_CONTAINS";
final String JSON_COLUMN_NAME = "tags" ;
final int TRUE_BIT = 1;
return builder.equal(
builder.function(
CONTAINS_FUNCTION,
String.class,
root.<String>get(JSON_COLUMN_NAME),
builder.literal(String.format("\"%s\"", jsonTagValue))),TRUE_BIT);
}, pageable);
}
}
And then somewhere in your code, you would call the method as follows :
itemRepository.findItemsByJsonTagValue("tag1", PageRequest.of(0 ,10));
SnappyData v.0-5 w/ ClientDriver JDBC driver.
I have a persistent row table in SnappyData called: sensor_data.
From the snappy> shell, this query returns thousands for rows.
snappy> select * from sensor_data where year_num = 2013 and
month_num = 1;
When run from a JDBC connection in SpringBoot, I get this error:
PreparedStatementCallback; uncategorized SQLException for SQL [select
* from sensor_data where year_num = ? and month_num = ?]; SQL state [XCL14]; error code [20000]; (SQLState=XCL14 Severity=20000) The
column position '1' is out of range. The number of columns for this
ResultSet is '0'.
Java Code is:
List<SensorData> list = jdbcTemplateBean.query("select * from sensor_data where year_num = ? and month_num = ?",
new Object[] {year, month}, new SensorDataRowMapper());
What do I need to do to fix this JDBC issue?
Trimmed Stacktrace on Spring boot:
org.springframework.jdbc.UncategorizedSQLException:
PreparedStatementCallback; uncategorized SQLException for SQL [select
* from sensor_data where year_num = ? and month_num = ?]; SQL state [XCL14]; error code [20000]; (SQLState=XCL14 Severity=20000) The
column position '1' is out of range. The number of columns for this
ResultSet is '0'.; nested exception is java.sql.SQLException:
(SQLState=XCL14 Severity=20000) The column position '1' is out of
range. The number of columns for this ResultSet is '0'. at
org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:84)
at
org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
at
org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
at
org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:645)
at
org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:680)
at
org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:707)
at
org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:757)
at
org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.query(NamedParameterJdbcTemplate.java:192)
at
org.kritek.scalability.repository.SensorDataRepository.findByYearAndMonth(SensorDataRepository.java:58)
...
at
org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555)
at java.lang.Thread.run(Thread.java:745) Caused by:
java.sql.SQLException: (SQLState=XCL14 Severity=20000) The column
position '1' is out of range. The number of columns for this
ResultSet is '0'.
...
Caused by: ERROR XCL14: The column position '1' is out of
range. The number of columns for this ResultSet is '0'. at
com.pivotal.gemfirexd.internal.client.am.ColumnMetaData.checkForValidColumnIndex(ColumnMetaData.java:856)
at
com.pivotal.gemfirexd.internal.client.am.ColumnMetaData.getColumnType(ColumnMetaData.java:638)
... 72 more
From the stack it looks like NamedParameterJdbcTemplate is being used but '?' placeholders are being used. For NamedParameterJdbcTemplate you need to use named parameters like here.
I will recommend using the standard '?' placeholder mechanism with JdbcTemplate like:
private JdbcTemplate jdbcTemplateBean;
public void setDataSource(DataSource dataSource) {
this.jdbcTemplateBean = new JdbcTemplate(dataSource);
}
List<SensorData> list = jdbcTemplateBean.query(
"select * from sensor_data where year_num = ? and month_num = ?",
new Object[] { year, month }, new SensorDataRowMapper());
The issue has been resolved. Here is what happened.... SnappyData routed the query to Spark because it determined it could not handle it. Spark knows nothing about JDBC PreparedStatements or bind variables and raised the error. To fix, I had to set the SnappyData JDBC property "route-query = false" in my DataSource configuration. This ensured it was not routed to Spark.
Hybris Console :
ERROR [hybrisHTTP19] [FlexibleSearch] Flexiblesearch error: missing values for [emailId, productCode], got {13=8796135981138, issent=false, productcode =0100, emailid ='hybrisa#gmail.com'}
ERROR [hybrisHTTP19] [FlexibleSearch] query was 'SELECT {p:pk} FROM {NotifyStock AS p} WHERE {p:status}=?isSent AND {p:productId}=?productCode AND {p:emailId}=?emailId '
ERROR [hybrisHTTP19] [FlexibleSearch] translated query was: SELECT item_t0.PK FROM notifystock item_t0 WHERE ( item_t0.p_status =? AND item_t0.p_productid =? AND item_t0.p_emailid =?) AND (item_t0.TypePkString=? )
Aug 31, 2015 6:51:35 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [DispatcherServlet] in context with path [/store] threw exception [Request processing failed; nested exception is de.hybris.platform.servicelayer.search.exceptions.FlexibleSearchException: missing values for [emailId, productCode], got {13=8796135981138, issent=false, productcode =0100, emailid ='hybrisa#gmail.com'}] with root cause
de.hybris.platform.jalo.flexiblesearch.FlexibleSearchException: missing values for [emailId, productCode], got {13=8796135981138, issent=false, productcode =0100, emailid ='hybrisa#gmail.com'}[HY-0]
at de.hybris.platform.persistence.flexiblesearch.TranslatedQuery.removeUnusedValues(TranslatedQuery.java:274)
at de.hybris.platform.jalo.flexiblesearch.FlexibleSearch.search(FlexibleSearch.java:1423)
at de.hybris.platform.jalo.flexiblesearch.FlexibleSearch.search(FlexibleSearch.java:1627)
at de.hybris.platform.servicelayer.search.impl.DefaultFlexibleSearchService$2.execute(DefaultFlexibleSearchService.java:374)
at de.hybris.platform.servicelayer.search.impl.DefaultFlexibleSearchService$2.execute(DefaultFlexibleSearchService.java:1)
at de.hybris.platform.servicelayer.session.impl.DefaultSessionService.executeInLocalView(DefaultSessionService.java:88)
at de.hybris.platform.servicelayer.search.impl.DefaultFlexibleSearchService.getJaloResult(DefaultFlexibleSearchService.java:363)
at de.hybris.platform.servicelayer.search.impl.DefaultFlexibleSearchService.search(DefaultFlexibleSearchService.java:164)
at de.hybris.merchandise.core.notifystock.NotifyStockServices.isAlreadyExists(NotifyStockServices.java:118)
at de.hybris.merchandise.facades.NotifyStock.impl.NotifyStockFacadeImpl.isAlreadyExists(NotifyStockFacadeImpl.java:51)
at de.hybris.merchandise.storefront.controllers.misc.AddToCartController.verifyEmail(AddToCartController.java:132)
Working Query in HAC :
select {p:PK} From {NotifyStock AS p} WHERE {p:status}=0 AND {p:productId}=0100 AND {p:emailId}='ertsergt#gmail.com'
Flexiblesearch Query(Not working):
final StringBuilder builder = new StringBuilder();
builder.append("SELECT {p:").append(ItemModel.PK).append("} ");
builder.append("FROM {").append(NotifyStockModel._TYPECODE).append(" AS p} ");
builder.append("WHERE ").append("{p:").append(NotifyStockModel.STATUS).append("}").append("=?isSent ");
builder.append("AND ").append("{p:").append(NotifyStockModel.PRODUCTID).append("}").append("=?productCode ");
builder.append("AND ").append("{p:").append(NotifyStockModel.EMAILID).append("}").append("=?emailId ");
final String email = "\'" + notifyStockModel.getEmailId() + "\'";
final FlexibleSearchQuery query = new FlexibleSearchQuery(builder.toString());
query.setNeedTotal(true);
query.addQueryParameter("isSent", Boolean.FALSE);
query.addQueryParameter("productCode ", notifyStockModel.getProductId());
query.addQueryParameter("emailId ", email);
When i Fire the above Query in HAC the query is working fine but when i fired the same query using flexible search i am getting some flexiblesarch exception.Can anyone tell me what is the Mistake in my flexible search query?Any help would be appreciated?
Adding to what Shresht has answered, always make it a habit to use the field name constants in the parameter map as well.
Example :
query.addQueryParameter(NotifyStockModel.PRODUCTID, notifyStockModel.getProductId());
query.addQueryParameter(NotifyStockModel.EMAILID, email);
The above syntax will never lead to issues. Also for such direct matching queries, I suggest you use flexible search's below method :
flexibleSearchService.getModelByExample(example)
This results in a more maintainable code. Check the wiki for more info.
I think you are giving extra space while adding query parameter for productCode and emailId in FlexibleSearchQuery. That's why you are getting missing values for [emailId, productCode] error.
Replace this
query.addQueryParameter("productCode ", notifyStockModel.getProductId()); // extra space after productCode
query.addQueryParameter("emailId ", email); // extra space after emailId
with
query.addQueryParameter("productCode", notifyStockModel.getProductId());
query.addQueryParameter("emailId", email);
Hope this will fix your problem.
I am trying to perform IN search using JbdcTemplate in Spring. Here goes my code
#Override
public Map<String, List> dataRetriveForAsset(String type) {
List<Integer> interfaceIdList = new ArrayList<Integer>();
List<Integer> fileList = new ArrayList<Integer>();
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
String sql2 = "select interface_id from tbl_interface_asset where asset_id in ( :ids )";
//fileList is populated with a different query
Set<Integer> ids = new HashSet(Arrays.asList(new Integer[fileList.size()] ));
for(int i=0; i<fileList.size();i++)
{
ids.add(fileList.get(i));
}
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("ids", ids);
interfaceIdList = jdbcTemplate.query(sql2,new ListMapper1(),parameters );
and the sql2 query part executes it throws the following error.
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/iccdashboard] threw exception [Request processing failed; nested exception is org.springframework.dao.TransientDataAccessResourceException: PreparedStatementCallback; SQL [select interface_id from tbl_interface_asset where asset_id in ( :ids )]; Invalid argument value: java.io.NotSerializableException; nested exception is java.sql.SQLException: Invalid argument value: java.io.NotSerializableException] with root cause
java.io.NotSerializableException: org.springframework.jdbc.core.namedparam.MapSqlParameterSource
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at com.mysql.jdbc.PreparedStatement.setSerializableObject(PreparedStatement.java:4401)
at com.mysql.jdbc.PreparedStatement.setObject(PreparedStatement.java:4083)
at org.springframework.jdbc.core.StatementCreatorUtils.setValue(StatementCreatorUtils.java:351)
at org.springframework.jdbc.core.StatementCreatorUtils.setParameterValueInternal(StatementCreatorUtils.java:216)
at org.springframework.jdbc.core.StatementCreatorUtils.setParameterValue(StatementCreatorUtils.java:144)
But if I use NamedParameterJdbcTemplate, I am getting a BadSQLGrammarError because the 'ids' value my sql query goes emplty like below.
select interface_id from tbl_interface_asset where asset_id in ( )
java.io.NotSerializableException: org.springframework.jdbc.core.namedparam.MapSqlParameterSource
I was able to fix this problem by replacing my usage of
org.springframework.jdbc.core.JdbcTemplate
with the:
org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
I was using the MapSqlParameterSource class but using the standard template which may have been the problem.
But if I use NamedParameterJdbcTemplate, I am getting a BadSQLGrammarError because the 'ids' value my sql query goes empty like below.
Can you make the SQL generation conditional on whether or not there are entries in your IN collection?
if (!ids.isEmpty()) {
parameters.addValue("ids", ids);
}