how to write native query in jpa - jpa

I am getting the following error when I press the search button:
An Error Occurred:
Exception [EclipseLink-4002] (Eclipse Persistence Services -
2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException Internal
Exception: java.sql.SQLException: Missing IN or OUT parameter at
index:: 1 Error Code: 17041 Call: SELECT * FROM CRM_DAILY_SHEET WHERE
to_char(reported_on,'dd-MM-yy') = :reportedOn Query:
ReadAllQuery(referenceClass=CrmDailySheet sql="SELECT * FROM
CRM_DAILY_SHEET WHERE to_char(reported_on,'dd-MM-yy') = :reportedOn")
Code:
public List < CrmDailySheet > searchres() throws Exception {
SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("dd/MM/yy");
Date d1 = searchsht.getReportedOn();
String date_to_string = ddMMMyyFormat.format(d1);
return crmsrvc.searchDailysht(date_to_string);
}
try {
Query query = em.createNativeQuery("SELECT * FROM CRM_DAILY_SHEET
WHERE to_char (reported_on,'dd-MM-yy') = :reportedOn", CrmDailySheet.class);
query.setParameter("reportedOn", reportedOn);
List < CrmDailySheet > res = query.getResultList();
return res;
} finally {
em.close();
}
Can anyone find the solution please?

You are trying to use the JPQL parameter syntax (the ":reportedOn") with a native query. Try using ? instead and set the parameter value by position, e.g.:
Query query = em.createNativeQuery("SELECT * FROM CRM_DAILY_SHEET
WHERE to_char (reported_on,'dd-MM-yy') = ?", CrmDailySheet.class);
query.setParameter(1, reportedOn);

Related

Dblink is not working in java

String id="";
List list = null;
Query query = null;
Session session = getSession();
String sql = "select id from student#dblink s, location#dblink l where s.id in (select name from Employ where id='" +Id +"') and s.country_id = l.country_id and l.country_end = '"+countryEnd+"'";
query = session.createSQLQuery(sql);
System.out.println("sql.1."+sql);
list = query.list();
if(list.size()>0)
id = list.get(0).toString();
else
id= "0";
System.out.println("Stage2Ubr Id is:"+id);
return id;
Here I got exception like "org.hibernate.exception.GenericJDBCException: could not execute query". Sometimes this exception is not coming. Sometimes it's working fine without exception. This exception won't come if dblink is working fine.Please help me. How to check wheather the dblink is working fine or not?

Eclipselink ScrollableCursor fails on second next() call

I am trying to use ScrollableCursor for loading all users of the system to memory.
I have a code like this:
Query findUsersQuery
= entityManager.createNamedQuery(UserEntity.QUERY_ALL_USERS, UserEntity.class);
findUsersQuery.setHint(QueryHints.SCROLLABLE_CURSOR, Boolean.TRUE);
findUsersQuery.setHint(QueryHints.CURSOR_PAGE_SIZE, bulkSize);
findUsersQuery.setMaxResults(maxInitialCacheSize);
ScrollableCursor scrollableCursor = (ScrollableCursor) findUsersQuery.getSingleResult();
int leftSize = scrollableCursor.size();
while (scrollableCursor.hasNext()) {
int nextSize = leftSize > bulkSize ? bulkSize : leftSize;
List subscriberPrefs = scrollableCursor.next(nextSize);
leftSize -= nextSize;
//... Result list processing
}
The query is: SELECT s FROM UserEntity u order by u.userId
Size of result table is 100, when scrollableCursor.next(nextSize); called, i get following exception:
org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLRecoverableException: Closed Resultset
Error Code: 17010
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:324)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.cursorRetrieveNextRow(DatabaseAccessor.java:447)[215:org.eclipse.persistence.core:2.4.1.v20121003-ad44345]
at org.eclipse.persistence.queries.ScrollableCursor.retrieveNextObject(ScrollableCursor.java:563)[215:org.eclipse.persistence.core:2.4.1.v20121003-ad44345]
at org.eclipse.persistence.queries.ScrollableCursor.loadNext(ScrollableCursor.java:411)[215:org.eclipse.persistence.core:2.4.1.v20121003-ad44345]
at org.eclipse.persistence.queries.ScrollableCursor.next(ScrollableCursor.java:437)[215:org.eclipse.persistence.core:2.4.1.v20121003-ad44345]
at org.eclipse.persistence.queries.ScrollableCursor.next(ScrollableCursor.java:459)[215:org.eclipse.persistence.core:2.4.1.v20121003-ad44345]
While calling next(10) the first row loaded normally and the exceptions occurs on second row. I don't have an idea why. Can anybody say how i can avoid this error?

Mybatis error : The error occurred while setting parameters

org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: java.lang.UnsupportedOperationException
### The error may exist in kr/co/techinmotion/mybatis/mappers/dataOutputMapper.xml
### The error may involve kr.co.techinmotion.mybatis.mappers.dataOutputMapper.selectData1-Inline
### The error occurred while setting parameters
### SQL: select * from tbl_id, tbl_feed where tbl_id.id = tbl_feed.upid and tbl_id.token = ?
### Cause: java.lang.UnsupportedOperationException
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:23)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:107)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:98)
at kr.co.techinmotion.daoImpl.DataDaoImplMybatis.selectData1(DataDaoImplMybatis.java:47)
I don't know why this error occurred.
This is my sql in mapper.
<select id="selectData1" parameterType="string" resultType="list">
select * from tbl_id, tbl_feed
where tbl_id.id = tbl_feed.upid
and tbl_id.token = #{token}
</select>
and.. this is DAO.
public class DataDaoImplMybatis implements IdataDao {
private DataDaoImplMybatis(){}
private static DataDaoImplMybatis dao;
public static DataDaoImplMybatis getInstance(){
if(dao == null){
dao = new DataDaoImplMybatis();
}
return dao;
}
SqlSessionFactory sessionFactory = SqlMapSessionFactory.getSqlSessionFactory();
#Override
public List<DataResult1> selectData1(String token){
SqlSession session = sessionFactory.openSession();
List<DataResult1> list = session.selectList("kr.co.techinmotion.mybatis.mappers.dataOutputMapper.selectData1", token);
session.close();
return list;
}
}
please help me.. T_T
The "MyBatis-3-User-Guide" says:
resultType: The fully qualified class name or alias for the expected type that will be returned from this statement. Note that in the case of collections, this should be the type that the collection contains, not the type of the collection itself. Use resultType OR resultMap, not both.
In my case was that added 'useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true' in jdbc.url, that solved my issue:)
jdbc.url=jdbc:mysql://127.0.0.1:3306/xxx?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
The resultType SHOULD NOT be list, the below shows the revised type, but you have to make sure the select statement can map to DataResult1 accordingly
<select id="selectData1" parameterType="string" resultType="DataResult1">
select * from tbl_id, tbl_feed
where tbl_id.id = tbl_feed.upid
and tbl_id.token = #{token}
</select>
alternatively, you may try this:
<select id="selectData1" parameterType="string" resultType="map">
select * from tbl_id, tbl_feed
where tbl_id.id = tbl_feed.upid
and tbl_id.token = #{token}
</select>
and the changes to the java source code
List<Map<String,Object> list = session.selectList("kr.co.techinmotion.mybatis.mappers.dataOutputMapper.selectData1", token);
1 floor is right, but I want to say resultType = "" respect a row in your database but not all, perhaps you may select count(user_id) from user, now your resultType = 'long', if you select more than two results, you may use resultType = 'map' or yourself map, resultType = 'yourselfMap'
You have to declare the "jdbcType=VARCHAR" or "jdbcType=NUMERIC" of the variable depending upon the type of variable passed in order to pass the null value. Try using this:
<select id="selectData1" parameterType="string" resultType="map">
select * from tbl_id, tbl_feed
where tbl_id.id = tbl_feed.upid
and tbl_id.token = #{token,jdbcType=VARCHAR}
</select>

Using DB2, "statement.executeQuery()" throws SqlEception only in my system

//Class UserProfileDBUtil.java
Connection conn = null;
PreparedStatement statment = null;
ResultSet rs = null;
try{
String sqlString = "select count(*) from "+AGENCY_SCHEMA_NAME+".AGENCY WHERE AGENCYCODE= ? and ENABLEDFLAG = ?";
conn = JDBCUtils.getConnection(JDBCUtils.WP_ODS);
statment = conn.prepareStatement(sqlString);
statment.setString(1, agencyCode.toUpperCase());
statment.setString(2, "Y");
rs =statment.executeQuery(); // SQL Error Line 42
while(rs.next())
{
if(rs.getInt(1) > 0 )
{
return true;
}
}
log.error("Agency for agency code "+agencyCode+" is not available or not active");
}
LOG :
com.ibm.db2.jcc.b.SqlException: DB2 SQL error: SQLCODE: -401, SQLSTATE: 42818, SQLERRMC: =
at com.ibm.db2.jcc.b.sf.e(sf.java:1680)
at com.ibm.db2.jcc.b.sf.a(sf.java:1239)
at com.ibm.db2.jcc.c.jb.h(jb.java:139)
at com.ibm.db2.jcc.c.jb.a(jb.java:43)
at com.ibm.db2.jcc.c.w.a(w.java:30)
at com.ibm.db2.jcc.c.cc.g(cc.java:161)
at com.ibm.db2.jcc.b.sf.n(sf.java:1219)
at com.ibm.db2.jcc.b.tf.gb(tf.java:1818)
at com.ibm.db2.jcc.b.tf.d(tf.java:2294)
at com.ibm.db2.jcc.b.tf.X(tf.java:508)
at com.ibm.db2.jcc.b.tf.executeQuery(tf.java:491)
at com.ibm.ws.rsadapter.jdbc.WSJdbcPreparedStatement.executeQuery(WSJdbcPreparedStatement.java:559)
at UserProfileDBUtil.isAgencyActive(UserProfileDBUtil.java:42)
The error you're getting is a -401, which means:
The data types of the operands for the operation operator are not
compatible or comparable.
I would check and make sure that the parameters you're passing in are using the right data types. If you catch the exception, you should be able to use the exceptions Message property to see what the operator is. See here for an example.

Postgresql query for this situation?

I am using the following statement
select *
from table
where column1 in(groups)
Where "groups" is a String array of size n.
If i use it as it is, It wont get executed so can anyone suggest exact query to perform this?
EDIT 1
If I use the following code
try{
System.out.println("before execute query");
ps1.setArray(1,conn.createArrayOf("text",gs));
ps1.setArray(2,conn.createArrayOf("text",gs));
System.out.println("after execute query");
}
catch(Exception e)
{
System.out.println("hrer----"+e);
}
First,It prints "before execute query" and then it gives the following exception
javax.servlet.ServletException:servlet execution threw an exception
*NOTE : * It does not print "hrer-----" in catch(Exception e) block
This should work:
PreparedStatement stmt = conn.prepareStatement(
"SELECT * FROM users WHERE username = any(?)");
String[] usernames = {"admin", "guest"};
stmt.setArray(1, conn.createArrayOf("varchar", usernames));
Credit goes to Boris's answer at https://stackoverflow.com/a/10240302
select * from table where column1 in (?, ?)
except that you have n question marks.
StringBuilder q = new StringBuilder("select * from table where column1 in (");
for(int i=0; i<groups.length; i++) {
q.append("?");
if(i != groups.length - 1) {
q.append(",");
}
}
q.append(")");
PreparedStatement query = con.prepareStatement(q.toString());
for(int i=1; i<=groups.length; i++) {
query.setString(i, groups[i-1]);
}
ResultSet rs = query.getResultSet();