I have been trying to pass the columns I want to select in but out of the box it appears it is not possible. I have tried things like
#Query("SELECT :columns FROM USERS u WHERE u.LOCALE = :locale AND u.id IN (:ids)")
Flux<Users> retrieveExportData(#Param("columns") String columns,
#Param("locale") String locale,
#Param("ids") String[] ids);
and with
private final R2dbcEntityTemplate template;
I tried to create my own query and but that was not working because it has to be of type Criteria and that was just creating a complexity that just was not worth it.
It would be nice if I could add the columns like
criteriaList.add(
Criteria.where("LOCALE").is(locale)
);
Criteria criteria = Criteria.from(criteriaList);
and execute it like
Flux<Users> users = this.template.select(User.class)
.matching(Query.query(criteria))
.all();
or just calling the repository like in my first example.
Has anyone been able to do this successfully?
----- update 1 -----
I tried doing like so:
import org.springframework.r2dbc.core.DatabaseClient;
DatabaseClient databaseClient = DatabaseClient.create(connectionFactory);
String sql = "SELECT " + columns + " FROM USERS u WHERE u.LOCALE=" + locale + " AND u.id IN (" + ids + ")";
return databaseClient.sql(sql)
.fetch()
.all().cast(User.class);
but Since Spring 4.3.6.RELEASE, LinkedCaseInsensitiveMap doesn't extend LinkedHashMap and HashMap, but only implements Map interface.
This results in a
Cannot cast org.springframework.util.LinkedCaseInsensitiveMap to User at java.base/java.lang.Class.cast
error.
I then tried the jooq approach suggested in the answers but it just produces syntax errors. Example
private final DSLContext ctx = DSL.using(connectionFactory);
private final Users users = ctx.newRecord(Users.USERS); <-- USERS not found
#Query("SELECT :columns FROM USERS u WHERE u.LOCALE = :locale AND u.id IN (:ids)")
public Flux<Users> retrieveExportData(
List<Field<?>> columns,
String locale,
String[] ids
) {
return Flux.from(ctx
.select(columns)
.from("USERS")
.where(users.LOCALE.eq(locale)) <--- LOCALE not found
.and(users.ID.in(ids)) <--- ID not found
).map(r -> r.into(Users.class)); <---- into not found
}
the library look promising. I will try to get it working.
You cannot replace a bind parameter (:columns) by syntactic elements like this, other than actual bind values. For this type of dynamic SQL, you'll have to resort to some sort of query building mechanism.
Perhaps look at jOOQ, which has R2DBC support? Your implementation would then look like this:
#Query("SELECT :columns FROM USERS u WHERE u.LOCALE = :locale AND u.id IN (:ids)")
public Flux<Users> retrieveExportData(
List<Field<?>> columns,
String locale,
String[] ids
) {
return Flux.from(ctx
.select(columns)
.from(USERS)
.where(USERS.LOCALE.eq(locale))
.and(USERS.ID.in(ids))
).map(r -> r.into(Users.class));
}
Disclaimer: I work for the company behind jOOQ.
you can write dynamic SQL like so.
import org.springframework.r2dbc.core.DatabaseClient;
DatabaseClient databaseClient = DatabaseClient.create(connectionFactory);
String sql = "SELECT " + columns + " FROM USERS u WHERE u.LOCALE=" + locale + " AND u.id IN (" + ids + ")";
return databaseClient.sql(sql)
.fetch()
.all().cast(User.class);
and you will need this dependency
implementation "org.springframework.boot:spring-boot-starter-data-r2dbc:2.6.2"
I want to two column value in entity but I
dont selected.
How to solve select problem.
Try code:
var t1= dbcontext.Entities.Student.Select(c=>c.Number , a=>a.branchcode).
I error branchcode area.
But ı select number and branchcode.
You can try this code:
var t1 = dbcontext.Entities.Student.Select(c => new { Number = c.Number, Branchcode = c.Branchcode });
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?
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>
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.