Spring Mybatis Oracle function call - mybatis

I'm getting following error while calling the oracle function...
org.springframework.jdbc.UncategorizedSQLException:
### Error querying database. Cause: java.sql.SQLException: Non supported SQL92 token at position: 1:
### The error may exist in file [C:\Users\pkr\rpt\bin\dbmappers\MyMapper.xml]
### The error may involve com.pkr.tpy.rpt.dao.MyDao.resetRecs-Inline
### The error occurred while setting parameters
### SQL: { ? = call actions.reset_recs(?, ?, ?, ?) }
### Cause: java.sql.SQLException: Non supported SQL92 token at position: 1:
; uncategorized SQLException for SQL []; SQL state [99999]; error code [17034]; Non supported SQL92 token at position: 1: ; nested exception is java.sql.SQLException: Non supported SQL92 token at position: 1:
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.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:75)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:447)
at com.sun.proxy.$Proxy37.selectOne(Unknown Source)
Here is my mapper.xml
<select id="resetRecs" resultType="String" statementType="CALLABLE">
{
#{retVal,mode=OUT,jdbcType=VARCHAR} = call actions.reset_recs(#{xCode, jdbcType=DECIMAL,mode=IN},
#{yCode,jdbcType=DECIMAL,mode=IN},
#{xyzNum,jdbcType=DECIMAL,mode=IN},
#{src,jdbcType=VARCHAR,mode=IN})
}
</select>
DAO Interface:
String resetRecs(#Param("xCode") int xCode,
#Param("yCode") int yCode,
#Param("xyzNum") int xyzNum, #Param("xyzSrc") String xyzSource,
#Param("retVal") String retVal);
I'm using Mybatis 3.4.0, any help would be greatly appreciated.

I was able to fix this when I updated my mapper call statement in one line.
<select id="resetRecs" resultType="String" statementType="CALLABLE">
{#{retVal,mode=OUT,jdbcType=VARCHAR} = call actions.reset_recs(#{xCode, jdbcType=DECIMAL,mode=IN},#yCode,jdbcType=DECIMAL,mode=IN},#xyzNum,jdbcType=DECIMAL,mode=IN},#{src,jdbcType=VARCHAR,mode=IN})}

Related

Using $1 in the #Query throws exception: Cannot encode parameter of type org.springframework.r2dbc.core.Parameter

I'm using R2DBC in my project. After upgrading to Spring Boot from 2.5.* to 2.6.1 my query:
#Query("SELECT EXISTS(SELECT 1 FROM some_link links WHERE links.data_id = $1 AND links.some_id != links.source_id)")
fun existsByDataIdAndLocked(dataId: UUID): Mono<Boolean>
Throws an exception:
Suppressed: java.lang.IllegalArgumentException: Cannot encode parameter of type org.springframework.r2dbc.core.Parameter
at io.r2dbc.postgresql.codec.DefaultCodecs.encode(DefaultCodecs.java:192)
at io.r2dbc.postgresql.ExtendedQueryPostgresqlStatement.bind(ExtendedQueryPostgresqlStatement.java:89)
at io.r2dbc.postgresql.ExtendedQueryPostgresqlStatement.bind(ExtendedQueryPostgresqlStatement.java:47)
at org.springframework.r2dbc.core.DefaultDatabaseClient$StatementWrapper.bind(DefaultDatabaseClient.java:544)
at java.base/java.util.LinkedHashMap.forEach(LinkedHashMap.java:684)
at org.springframework.data.r2dbc.repository.query.StringBasedR2dbcQuery$ExpandedQuery.bindTo(StringBasedR2dbcQuery.java:227)
at org.springframework.r2dbc.core.DefaultDatabaseClient$DefaultGenericExecuteSpec.lambda$execute$2(DefaultDatabaseClient.java:334)
at org.springframework.r2dbc.core.DefaultDatabaseClient$DefaultGenericExecuteSpec.lambda$execute$3(DefaultDatabaseClient.java:374)
at org.springframework.r2dbc.core.ConnectionFunction.apply(ConnectionFunction.java:46)
at org.springframework.r2dbc.core.ConnectionFunction.apply(ConnectionFunction.java:31)
at org.springframework.r2dbc.core.DefaultFetchSpec.lambda$all$2(DefaultFetchSpec.java:88)
at org.springframework.r2dbc.core.ConnectionFunction.apply(ConnectionFunction.java:46)
at org.springframework.r2dbc.core.ConnectionFunction.apply(ConnectionFunction.java:31)
at org.springframework.r2dbc.core.DefaultDatabaseClient.lambda$inConnectionMany$6(DefaultDatabaseClient.java:138)
at reactor.core.publisher.FluxUsingWhen.deriveFluxFromResource(FluxUsingWhen.java:119)
at reactor.core.publisher.FluxUsingWhen.access$000(FluxUsingWhen.java:53)
at reactor.core.publisher.FluxUsingWhen$ResourceSubscriber.onNext(FluxUsingWhen.java:194)
... 172 more
Once I change $1 in the query to :dataId then it works.
Why is that? As per documentation, both are valid.

Query Native - could not extract ResultSet

i have a problem.I explain my situation: SpringBoot + Hibernate + Multitenant (DB master + DB for tenant) + Postgressql. I have two datasource configurations, one for the master and one for each client's database. I need doing a query native in JPARepository And that's the only way I can do it
In my JPARepository :
public interface IEntity extends JpaRepository<Entity, Integer> {
........
#Query(value = "ALTER SEQUENCE entity_identity_seq RESTART", nativeQuery = true)
#Modifying ///Add 1
#Transactional ///Add 2
void restarID();
}
when I first call the method, I got:
> Hibernate:
ALTER SEQUENCE entity_identity_seq RESTART
> 2019-09-10 15:41:53.919 WARN 18680 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 02000
> 2019-09-10 15:41:53.919 ERROR 18680 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : La consulta no retornó ningún resultado.
> 2019-09-10 15:41:53.940 ERROR 18680 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet] with root cause
org.postgresql.util.PSQLException: La consulta no retornó ningún resultado.
After looking for solutions and discovered that he needed to add
#Query(value = "ALTER SEQUENCE entity_identity_seq RESTART", nativeQuery = true)
#Modifying
void restarID();
But the query is not made in hibernate and this error comes up:
> 2019-09-10 15:46:57.972 ERROR 14392 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Executing an update/delete query; nested exception is javax.persistence.TransactionRequiredException: Executing an update/delete query] with root cause
javax.persistence.TransactionRequiredException: Executing an update/delete query
I keep searching and find that I should add #Transactional. Then :
#Query(value = "ALTER SEQUENCE entity_identity_seq RESTART", nativeQuery = true)
#Modifying
#Transactional
void restarID();
But, then come back, I call the method, I got:
> Hibernate:
ALTER SEQUENCE entity_identity_seq RESTART
> 2019-09-10 15:41:53.919 WARN 18680 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 02000
> 2019-09-10 15:41:53.919 ERROR 18680 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : La consulta no retornó ningún resultado.
> 2019-09-10 15:41:53.940 ERROR 18680 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet] with root cause
org.postgresql.util.PSQLException: La consulta no retornó ningún resultado.
Please, will anyone have any recommendations?
I am new to hibernate. Thank you.
If someone yet have the same problem, I've resolved it, adding the next to the query:
#Modifying(clearAutomatically = true)
#Transactional

Media type separator is missing

Please help as I don't know what is wrong here. I have a very simple REST GET service but I keep running into the error below:
#GET
#Path("users/{id}")
#Produces("text/plain")
public Response getUserById(#PathParam("id") String id) {
return Response.status(200).entity("getUserById is called, id : " + id).build();
}
And the exception I'm seeing is below:
[ERROR ] SRVE0315E: An exception occurred: java.lang.Throwable: javax.servlet.ServletException: SRVE0207E: Uncaught initialization exception created by servlet
at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:5000)
at [internal classes]
Caused by: javax.servlet.ServletException: SRVE0207E: Uncaught initialization exception created by servlet
at com.ibm.ws.webcontainer.servlet.ServletWrapper.init(ServletWrapper.java:401)
... 1 more
Caused by: java.lang.IllegalArgumentException: Media type separator is missing
at org.apache.cxf.jaxrs.impl.MediaTypeHeaderProvider.handleMediaTypeWithoutSubtype(MediaTypeHeaderProvider.java:196)
... 1 more
Any idea what is wrong here? TIA

MyBatis issue: Unrecognized jdbcType

While trying to convert my app from using MyBatis [it was iBatis before], I've been getting the following error, in spite of trying to make so many different kinds of changes to the code: What am I doing wrong? Any help would be really really really great!!!
Error message:
`Caused by: org.springframework.jdbc.UncategorizedSQLException: ### Error querying database. Cause: com.ibm.db2.jcc.am.SqlException: [jcc][10271][10296][3.58.82] Unrecognized JDBC type: -10. ERRORCODE=-4228, SQLSTATE=null
`
`### The error may exist in Path-to-XML-File.XML`
`### The error may involve namespace.resultMap-name`
`### The error occurred while executing a query`
`### SQL: {call name-of-stored-proc(?)}`
`### Cause: com.ibm.db2.jcc.am.SqlException: [jcc][10271][10296][3.58.82] Unrecognized JDBC type: -10. ERRORCODE=-4228, SQLSTATE=null`
`; uncategorized SQLException for SQL []; SQL state [null]; error code [-4228]; [jcc][10271][10296][3.58.82] Unrecognized JDBC type: -10. ERRORCODE=-4228, SQLSTATE=null; nested exception is com.ibm.db2.jcc.am.SqlException: [jcc][10271][10296][3.58.82] Unrecognized JDBC type: -10. ERRORCODE=-4228, SQLSTATE=null`
XML File: `
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="Namespace-name">
<resultMap id="retrieveReports-results" type="Folder-structure-to-Java-file" autoMapping="true">
<result property="name" column="REPORT_NAME"/>
<result property="location" column="REPORT_DIRECTORY"/>
<result property="key" column="REPORT_KEY"/>
<result property="executable" column="EXECUTABLE"/>
<result property="commandLine" column="COMMAND_LINE"/>
<result property="commandLineFormat" column="COMMAND_LINE_FORMAT"/>
</resultMap>
<select id="retrieveReports" resultType="java.util.Map" statementType="CALLABLE">
{call prc_sel_reports(#{reports,jdbcType=CURSOR,javaType=java.sql.ResultSet,mode=OUT,resultMap=retrieveReports-results})}
</select>
</mapper>`
Java code:
try {
List < Report > reports = super.getSqlSession().selectList("retrieveReports");
if(log.isDebugEnabled()){
log.debug("Retrieved " + reports.size() + " reports, in method: retrieveReports()");
}
return reports;
// Attempt to catch different kinds of exceptions.
} catch (Exception e) {
throw new RuntimeException("Exception caught while trying to retrieve reports", e);
}
You have to specify a parameterType in the select statement, either map or custom class. An instance has to be passed on statement invocation.
resultType is not used, then irrelevant.
Procedure actually writes in a field of the "input" parameter passed to mybatis statement, and the statement does not return anything.
Mapper interface would be: void retrieveReports(Map<String, Object> params);
And your call:
Map<String, Object> params = new HashMap<String, Object>();
session.selectList("retrieveReports", params);
List<Report> reports = (List<Report>)params.get("reports");
Param may also be a custom type with property private List<Report> reports;.

Included SQL fragment doesn't substitute parameter

My mapper interface looks like this.
public interface CommonMapper {
long selectSequenceNumber(String sequenceName);
}
And I prepared sql mapper looks like this.
<sql id="sequenceNumber">
<choose>
<when test="_databaseId == 'derby'">
VALUES NEXT VALUE FOR #{sequenceName}
</when>
<otherwise>
SELECT #{sequenceName}.NEXTVAL FROM DUAL
</otherwise>
</choose>
</sql>
<select id="selectSequenceNumber" resultType="_long">
<!--<include refid="....mapper.CommonMapper.sequenceNumber"/>-->
<include refid="sequenceNumber"/>
</select>
When I test mapper #{sequenceName} part is not substituted with given.
14:36:09.492 [main] DEBUG ....selectSequenceNumber - ==> Preparing: VALUES NEXT VALUE FOR ?
14:36:09.724 [main] ERROR ....PersistenceTests - failed to apply function for SqlSession
org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: java.sql.SQLSyntaxErrorException: Syntax error: Encountered "?" at line 1, column 23.
### The error may exist in .../CommonMapper.xml
### The error may involve ....CommonMapper.selectSequenceNumber
### The error occurred while executing a query
### SQL: VALUES NEXT VALUE FOR ?
### Cause: java.sql.SQLSyntaxErrorException: Syntax error: Encountered "?" at line 1, column 23.
Is this normal? How can I fix this?
You need to use string substitution ${sequenceName} instead of setting the parameter with #{} for direct string placement in your queries (such as for giving object names, dynamic sql etc...)
<sql id="sequenceNumber">
<choose>
<when test="_databaseId == 'derby'">
VALUES NEXT VALUE FOR ${sequenceName}
</when>
<otherwise>
SELECT ${sequenceName}.NEXTVAL FROM DUAL
</otherwise>
</choose>
</sql>
<select id="selectSequenceNumber" resultType="_long">
<!--<include refid="....mapper.CommonMapper.sequenceNumber"/>-->
<include refid="sequenceNumber"/>
</select>