Hibernate #SQLInsert insert where not exists Postgres - java

I`m trying to make this work:
#SQLInsert(sql =
"INSERT INTO table" +
"(colum1,colum2,colum3,colum4,colum5)" +
" SELECT ?,?,?,?,?" +
" WHERE" +
" NOT EXISTS (" +
"SELECT id FROM table WHERE " +
"colum1 = ? " +
"AND colum2 = ? " +
"AND colum3 = ? " +
"AND colum4 = ? " +
"AND colum5 = ? " +
")",
check = ResultCheckStyle.COUNT)
But I'm getting exception:
ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.RuntimeException: org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; nested exception is
org.hibernate.exception.DataException: could not execute statement] with root cause
org.postgresql.util.PSQLException: No value specified for parameter 18.
And I'm starting to think that this functionality is impossible to be achieved using the #SQLInsert annotation. Witch is unfortunate because should it work it seems pretty clean approach on the issue.

Related

Spring Boot Mybatis Dynamic query

Hello im pretty new to mybatis and is the first time im trying to use with annotations in spring boot.
My code is something like this :
#Select("<script>"
+ "SELECT t.something, s.somewhat, "
+ "FROM t.table1 t "
+ "LEFT JOIN table2 s ON t.id = s.id "
+ "WHERE s.delete_date IS NULL "
+ "<if test=\"isnew\"> "
+ "AND t.insert_date = t.update_date "
+ "AND (t.score >= s.min_score AND t.score <= s.max_score) "
+ "</if>"
+ "union "
+ "ANOTHER SIMILAR QUERY WITH ANOTHER <IF> + "</script>")
List<Map<String, Object>> methodName(#Param("isnew") Boolean isNew);
This is the error.
Caused by: java.lang.IllegalArgumentException: org.apache.ibatis.builder.BuilderException: Could not find value method on SQL annotation. Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance. Cause: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 822;
Im almost sure there is an error of syntax very predictable but I cant find it.
Here are some examples of what I tried, none of them works:
"<if test="isnew = true">"
"<if test="isnew == true">"
"<if test="isnew != false">"
"<if test="isnew"> "
"<if test=#{isnew}"> "
"<if #{isnew} = true> "
Thanks in advance
For those who may have the same problem this is the solution:
You have to escape the character < , because mybatis takes it as an unopened tag, &lt will work :
+ "SELECT t.something, s.somewhat, "
+ "FROM t.table1 t "
+ "LEFT JOIN table2 s ON t.id = s.id "
+ "WHERE s.delete_date IS NULL "
+ "<if test=\"isnew\"> "
+ "AND t.insert_date = t.update_date "
+ "AND (t.score >= s.min_score AND t.score lt;= s.max_score) "
+ "</if>"
+ "union "
+ "ANOTHER SIMILAR QUERY WITH ANOTHER <IF> + "</script>")
List<Map<String, Object>> methodName(#Param("isnew") Boolean isNew);```

Getting Error : SQLErrorCodes loaded: Spring jdbc connection

I am getting below error when I am trying to insert row in database and also while calling prepared statement:
INFO XmlBeanDefinitionReader:315 - Loading XML bean definitions from class path resource [org/springframework/jdbc/support/sql-error-codes.xml]
07:05:53,727 INFO SQLErrorCodesFactory:126 - SQLErrorCodes loaded: [DB2, Derby, H2, HSQL, Informix, MS-SQL, MySQL, Oracle, PostgreSQL, Sybase]
Also below is insert statement:
String sql = " INSERT INTO customer_Table (customer_no ,customer_name ,address_no ,phone_no"
+ " ,email_addr ,customer_type_code ,city_code ,language_code ,input_user_id ,input_timestamp ,last_update_user_id ,last_update_timestamp"
+ ") VALUES ( '"
+ customerNumber2
+ "' ,UPPER('"
+ getTrimmedString(customerName,300)
+ "') , '"
+ addSeqNum2
+ "'"
+ ",'"
+ processForNull(getTrimmedString(helperObject.getData().getVisitPhone(),30))
+ "','"
+ processForNull(getTrimmedString(helperObject.getData()
.getVisitEmailAddress(),256))
+ "','001','"
+ helperObject.getCityCode()
+ "', 'en','SYSTEM',SYSDATE+-1/24,'SYSTEM',SYSDATE+-1/21)";
jdbcTemplate.update(sql);
Because of this error code is not executing completely. I am also not getting full stack of error.
Can anyone help me please.
Length of background parameter, exceeding the length defined by the field in the database
The data type of descendant parameters conflicts with the data type of the field in the database

Hibernate Data Exception in T-SQL query (Java Web application)

I have problem with executing the following T-SQL script in Java application using hibernate sessionFactory, however, this SQL code works when I run it in PostgreSQL:
...
query = session.createSQLQuery(
"; CREATE TEMP TABLE deathuntil1 AS "+
" SELECT id, jamoatorgunit, organisationunitid "+
" , REGEXP_REPLACE( "+
" COALESCE( "+
" substring( "+
" CAST(age(deathdate,birthdate) AS character varying ) "+
" from 1 for "+
" CASE WHEN (position('years' in CAST(age(deathdate,birthdate) AS character varying ))-1)>0 THEN position('years' in CAST(age(deathdate,birthdate) AS character varying ))-1 ELSE 0 END "+
" ) "+
" , '0'), '[^0-9]*' ,'0')::integer AS years "+
" FROM public.cro_death "+
" WHERE "+
" length(firstname)>= 3 "+
";"
);
query.executeUpdate();
the following is the error from Eclipse console:
* ERROR 2016-08-16 11:36:18,753 No value specified for parameter 1. (SqlExceptionHelper.java [qtp1843774775-20])
* ERROR 2016-08-16 11:36:18,760 Error while executing action (ExceptionInterceptor.java [qtp1843774775-20])
org.hibernate.exception.DataException: could not execute statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:135)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:124)
Caused by: org.postgresql.util.PSQLException: No value specified for parameter 1.
at org.postgresql.core.v3.SimpleParameterList.checkAllParametersSet(SimpleParameterList.java:225)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:190)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:424)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:161)
at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:133)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:105)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:186)
... 124 more
When running this sql through java, there is a "misunderstanding" of :: casting.
Please replace '[^0-9]*' ,'0')::integer with '[^0-9]*' ,'0')\\:\\:integer and it should work.

create a function via nativeQuery

I'm trying to insert a function on database via native query, like this
EntityManagerImpl entityManagerFunctionConta = (EntityManagerImpl) GermantechEntityManager.getEntityManager();
EntityTransaction transactionFunctionConta = entityManagerFunctionConta.getTransaction();
String functionConta = "CREATE OR REPLACE FUNCTION saldo_anterior_conta(dt_inicial date, id_conta bigint, id_empresa bigint) " +
"RETURNS numeric AS " +
"$BODY$ " +
"declare " +
"saldo_anterior numeric(14,2);" +
"begin " +
"select coalesce(sum(valor), 0) into saldo_anterior " +
"from saldoinicialconta " +
"where data < dt_inicial and empresa_id = id_empresa and conta_id = id_conta; " +
"return saldo_anterior;" +
"end;" +
"$BODY$ " +
"LANGUAGE plpgsql VOLATILE COST 100;" +
"ALTER FUNCTION saldo_anterior_movimentacao(date, bigint, bigint) OWNER TO postgres;";
transactionFunctionConta.begin();
entityManagerFunctionConta.createNativeQuery(functionConta).executeUpdate();
transactionFunctionConta.commit();
but the following exception is thrown
Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.4.1.v20121003-ad44345): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.BatchUpdateException: Entrada em lote 1 <unknown> foi abortada. Chame getNextException para ver a causa.
Error Code: 0
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:324)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeJDK12BatchStatement(DatabaseAccessor.java:882)
at org.eclipse.persistence.internal.databaseaccess.DynamicSQLBatchWritingMechanism.executeBatchedStatements(DynamicSQLBatchWritingMechanism.java:144)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.writesCompleted(DatabaseAccessor.java:1714)
is there something wrong with the function? can we run a command like this via nativeQuery?

while executing this sql statement in java i m getting this error

this is my sql statement in java.
//validating for employee no exits in database or not
String importTable = getConfig().getImportTable();
String sql = "update "
+ importTable
+ " set errMsg = case when errMsg is null or errMsg ='' then '' else errMsg + '<br>' end "
+ "+ 'Employeeno doesn't exists in the database.(' + employeeno + ')' "
+ " where employeeno is not null and not exists (select * from uae_empinfo where employee = "
+ importTable + ".cid)";
executeCommand(sql);
this is the error:-
org.springframework.dao.DataIntegrityViolationException: StatementCallback; SQL []; Invalid SQL statement or JDBC escape, terminating ''' not found.; nested exception is java.sql.SQLException: Invalid SQL statement or JDBC escape, terminating ''' not found.
Your problem is that you have an embedded single quote here:
+ "+ 'Employeeno doesn't exists in the database.(' + employeeno + ')' "
// -------------------^
So you end up with unbalanced single quotes and invalid SQL. You need to properly escape your text before trying to turn it into SQL.
You need to use PreparedStatement, instead.

Categories

Resources