Spring JdbcTemplate query parameters type error: Invalid column type - oracle

I use Spring Jdbc Template that way:
public List<User> getUsersForGrid(int rows, int page, String sidx,
String sord) {
int fromRecord = 0;
int toRecord = 0;
toRecord = page * rows;
fromRecord = (page - 1) * rows;
StringBuilder sqlB = new StringBuilder();
sqlB.append("SELECT user_id, username ");
sqlB.append("FROM users ");
sqlB.append("WHERE :fromRecord <= rownum AND rownum <= :toRecord ");
sqlB.append("ORDER BY %s %s ");
String sql = String.format(sqlB.toString(), sidx, sord);
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("fromRecord", fromRecord);
params.addValue("toRecord", toRecord);
List<Map<String, Object>> rsRows = this.jdbcTemplate.queryForList(sql
.toString(),params);
List<User> users = new ArrayList<User>();
for (Map<String, Object> row : rsRows) {
BigDecimal id = (BigDecimal) row.get("user_id");
String username = (String) row.get("username");
User user = new User(id.intValue(), username);
users.add(user);
}
return users;
}
and get java.sql.SQLException: Invalid column type
sidx is column nate("user_id" for example) sord is asc/desc
When pass no params(execute only
sql.append("SELECT user_id, username ");
sql.append("FROM users ");
) everything is OK.
Update: Works with:
sqlB.append("WHERE ? <= rownum AND rownum <= ? ");
and
this.jdbcTemplate.queryForList(sql.toString(),new Object[]{fromRecord, toRecord});
Seems like problem with Spring MapSqlParameterSource and named parameters. I use Spring 3.1.3
DB is Oracle 11.2
describe users;
Name Null Type
------------------------------ -------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
USER_ID NOT NULL NUMBER
USERNAME NOT NULL VARCHAR2(40)
PASSWORD NOT NULL VARCHAR2(20)
ENABLED NOT NULL NUMBER

I think the problem is with your order by clause,
you are trying to dynamically change your order by clause.
Just try
StringBuilder sql = new StringBuilder();
sql.append("SELECT user_id, username ");
sql.append("FROM users ");
sql.append("WHERE :fromRecord <= rownum AND rownum <= :toRecord ");
sql.append("ORDER BY user_id asc ");
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("fromRecord", fromRecord);
params.addValue("toRecord", toRecord);
If the above works, then instead of using the MapSqlParameterSource for changing the order by clause use something like
StringBuilder sql = new StringBuilder();
sql.append("SELECT user_id, username ");
sql.append("FROM users ");
sql.append("WHERE :fromRecord <= rownum AND rownum <= :toRecord ");
sql.append("ORDER BY %s %s ");
//Format the sql string accordingly
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("fromRecord", fromRecord, Types.INTEGER);
params.addValue("toRecord", toRecord, Types.INTEGER);
Hope it helps.

try this
List<Map> rows = getJdbcTemplate().queryForList(sql);
for (Map row : rows) {
BigDecimal id = (BigDecimal) row.get("user_id");
String username = (String) row.get("username");
User user = new User(id.intValue(), username);
users.add(user);
}
ok try
MapSqlParameterSource namedParameters = new MapSqlParameterSource();
namedParameters.addValue("fromRecord", fromRecord);
namedParameters.addValue("toRecord", toRecord);
namedParameters.addValue("sidx", sidx);
namedParameters.addValue("sord", sord);
return this.getNamedParameterJdbcTemplate().query(query,
namedParameters, new UserElementMapper());
public class UserMapper implements RowMapper<User> {
public EmailElement mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
emailElement.setID(rs.getInt("user_id"));
emailElement.setUsernameo(rs.getString("username"));
return user;
}
}

Related

oracle jdbc driver reports no primary key columns on a table that has a primary key

This was reported by HibernateTools Reverse Engineering, but it seems to be true.
oracle jdbc driver reports no primary key columns on a table that has a primary key.
#Test
public void checkTable() throws SQLException, IOException {
System.out.println("in check table");
assertNotNull(conn);
Statement s = conn.createStatement();
ResultSet rset = s.executeQuery("select user from dual");
rset.next();
String username = rset.getString(1);
rset.close();
try {
s.execute("drop table " + username + ".x");
} catch (Exception e) {
// nothing it might not exist
}
s.execute("create table " + username + ".x (y number)");
s.execute("alter table x add constraint x_pk primary key (y)");
DatabaseMetaData meta = conn.getMetaData();
final String[] tableTypes = new String[] { "TABLE", "VIEW" };
ResultSet rs = meta.getTables(null, username, "X",tableTypes);
rs.next();
String table = rs.getString("table_name");
System.out.println("table is " + table);
rs.close();
rs = s.executeQuery("select * from user_constraints where table_name = 'X'");
rs.next();
String type = rs.getString("constraint_type");
assertEquals("P",type); // primary key
rs.close();
rs = meta.getPrimaryKeys(null, username, "X");
rs.next();
logger.info("getting pk");
System.out.print("wtf");
int colCount = 0;
while (rs.next()) {
final String pkName = rs.getString("pk_name");
logger.info("pkName: {}", pkName);
int keySeq = rs.getShort("key_seq"); // TODO should probably be column seq
String columnName = rs.getString("column_name");
logger.warn("seq: {}, columnName: {}, keySeq, columnName");
colCount++;
}
System.out.println("colCount: " + colCount);
assertEquals(1,colCount);
}

Retrieve the Columns and Tables of a Database in Postgres

I am working on a Spring MVC project where I need to get the tables and the attributes of a selected Postgres Database and store them in an array as soon as the page loads.
I have currently written the following ajax call through which am able to retrieve the tables and display under the respective database.
VisualEditor.js
drop: function (e, ui) {
var mouseTop = e.clientY;
var mouseLeft = e.clientX;
var dropElem = ui.draggable.attr('class');
droppedElement = ui.helper.clone();
ui.helper.remove();
$(droppedElement).removeAttr("class");
$(droppedElement).draggable({containment: "container"});
jsPlumb.repaint(ui.helper);
//If the dropped Element is a TABLE then->
if (dropElem == "stream ui-draggable ui-draggable-handle") {
var newAgent = $('<div>');
jsPlumb.addEndpoint(newAgent,connectorProperties);
newAgent.attr('id', i).addClass('streamdrop');
var elemType = "table";
$("#container").addClass("disabledbutton");
$("#toolbox").addClass("disabledbutton");
$('#container').append(newAgent);
$.ajax({
type: "post",
url: "http://localhost:8080/controllers/tables",
cache: false,
success: function(response){
if (response !== "{}"){
var array = response.replace("{", "").replace("}", "");
var index = array.indexOf("[") +1;
var stringval = array.split(":");
var stringval2 = array.substring(index,array.indexOf("]")).split(",");
var db_names = new Array();
var table_names = new Array();
var column_names = new Array();
for(var i = 0 ;i < stringval.length-1 ;i++)
{
db_names[i] = eval(stringval[i]);
if(db_names[i]=="testdb"){
var StreamArray = new Array();
}
var listId = "db"+i;
var dropdownId ="mydrpdown"+i;
table_names[i] = new Array();
$("#lot").append(
"<li onclick='myFunction(\""+dropdownId+"\","+i+","+stringval2.length+")' class='list-group-item dropbtn' id='"+listId+"'> " + db_names[i] +
"</li> "+
"<div id='" + dropdownId +"' class='dropdown-content'> " +
"<a onclick='setDatabase(\""+db_names[i]+"\",\""+listId+"\")'> Make This as Default Database</a>"+
"</div>"
);
$("#databaseID").append(
"<option>" + db_names[i] +"</option>"
);
for(var j=0;j < stringval2.length;j++)
{
/**
* Loading the Predefined Databases and Tables of the Connected DB
*/
var table_id= "tableId"+i+j;
if( eval(stringval2[j]) != null){
table_names[i][j] = eval(stringval2[j]);
if(db_names[i]=="testdb")
{
StreamArray[j] = new Array(4);
StreamArray[j][0] = table_names[i][j];
/**
* table_names array values at the moment are:
* customer,department and students
* So the following ajax call should pass each table name to the listTables
* method in the controller and fetch the respective columns of each table
*/
$.ajax({
type: "post",
url: "http://localhost:8080/controllers/listTables/{tablename}",
data: { tablename: table_names[i][j]} ,
cache: false,
success: function(response){
if (response !== "{}"){
var array = response.replace("{", "").replace("}", "");
var index = array.indexOf("[") +1;
var stringval = array.split(":");
var stringval2 = array.substring(index,array.indexOf("]")).split(",");
var db_names = new Array();
var table_names = new Array();
var column_names = new Array();
for(var i = 0 ;i < stringval.length-1 ;i++){
}
}
}
});
}
$("#lot").append(
"<li class='list-group-item'style = 'display:none' id='"+table_id+"'> "+table_names[i][j]+" </li>");
}
}
$("#lot").append(
"</br>");
array = array.slice(array.indexOf("]") +2);
index = array.indexOf("[") +1;
stringval2 = array.substring(index,array.indexOf("]")).split(",");
}
}
},
error: function(xhr, status, error){
alert("Error while loading the query");
}
});
$("property").show();
$(".toolbox-titlex").show();
$(".panel").show();
I have written 2 ajax calls embedded within to get the table_names in the first go and the column_names following that. But am guessing that this is not a very efficient way. But I am not sure how to get both at the same time.
EditorController.java
#RequestMapping(value= "/tables", method = RequestMethod.POST)
public #ResponseBody
String tables(HttpServletRequest request, HttpServletResponse response)
throws Exception {
Map<String, List<String>> alvalues = new HashMap<String, List<String>>();;
String queryString = request.getParameter("query");
// ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Module.xml");
//CustomerDao customerDAO = (CustomerDao) context.getBean("CustomerDao");
alvalues = customerDAO.getAllTables();
Gson gson = new Gson();
String element = gson.toJson(alvalues);
System.out.println(element);
return element;
}
#RequestMapping(value= "/listTables/{tablename}", method = RequestMethod.POST)
public #ResponseBody
String listTables(HttpServletRequest request, HttpServletResponse response,#PathVariable("tablename") String tablename)
throws Exception {
Map<String, List<String>> alvalues = new HashMap<String, List<String>>();;
String queryString = request.getParameter("query");
alvalues = customerDAO.getAllFields(tablename);
Gson gson = new Gson();
String element = gson.toJson(alvalues);
System.out.println(element);
return element;
}
CustomerDAO.java
public Map<String, List<String>> getAllTables();
public Map<String, List<String>> getAllFields(String tablename);
jdbcCustomerDAO.java
public Map<String, List<String>> getAllTables(){
int k = 1;
Map<String, List<String>> map = new HashMap<String, List<String>>();
ArrayList<String> databases = getAllDatabse();
String sql = "SELECT table_name FROM information_schema.tables WHERE table_schema='public'";
Connection conn = null;
for(int i=0;i<=databases.size();i++)
{
try {
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/"+databases.get(i),"postgres", "123");
PreparedStatement ps = conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = ps.executeQuery();
ArrayList<String> alvalues = new ArrayList<String>();
while(rs.next()){
alvalues.add(rs.getString(1));
}
map.put(databases.get(i), alvalues);
rs.beforeFirst();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
String key = entry.getKey();
List<String> values = entry.getValue();
System.out.println("Key = " + key);
System.out.println("Values = " + values + "n");
}
conn.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
return map;
}
public Map<String, List<String>> getAllFields(String tablename){
int k = 1;
Map<String, List<String>> map = new HashMap<String, List<String>>();
ArrayList<String> databases = getAllDatabse();
String sql = "SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '"+tablename+"'";
Connection conn = null;
for(int i=0;i<=databases.size();i++)
{
try {
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/"+databases.get(i),"postgres", "123");
PreparedStatement ps = conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = ps.executeQuery();
ArrayList<String> alvalues = new ArrayList<String>();
while(rs.next()){
alvalues.add(rs.getString(1));
}
map.put(databases.get(i), alvalues);
rs.beforeFirst();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
String key = entry.getKey();
List<String> values = entry.getValue();
System.out.println("Key = " + key);
System.out.println("Values = " + values + "n");
}
conn.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
return map;
}
But am not able to get the column names successfully.
Console Log
According to this, the table_names are successfully retrieved but the column names are empty.
INFO : com.postgres.controllers.HomeController - Welcome home! The client locale is en_US.
postgres
postgreside
testdb
Key = postgres
Values = []n
Key = postgreside
Values = [constraints, users, notes, session, projects, databases, tables, columns, index, checksconstraint, additionalproperties, foreignref, primaryref, referenceproperties, department, person]n
Key = postgres
Values = []n
Key = testdb
Values = [customer, department, students]n
Key = postgreside
Values = [constraints, users, notes, session, projects, databases, tables, columns, index, checksconstraint, additionalproperties, foreignref, primaryref, referenceproperties, department, person]n
Key = postgres
Values = []n
Index: 3, Size: 3
{"testdb":["customer","department","students"],"postgreside":["constraints","users","notes","session","projects","databases","tables","columns","index","checksconstraint","additionalproperties","foreignref","primaryref","referenceproperties","department","person"],"postgres":[]}
postgres
postgreside
testdb
postgres
postgreside
testdb
postgres
postgreside
testdb
Key = postgres
Values = []n
Key = postgres
Values = []n
Key = postgres
Values = []n
Key = postgreside
Values = []n
Key = postgres
Values = []n
Key = postgreside
Values = []n
Key = postgres
Values = []n
Key = postgreside
Values = []n
Key = postgres
Values = []n
Key = testdb
Values = []n
Key = postgreside
Values = []n
Key = postgres
Values = []n
Index: 3, Size: 3
{"testdb":[],"postgreside":[],"postgres":[]}
Key = testdb
Values = []n
Key = postgreside
Values = []n
Key = postgres
Values = []n
Index: 3, Size: 3
{"testdb":[],"postgreside":[],"postgres":[]}
Key = testdb
Values = []n
Key = postgreside
Values = []n
Key = postgres
Values = []n
Index: 3, Size: 3
{"testdb":[],"postgreside":[],"postgres":[]}
I would like to have a single method to retrieve the table names and their attributes/columns and store it in the StreamArray so that I don't need to access the DB everytime I need to refer to the related data.
Any suggestions on how I could get the column names and store it in the StreamArray that I've created under the VisualEditor.js will be highly appreciated.
In the general case, you can have more than one database to deal with, more than one schema, and each table name can appear in more than one schema. In your case, there might be more schemas you need to exclude. Or you might decide that only the schema 'public' is relevant. (Be careful with decisions like that.)
select table_catalog, table_schema, table_name, column_name
from information_schema.columns
where table_catalog = 'your_db_name'
and table_schema <> 'information_schema'
and table_schema <> 'pg_catalog'
order by table_catalog, table_schema, table_name, column_name;

Query works fine in MySql but returns no records with JdbcTemplate

I have the following service method:
public Page<ProductSalesReportLineDto> getReport(
Unit unit, Organization customer, Organization supplier, Date startDate, Date endDate, Pageable pageable
){
List<ProductSalesReportLineDto> lines = new ArrayList<ProductSalesReportLineDto>();
String sql = "SELECT product.id, product.code as code, product.barcode as barcode, product_name.name__text AS name, " +
"SUM(order_line.quantity) as quantity, SUM(order_line.commissioned_price_price * order_line.quantity) as price " +
"FROM product LEFT JOIN order_line ON order_line.product_id = product.id " +
"JOIN `order` ON order_line.order_id = order.id " +
"JOIN product_name ON product_name.product_id = product.id " +
"WHERE product_name.name__locale = \"en-US\" " +
"AND (:customer is null OR :customer='' OR `order`.customer_id = :customer) " +
"AND (:supplier is null OR :supplier='' OR `order`.supplier_id = :supplier) " +
"AND (:startDate is null OR :startDate='' OR `order`.date >= :startDate) " +
"AND (:endDate is null OR :endDate='' OR `order`.date <= :endDate) " +
"AND (:unit is null OR :unit='' OR product.unit = :unit) " +
"GROUP BY product.id, product_name.name__text " +
"LIMIT :offset, :pageSize";
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("offset", pageable.getOffset());
parameters.put("pageSize", pageable.getPageSize());
parameters.put("customer", customer != null ? customer.id : null);
parameters.put("supplier", supplier != null ? supplier.id : null);
parameters.put("startDate", startDate);
parameters.put("endDate", endDate);
parameters.put("unit", unit);
List<Map<String, Object>> rows = namedParameterJdbcTemplate.queryForList(sql, parameters);
for (Map<String, Object> row : rows) {
ProductSalesReportLineDto line = new ProductSalesReportLineDto();
line.productName = row.get("name") != null ? row.get("name").toString() : "";
line.productCode = row.get("code") != null ? row.get("code").toString() : "";
line.productBarcode = row.get("barcode") != null ? row.get("barcode").toString() : "";
line.quantity = row.get("quantity") != null ? Double.parseDouble(row.get("quantity").toString()) : 0;
line.price = row.get("price") != null ? Double.parseDouble(row.get("price").toString()) : 0;
lines.add(line);
}
Page<ProductSalesReportLineDto> page = new PageImpl<ProductSalesReportLineDto>(lines);
return page;
}
The parameters come from a #RestController method:
public #ResponseBody
ResponseEntity<?> get(
#RequestParam(value = "unit", required = false) Unit unit,
#RequestParam(value = "customer", required = false) Organization customer,
#RequestParam(value = "supplier", required = false) Organization supplier,
#DateTimeFormat(pattern = "yyyyy-MM-dd") #RequestParam(value = "startDate", required = false) Date startDate,
#DateTimeFormat(pattern = "yyyyy-MM-dd") #RequestParam(value = "endDate", required = false) Date endDate,
Pageable pageable
)
And Unit is an enum type field on Product:
#Enumerated(EnumType.STRING)
public Unit unit;
public enum Unit {
ROLL("ROLL", "ROLL", AbstractUnit.ONE),
METRE("METRE", Units.METRE.getSymbol(), Units.METRE),
KILOGRAM("KILOGRAM", Units.KILOGRAM.getSymbol(), Units.KILOGRAM),
PIECE("PIECE", "PIECE", AbstractUnit.ONE),
SAMPLE("SAMPLE", "SAMPLE", AbstractUnit.ONE);
I cannot retrieve products by unit using this query. With MySql the query works fine and it returns records. For example:
SELECT product.id, product.code as code, product.barcode as barcode, product_name.name__text AS name, SUM(order_line.quantity) as quantity, SUM(order_line.commissioned_price_price) as price FROM product LEFT JOIN order_line ON order_line.product_id = product.id JOIN `order` ON order_line.order_id = `order`.id JOIN product_name ON product_name.product_id = product.id WHERE product_name.name__locale = "en-US" AND (null is null OR null='' OR `order`.customer_id = null) AND (null is null OR null='' OR `order`.supplier_id = null) AND (null is null OR null='' OR `order`.date >= null) AND (null is null OR null='' OR `order`.date <= null) AND ("ROLL" is null OR "ROLL"='' OR product.unit = "ROLL") GROUP BY product.id, product_name.name__text
This query returns one row. When I run the same query via the rest interface and NamedParameterJdbcTemplate it returns no records. Can anybody tell what I am missing?
Following code also returns one row:
String sql2 = "SELECT * FROM product WHERE product.unit = :unit";
Map<String, Object> parameters2 = new HashMap<String, Object>();
parameters2.put("unit", "ROLL");
List<Map<String, Object>> rows2 = namedParameterJdbcTemplate.queryForList(sql2, parameters2);

Hextoraw() not working with IN clause while using NamedParameterJdbcTemplate

I am trying to update certain rows in my oracle DB using id which is of RAW(255).
Sample ids 0BF3957A016E4EBCB68809E6C2EA8B80, 1199B9F29F0A46F486C052669854C2F8...
#Autowired
private NamedParameterJdbcTemplate jdbcTempalte;
private static final String UPDATE_SUB_STATUS = "update SUBSCRIPTIONS set status = :status, modified_date = systimestamp where id in (:ids)";
public void saveSubscriptionsStatus(List<String> ids, String status) {
MapSqlParameterSource paramSource = new MapSqlParameterSource();
List<String> idsHexToRaw = new ArrayList<>();
String temp = new String();
for (String id : ids) {
temp = "hextoraw('" + id + "')";
idsHexToRaw.add(temp);
}
paramSource.addValue("ids", idsHexToRaw);
paramSource.addValue("status", status);
jdbcTempalte.update(*UPDATE_SUB_STATUS*, paramSource);
}
This above block of code is executing without any error but the updates are not reflected to the db, while if I skip using hextoraw() and just pass the list of ids it works fine and also updates the data in table. see below code
public void saveSubscriptionsStatus(List<String> ids, String status) {
MapSqlParameterSource paramSource = new MapSqlParameterSource();]
paramSource.addValue("ids", ids);
paramSource.addValue("status", status);
jdbcTempalte.update(UPDATE_SUB_STATUS, paramSource);
}
this code works fine and updates the table, but since i am not using hextoraw() it scans the full table for updation which I don't want since i have created indexes. So using hextoraw() will use index for scanning the table but it is not updating the values which is kind of weird.
Got a solution myself by trying all the different combinations :
#Autowired
private NamedParameterJdbcTemplate jdbcTempalte;
public void saveSubscriptionsStatus(List<String> ids, String status) {
String UPDATE_SUB_STATUS = "update SUBSCRIPTIONS set status = :status, modified_date = systimestamp where id in (";
MapSqlParameterSource paramSource = new MapSqlParameterSource();
String subQuery = "";
for (int i = 0; i < ids.size(); i++) {
String temp = "id" + i;
paramSource.addValue(temp, ids.get(i));
subQuery = subQuery + "hextoraw(:" + temp + "), ";
}
subQuery = subQuery.substring(0, subQuery.length() - 2);
UPDATE_SUB_STATUS = UPDATE_SUB_STATUS + subQuery + ")";
paramSource.addValue("status", status);
jdbcTempalte.update(UPDATE_SUB_STATUS, paramSource);
}
What this do is create a query with all the ids to hextoraw as id0, id1, id2...... and also added this values in the MapSqlParameterSource instance and then this worked fine and it also used the index for updating my table.
After running my new function the query look like : update
SUBSCRIPTIONS set status = :status, modified_date = systimestamp
where id in (hextoraw(:id0), hextoraw(:id1), hextoraw(:id2)...)
MapSqlParameterSource instance looks like : {("id0", "randomUUID"),
("id1", "randomUUID"), ("id2", "randomUUID").....}
Instead of doing string manipulation, Convert the list to List of ByteArray
List<byte[]> productGuidByteList = stringList.stream().map(item -> GuidHelper.asBytes(item)).collect(Collectors.toList());
parameters.addValue("productGuidSearch", productGuidByteList);
public static byte[] asBytes(UUID uuid) {
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uuid.getMostSignificantBits());
bb.putLong(uuid.getLeastSignificantBits());
return bb.array();
}

Spring JDBC Framework Conditional Prepared Statement

public ResultSet getAdCampaignDetailsbyName(ADCampaignDetails Obj,
Connection conn, ResultSet rs, PreparedStatement pstmt) throws SQLException {
String query = "select adCampaignName,adCampaignId from AdCampaignDetails";
query += " where 1=1 ";
if (Obj.getAdCamapignName() != null)
query += " and adCampaignName = ?";
if (Obj.userId != "")
query += " and userId = ?";
pstmt = conn.prepareStatement(query);
int i = 0;
if (Obj.getAdCamapignName() != null)
pstmt.setString(++i, Obj.getAdCamapignName());
if (Obj.userId != "")
pstmt.setString(++i, Obj.userId);
System.out.println(" Q : " + query);
rs = pstmt.executeQuery();
return rs;
}
I am new to Spring , in this above query, i have used two conditions , How to execute query with condition in Spring JDBC Framework?
You can use SimpleJDBCTemplate.
// SQL query
String query = "select adCampaignName,adCampaignId from AdCampaignDetails where 1=1";
// Map with parameter value
Map<String, Object> parameters = new HashMap<String, Object>();
if (adCampaignName!=null){
parameters.put("adCampaignName ", adCampaignName );
query += " AND adCampaignName = :adCampaignName";
}
if (userId!=null){
parameters.put("userId", 1);
query += " AND userId= :userId";
}
// Execute query using simpleJDBC Template
List<AdCampaignDetails> resultList = getSimpleJdbcTemplate().query(query, new customRowMapper(), parameters);
You can build the query string accordingly, just add coresponding entries in map.
Check this link for details.

Resources