Mybatis error : The error occurred while setting parameters - mybatis

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>

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?

Custom procedure fails to collect properties of a class parameter; why?

OK, first of all, I'm a rookie with Caché, so the code will probably be poor, but...
I need to be able to query the Caché database in Java in order to rebuild source files out of the Studio.
I can dump methods etc without trouble, however there is one thing which escapes me... For some reason, I cannot dump the properties of parameter EXTENTQUERYSPEC from class Samples.Person (namespace: SAMPLES).
The class reads like this in Studio:
Class Sample.Person Extends (%Persistent, %Populate, %XML.Adaptor)
{
Parameter EXTENTQUERYSPEC = "Name,SSN,Home.City,Home.State";
// etc etc
}
Here is the code of the procedure:
CREATE PROCEDURE CacheQc.getParamDesc(
IN className VARCHAR(50),
IN methodName VARCHAR(50),
OUT description VARCHAR(8192),
OUT type VARCHAR(50),
OUT defaultValue VARCHAR(1024)
) RETURNS NUMBER LANGUAGE COS {
set ref = className _ "||" _ methodName
set row = ##class(%Dictionary.ParameterDefinition).%OpenId(ref)
if (row = "") {
quit 1
}
set description = row.Description
set type = row.Type
set defaultValue = row.Default
quit 0
}
And the Java code:
private void getParamDetail(final String className, final String paramName)
throws SQLException
{
final String call
= "{ ? = call CacheQc.getParamDesc(?, ?, ?, ?, ?) }";
try (
final CallableStatement statement = connection.prepareCall(call);
) {
statement.registerOutParameter(1, Types.INTEGER);
statement.setString(2, className);
statement.setString(3, paramName);
statement.registerOutParameter(4, Types.VARCHAR);
statement.registerOutParameter(5, Types.VARCHAR);
statement.registerOutParameter(6, Types.VARCHAR);
statement.executeUpdate();
final int ret = statement.getInt(1);
// HERE
if (ret != 0)
throw new SQLException("failed to read parameter");
System.out.println(" description: " + statement.getString(4));
System.out.println(" type : " + statement.getString(5));
System.out.println(" default : " + statement.getString(6));
}
}
Now, for the aforementioned class/parameter pair the condition marked // HERE is always triggered and therefore the exception thrown... If I comment the whole line then I see that all three of OUT parameters are null, even defaultValue!
I'd have expected the latter to have the value mentioned in Studio...
So, why does this happen? Is my procedure broken somewhat?
In first you should check that you send right value for className and paramName, full name and in right case and. Why you choose storage procedures, when you can use select? And you can call your procedure in System Management Portal to see about probable errors.
select description, type,_Default "Default" from %Dictionary.ParameterDefinition where id='Sample.Person||EXTENTQUERYSPEC'
Your example, works well for me.
package javaapplication3;
import com.intersys.jdbc.CacheDataSource;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
public class JavaApplication3 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws SQLException {
CacheDataSource ds = new CacheDataSource();
ds.setURL("jdbc:Cache://127.0.0.1:56775/Samples");
ds.setUser("_system");
ds.setPassword("SYS");
Connection dbconnection = ds.getConnection();
String call = "{ ? = call CacheQc.getParamDesc(?, ?, ?, ?, ?)}";
CallableStatement statement = dbconnection.prepareCall(call);
statement.registerOutParameter(1, Types.INTEGER);
statement.setString(2, "Sample.Person");
statement.setString(3, "EXTENTQUERYSPEC");
statement.registerOutParameter(4, Types.VARCHAR);
statement.registerOutParameter(5, Types.VARCHAR);
statement.registerOutParameter(6, Types.VARCHAR);
statement.executeUpdate();
int ret = statement.getInt(1);
System.out.println("ret = " + ret);
System.out.println(" description: " + statement.getString(4));
System.out.println(" type : " + statement.getString(5));
System.out.println(" default : " + statement.getString(6));
}
}
end result
ret = 0
description: null
type : null
default : Name,SSN,Home.City,Home.State
UPD:
try to change code of your procedure and add some debug like here
Class CacheQc.procgetParamDesc Extends %Library.RegisteredObject [ ClassType = "", DdlAllowed, Owner = {UnknownUser}, Not ProcedureBlock ]
{
ClassMethod getParamDesc(className As %Library.String(MAXLEN=50), methodName As %Library.String(MAXLEN=50), Output description As %Library.String(MAXLEN=8192), Output type As %Library.String(MAXLEN=50), Output defaultValue As %Library.String(MAXLEN=1024)) As %Library.Numeric(SCALE=0) [ SqlName = getParamDesc, SqlProc ]
{
set ref = className _ "||" _ methodName
set row = ##class(%Dictionary.ParameterDefinition).%OpenId(ref)
set ^debug($i(^debug))=$lb(ref,row,$system.Status.GetErrorText($g(%objlasterror)))
if (row = "") {
quit 1
}
set description = row.Description
set type = row.Type
set defaultValue = row.Default
quit 0
}
}
and after some test from java, check zw ^debug
SAMPLES>zw ^debug
^debug=4
^debug(3)=$lb("Sample.Person||EXTENTQUERYSPEC","31#%Dictionary.ParameterDefinition","ERROR #00: (no error description)")
Well, uh, I found the problem... Talk about stupid.
It happens that I had the Samples.Person class open in Studio and had made a "modification" to it; and deleted it just afterwards. Therefore the file was "as new"...
But the procedure doesn't seem to agree with this statement.
I closed the Studio where that file was, selected not to modify the "changes", reran the procedure again, and it worked...
Strangely enough, the SQL query worked even with my "fake modification". I guess it's a matter of some cache problem...

how to write native query in 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);

How do i convert this multiple where cause SQL to eSQL?

T-SQL
USE [AdventureWorks];
SELECT p.* FROM Production.ProductCategory cat ,[Production].[ProductSubcategory] sub, [Production].[Product] p
WHERE cat.ProductCategoryID=1 AND sub.ProductCategoryID = cat.ProductCategoryID and p.ProductSubcategoryID = sub.ProductSubcategoryID
And i want to convert to eSQL for EntityDatasource
<asp:EntityDataSource ID="ProductDataSource" runat="server" ConnectionString="name=AdventureWorksEntities"
DefaultContainerName="AdventureWorksEntities" EntitySetName="Product"
Where="EXISTS(SELECT VALUE cat FROM ProductCategory AS cat WHERE cat.ProductCategoryID=1)
AND EXISTS(SELECT VALUE sub FROM ProductSubcategory AS sub WHERE sub.ProductCategoryID = cat.ProductCategoryID)
AND it.ProductSubcategoryID = sub.ProductSubcategoryID) "
>
</asp:EntityDataSource>
But it is error.
Update :
Thanks devart hints,
I modify the query to
SELECT VALUE p FROM AdventureWorksEntities.ProductCategory AS cat, AdventureWorksEntities.ProductSubcategory AS sub, AdventureWorksEntities.Product AS p WHERE cat.ProductCategoryID=1 AND sub.ProductCategoryID = cat.ProductCategoryID and p.ProductSubcategoryID = sub.ProductSubcategoryID
It work now.
You can use the following code for the Selecting EntityDataSource event handler, for example:
string query = #"SELECT VALUE p FROM EntityContainer.ProductCategory as cat, EntityContainer.ProductSubcategory as sub, EntityContainer.Product as p WHERE cat.ProductCategoryID=1 AND sub.ProductCategoryID = cat.ProductCategoryID and p.ProductSubcategoryID = sub.ProductSubcategoryID";
EntityDataSource source = null;
source = Page.FindControl("ProductDataSource") as EntityDataSource;
if(source != null) {
source.EntitySetName = null;
source.CommandText = query;
}
This code provides a strongly-typed result and uses the Where clause.

Extending Zend_Db

I apologize if my title is a bit misleading and it turns out that it's some other class under Zend_Db.
I use the following method of extracting data from a MSSQL:
// $_config contains information about how to connect to my MSSQL server
$config = new Zend_Config($_config);
$db = Zend_Db::factory($config->database);
$sql = "SELECT * FROM table1";
print_r($db->fetchAll($sql));
So far no problem and everything runs smooth :).
Now I need to run some more complex queries with multiple rowsets:
$sql2 = <<<EOD
DECLARE #test INT
SET #test = 42
SELECT * FROM table1 WHERE col1 = #test
SELECT col2 FROM table2 UNION
SELECT col3 FROM table2
SELECT * FROM table3
EOD;
print_r($db->fetchAll($sql2));
I hope you get the idea.
Using $db->fetchAll($sql2); will result in
Fatal error: Uncaught exception
'Zend_Db_Statement_Exception' with
message 'SQLSTATE[HY000]: General
error: 10038 Attempt to initiate a new
SQL Server operation with results
pending. [10038] (severity 7)
[(null)]' in
\Sacp026a\sebamweb$\prod\includes\Zend\Db\Statement\Pdo.php:234
The following function will return all the correct rowsets:
function sqlquery_multiple($zdb, $sql) {
$stmt = $zdb->query($sql);
$rowsets = array();
do {
if ($stmt->columnCount() > 0) {
$rowsets[] = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
} while ($stmt->nextRowset());
return $rowsets;
}
print_r(sqlquery_multiple($db, $sql2));
Now my big question is:
How do I extend Zend_Db, so I can implement and use the function above as $db->fetchMulti($sql2); instead of sqlquery_multiple($db, $sql2)?
Thanks in advance :)
NB: It's worth mentioning that I'm using the ODBC-patch in order to be able to fetch multiple rowsets in the first place.