Hibernate native SQL error - oracle

I am trying to execute sql native query using hibernate 3.3.2.GA.
I have following query.
session.createSQLQuery("SELECT {dept1.*}, {dept2.*} FROM Dept d1, Dept d2 WHERE d1.deptId = d2.deptId").
addEntity("dept1",com.test.pojo.Dept.class).
addEntity("dept2",com.test.pojo.Dept.class).
list();
Mapping file for Dept class is
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.test.pojo.Dept">
<id column="deptId" name="deptId" type="long">
<generator class="native"/>
</id>
<version name="version" access="field" column="version"></version>
<property name="deptName" type="string" column="deptName"/>
<set name="emps" cascade="all" inverse="true">
<key column="deptId"></key>
<one-to-many class="com.test.pojo.Emp"/>
</set>
</class>
</hibernate-mapping>
But why I get following error? It is converting my query to
SELECT dept1.**deptId as deptId1_0_, **dept1.**version as
version1_0_, **dept1.**deptName as deptName1_0_, **dept2.**deptId as
deptId1_1_, **dept2.**version as version1_1_, **dept2.**deptName as
deptName1_1_ **FROM Dept d1, Dept d2 WHERE d1.deptId = d2.deptId.
Hibernate: SELECT dept1.deptId as deptId1_0_, dept1.version as
version1_0_, dept1.deptName as deptName1_0_, dept2.deptId as
deptId1_1_, dept2.version as version1_1_, dept2.deptName as
deptName1_1_ FROM Dept d1, Dept d2 WHERE d1.deptId = d2.deptId
20:43:41,109 WARN JDBCExceptionReporter:100 - SQL Error: 904,
SQLState: 42000 20:43:41,109 ERROR JDBCExceptionReporter:101 -
ORA-00904: "DEPT2"."DEPTNAME": invalid identifier
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not execute query
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:90)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.loader.Loader.doList(Loader.java:2235)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2129)
at org.hibernate.loader.Loader.list(Loader.java:2124)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:312)
at org.hibernate.impl.SessionImpl.listCustomQuery(SessionImpl.java:1723)
at org.hibernate.impl.AbstractSessionImpl.list(AbstractSessionImpl.java:165)
at org.hibernate.impl.SQLQueryImpl.list(SQLQueryImpl.java:175)
at com.test.test.Test1.main(Test1.java:96)
Caused by: java.sql.SQLException: ORA-00904: "DEPT2"."DEPTNAME": invalid identifier
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:289)
at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:590)
at oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1973)
at oracle.jdbc.ttc7.TTC7Protocol.parseExecuteDescribe(TTC7Protocol.java:850)
at oracle.jdbc.driver.OracleStatement.doExecuteQuery(OracleStatement.java:2599)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:2963)
at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:658)
at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:584)
at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1812)
at org.hibernate.loader.Loader.doQuery(Loader.java:697)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259)
at org.hibernate.loader.Loader.doList(Loader.java:2232)
... 7 more

It should be
session.createSQLQuery(
"SELECT {dept1.*}, {dept2.*} FROM Dept dept1, Dept dept2 WHERE dept1.deptId = dept2.deptId")
.addEntity("dept1",com.test.pojo.Dept.class)
.addEntity("dept2",com.test.pojo.Dept.class)
.list();
If you was misled by the documentation (18.1.4. Returning multiple entities), there is a bug there (HHH-2976), feel free to vote for it.

Try Google with the ORA-XXX codes. From http://www.dba-oracle.com/t_ora_00904_string_invalid_identifier.htm
Question: I am running a SQL
statement and I get a SQL*Plus error
ORA-00904 invalid identifier.
Answer: When ORA-00904 occurs, you
must enter a valid column name as it
is either missing or the one entered
is invalid. The "invalid identifier"
most common happens when you are
referencing an invalid alias in a
select statement. The Oracle docs
note this on the ORA-00904 error:

Related

Oracle error in MyBatis XML Mapper file, but not in SQL Developer

I have a query in a MyBatis XML wrapper that results in a ORA-00904 invalid identifier. However, when I copy the statement shown in the log it runs.
The log message is
SQL: select /*+ parallel(AUTO) */ avg(DURATION) AVERAGE_SESSION_DURATION
from sc_report_new.sc_hub_session_activity schsa
inner join sc_hub_users schu on schsa.user_key=schu.user_key
inner join sc_hub_user_types schut on chut.user_type_id=schu.user_type_id
inner join sc_hub_content_master schcm on chcm.trace_id_key=schsa.hub_key
WHERE schsa.FISCAL_QUARTER_ID = '2020Q2'
Cause: java.sql.SQLSyntaxErrorException: ORA-00904: "SCHSA"."FISCAL_QUARTER_ID": invalid identifier
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:149)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:140)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:76)
The snippet of the mapper query is
<select id="getDashboardAverageSessionDuration"
resultType="int"
parameterType="com.mycompany.salesconnect.screport.model.AuthorizedHubRequest">
select /*+ parallel(AUTO) */
avg(DURATION) AVERAGE_SESSION_DURATION
from sc_report_new.sc_hub_session_activity schsa
inner join sc_hub_users schu
on schsa.user_key=schu.user_key
inner join sc_hub_user_types schut
on schut.user_type_id=schu.user_type_id
inner join sc_hub_content_master schcm
on schcm.trace_id_key=schsa.hub_key
<include refid="com.mycompany.salesconnect.screport.mapper.hubportfolio.Common.joinHubAuthorizations">
<property name="hubAuthorizations" value="hubAuthorizations"/>
</include>
<where>
<if test="hubRequestFilter.dateRangeSpecified">
schsa.time_stamp
BETWEEN to_date(#{hubRequestFilter.fromDate}, 'mm/dd/yyyy')
AND
to_date(#{hubRequestFilter.toDate}, 'mm/dd/yyyy')
</if>
<if test="!hubRequestFilter.dateRangeSpecified">
<if test="hubRequestFilter.quarterListByNameNotEmpty">
SCHSA.FISCAL_QUARTER_ID IN
<foreach item="quarterName" collection="hubRequestFilter.quarterListByName" open="(" close=")" separator=",">
<bind name="quarterId"
value="#com.mycompany.salesconnect.screport.dao.SCHubPortfolioUtil#getQuarterAsId(quarterName)"/>
#{quarterName}
</foreach>
</if>
<if test="hubRequestFilter.quarterListByIdNotEmpty">
SCHSA.FISCAL_QUARTER_ID IN
<foreach item="quarterId" collection="hubRequestFilter.quarterListById" open="(" close=")" separator=",">
#{quarterId}
</foreach>
</if>
</if>
<include refid="com.mycompany.salesconnect.screport.mapper.hubportfolio.Common.whereHubRequestFilter"><property name="hubRequestFilter" value="hubRequestFilter"></property></include>
<include refid="com.mycompany.salesconnect.screport.mapper.hubportfolio.Common.whereHubAuthorizations"><property name="hubAuthorizations" value="hubAuthorizations"></property></include>
</where>
</select>
I looked for non-printable characters in the XML and didn't see any. Stating what should be obvious, the SC_HUB_SESSION_ACTIVITY table has a FISCAL_QUARTER_ID field. Interestingly, if I choose another SCHSA column, it works. For some reason the system singles out this field for arbitrarily not working.
This was not an issue with MyBatis but rather not pointing to the same database as the SQL Developer that I was using.

Trouble when using expression IN

Use: db: HSQLDB, jdbctemplate.
I created tables:
<SELECTED_DATE ID="1" DATE_VALUE="2018-02-02 00:00:00.000000"/>
<SELECTED_DATE ID="2" DATE_VALUE="2018-02-03 00:00:00.000000"/>
<SELECTED_DATE ID="3" DATE_VALUE="2018-02-04 00:00:00.000000"/>
<SELECTED_DATE ID="4" DATE_VALUE="2018-02-05 00:00:00.000000"/>
<SELECTED_DATE ID="5" DATE_VALUE="2018-02-07 00:00:00.000000"/>
<SELECTED_DATE ID="6" DATE_VALUE="2018-02-08 00:00:00.000000"/>
How to use select * from SELECTED_DATE where DATE_VALUE in ( '2018-02-08', ... );
this causes an error: java.sql.SQLSyntaxErrorException: data type of expression is not boolean
or select * from SELECTED_DATE where DATE_VALUE IN ELEMENTS('2018-02-08', ...);
this causes an error: java.sql.SQLSyntaxErrorException: unexpected token: ELEMENTS required: (
but such select * from SELECTED_DATE where DATE_VALUE = ( '2018-02-08'); its work
Your date column is in fact a TIMESTAMP column.
For IN predicates, you need to declare the type of the values:
select * from SELECTED_DATE where DATE_VALUE in ( DATE'2018-02-02', DATE'2018-02-03');
The above works. If your SELECT statement does not still work, please report the complete statement.

NamedParameterJdbcTemplate batchUpdate not working for merge

I am running the below merge query using NamedParameterJdbcTemplate batchUpdate.
The batchUpdate(String sql, SqlParameterSource[] batchArgs) works for batchArgs with 1 item and does not work for multiple items. Below is the query and I renamed table column names.
The NamedParameterJdbcTemplate.batchUpdate works if run for each array item seperately or if run as NamedParameterJdbcTemplate .update()
Sql Query:
MERGE INTO tableName C1 USING (VALUES (:f1)) AS C2(Field1)
ON (C1.CMP = C2.CO_C)
WHEN MATCHED THEN
UPDATE SET Field2 = :date1, Field3 = :time1, Field4 =:userId
WHEN NOT MATCHED THEN
INSERT (Field5, Field1, Field4, Field2, Field3) VALUES (:offCC, :f1,:userId, :date1, :time1)
[err] SQL exception:
[err] Message: [jcc][t4][102][10040][4.22.29] Batch failure. The batch was submitted, but at least one exception occurred on an individual member of the batch. Use getNextException() to retrieve the exceptions for specific batched elements. ERRORCODE=-4229, SQLSTATE=null
[err] SQLSTATE: null
[err] Error code: -4229
[err] SQL exception:
[err] Message: VARIABLE IS NOT DEFINED OR NOT USABLE.
SQLCODE=-312, SQLSTATE=42618, DRIVER=4.22.29
[err] SQLSTATE: 42618
[err] Error code: -312
[err] SQL exception:
[err] Message: Error for batch element #1: VARIABLE IS NOT DEFINED OR NOT USABLE
[err] SQLSTATE: 42618
[err] Error code: -312

Want to extract the a text from a tag

I have a column in a table where the data is stored in below format
<Server start>
<message tagid=" ">false</message>
<message tagid="34">no data found</message>
<message tagid=" ">false</message>
<Server stop>
Where I need to extract "no data found". Tried using regexp replace function but couldnot make it in a proper way.
Note: message tag id (number) can be of any length.
Query:
SELECT x.tagid,
x.message
FROM your_table t
CROSS JOIN
XMLTable(
'/Server/message'
PASSING XMLType(
REPLACE(
REPLACE( t.your_column, '<Server start>', '<Server>' ),
'<Server stop>',
'</Server>'
)
)
COLUMNS tagid VARCHAR2(100) PATH './#tagid',
message VARCHAR2(400) PATH './text()'
) x;
Output
TAGID MESSAGE
----- -------
false
34 no data found
false
If you just want the values where the message is no data found then add a WHERE clause at the end of the query:
WHERE x.message = 'no data found';
Try to build your query based on the following code. First converting your text to XML, then extract neccesary data by using XMLType.extract() function
with test_query as (select XMLType(replace(replace(s,'<Server stop>','</Server>'),'<Server start>','<Server>')) xml from
(select '<Server start>
<message tagid=" ">false</message>
<message tagid="34">no data found</message>
<message tagid=" ">false</message>
<Server stop>' as s from dual))
select
t.xml.extract('//message[position()=2]/text()') out
from test_query t;

Mybatis BindingException Parameter '__frch_e_0' not found

I'm trying to insert a list to Mybatis and getting the foloowing error:
org.apache.ibatis.binding.BindingException: Parameter '__frch_e_0' not found. Available parameters are [list]
Can you please let know what I'm missing. Thanks
DAO interface:
void saveErrorMessageList(List<ErrorMessage> emList);
XML:
<insert id="saveErrorMessageList" parameterType="java.util.List">
{call
declare
ID PLS_INTEGER;
begin
<foreach collection="list" item="e" index="index" >
SELECT SEQ_ERR_ID.NEXTVAL into ID FROM DUAL;
INSERT INTO ERR (ERR_ID, CREAT_TS,
MSG_CD, MSG_TXT) values (ID,CURRENT_TIMESTAMP,
#{e.code}, #{e.message});
</foreach>
end
}
</insert>
Error Message:
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter '__frch_e_0' not found. Available parameters are [list]
at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:75)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:371)
at com.sun.proxy.$Proxy11.insert(Unknown Source)
at org.mybatis.spring.SqlSessionTemplate.insert(SqlSessionTemplate.java:240)
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:51)
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:52)
at com.sun.proxy.$Proxy12.saveBeneErrorMessageList(Unknown Source)
at ...
... 35 more
check column name and bean field name in sql
try to update mybatis version. when i use 3.3.0 have this error, but use 3.4.1 it is ok
Please check foreach tag for collection attribute. I feel value should be "emList" or add #Param (org.apache.ibatis.annotations.Param) in interface method.
<foreach collection="emList" item="e" index="index" >
INSERT INTO ERR (ERR_ID, CREAT_TS,
MSG_CD, MSG_TXT) values (CURRENT_TIMESTAMP,
#{e.code}, #{e.message});
</foreach>
</insert>

Resources