How to update an entire object using jdbcTemplate without specifying column names? - java

I was looking at the reference here. We can do this -
String orderSql = "select * from order where id = ?";
jdbcTemplate.query(orderSql, new BeanPropertyRowMapper<>(Order.class), orderId);
This reads from the database and can directly deserialise into the Order object. This is well and good.
What I want to do is -
String updateSql = "update order ? where id = ?";
jdbcTemplate.save(updateSql, new BeanPropertyRowMapper<>(Order.class), order, orderId);
Is there a way of doing this?

No, it's not possible. JdbcTemplate comes with the ability to map an object using query as you've said without having to define columns/attributes, but there is no equivalent usage for update. You will have to pass in your SQL and the relevant parameters. As someone has mentioned if you really want to do this you could consider using hibernate.

Use this query for update :-
String updateSql = "update <table_name> set order= ? where id = ?";
jdbcTemplate.update(updateSql, new Object[]{order, orderId});
It will return affected row update count.

No ! You can only do this !
jdbcTemplate.update("update ordertable set order = ? where id = ?", order, orderId);

Related

SQL Syntax error in Hibernate's map function

SELECT NEW Map (PRODUCT_CATEGORY, COUNT(PRODUCT_CATEGORY) AS COUNTER) from Product WHERE USER_ID = (SELECT USER_ID FROM USERS WHERE USERNAME='burak123'
Hi everyone,
As hibernates document says here: https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html#queryhql-select
I am trying to map the query result into a hash map like this
#Query(value = "SELECT NEW Map( PRODUCT_CATEGORY , COUNT(PRODUCT_CATEGORY) AS COUNTER ) from Product WHERE USER_ID=(SELECT USER_ID FROM USERS WHERE USERNAME=(:username)) ",nativeQuery = true)
HashMap<Integer,Integer> getCategoryCountsWithUsername(#Param("username")String username);
But it throws an JdbcSyntaxErrorException. I am trying to solve this for like 1 hours already. Can someone help?
You are using a native query, not an HQL query. Check your SQL syntax.
With a native query, your named parameter won't work. You need to remove the nativeQuery = true

How to pass dashed strings to oracle from a query written in java

I have a problem with this query when I pass it to an oracle dbms
SELECT * FROM RD_RBF WHERE REQUEST_ID = 'S2N-F01-000000000001'
because of the dashes in the string the jvm return me this exception
java.sql.SQLException: Fail to convert to internal representation
How can I pass this query to oracle correctly? Thanks a lot
P.S. I'm not shure of the code because I'm using Talend software that generates automatically the code of components but I can post part of the code above
String dbquery_tOracleInput_1 = "SELECT * FROM RD_RBF WHERE REQUEST_ID = 'S2N-F01-000000000001'";
java.sql.ResultSet rs_tOracleInput_1 = null;
try{
rs_tOracleInput_1 = stmt_tOracleInput_1.executeQuery(dbquery_tOracleInput_1);
java.sql.ResultSetMetaData rsmd_tOracleInput_1 = rs_tOracleInput_1.getMetaData();
int colQtyInRs_tOracleInput_1 = rsmd_tOracleInput_1.getColumnCount();
Use toraclerow component.
Query as follows in component:
"SELECT * FROM RD_RBF WHERE REQUEST_ID = ?"
Go to advance setting, select use prepared statement and add 1 paarmeter index.
also select the propagate Query's record set.
tOracleRow_1 -----> tParseRecordSet----->

Use PreparedStatement to build a query

I was wondering if using PreparedStatement.setString() was a good idea (possible, sensible?) to dynamically build a query.
For example :
sql code:
SELECT * FROM table1 WHERE table1.category = ? ?
java code:
ps.setString(1,"category1");
ps.setString(2,"AND table1.category = 'category2'");
Also, would it be possible to do something like:
ps.setString(1,"category1");
ps.setString(2," AND table1.category = ?");
ps.setString(3,"category2");
Best regards
Unfortunately, NO.
PreparedStatements are strictly for values only. Table Names and Column Names (as well as conditions in your example) are not allowed. So the best way to do is to concatenate it with the string.
String others = " AND table1.category = ?";
String query = "SELECT * FROM table1 WHERE table1.category = ? " + others;
java code:
ps.setString(1,"category1");
ps.setString(2,"category2");
Whatever you put inside setString will go within single quotes ' ' and will not be interpreted as a query.

Hql Query to Bind a Data Member

Query qry = session.createQuery("From RegistrationBean where ? = ?");
qry.setString(0,searchCriteria);
qry.setString(1,searchField);
searchList =(ArrayList<RegistrationBean>) qry.list();
RegistrationBean Entity class has userName, address, age fields..
I want to search a user by search criteria such as userName, address etc. using the above single query...
But the query is returning me zero results even though the user exist..
what's the problem?
Both parameters are set to 0 position, the second is not set. The position parameter should be set sequentially.
qry.setParameter(0,searchCriteria);
qry.setParameter(1,searchField);
But the field name should pass in the following way
String queryString = "from RegistrationBean as model where model." + propertyName + "= ?";
Query queryObject = getSession().createQuery(queryString);
queryObject.setParameter(0, value);
return queryObject.list();
Try in the following way:
Query qry = session.createQuery("select * from RegistrationBean where :searchCrit = :searchValue");
qry.setString(":searchCrit",searchCriteria);
qry.setString(":searchValue",searchField);
searchList =(ArrayList<RegistrationBean>) qry.list();
It is more appropriate to use it like this instead of setting indexes (your problem is that you set both to 0), because if you change something in your query you might need to change your setters afterwards.

How to handle 'IN' case in SQL Statement with the way of Parameterized Query?

To avoid SQL injection attacks in my project, I'm attempting access database with Parameterized Query way. Right now I know how to handle equal case like below (With Spring JdbcTemplate):
String sql = "SELECT * FROM T_USER WHERE USERNAME = ? AND PASSWORD = ?"
jdbcTemplate.query(sql,
new UserRowMapper(),
new Object[]{"%admin%", "%password%"});
Above code runs no problem, but I had no idea how to handle the 'IN' case, following is my case, and it works failed:
String sql =
"SELECT * FROM T_USER WHERE USERNAME = ? AND PASSWORD = ? AND CLASS_ID IN (?)"
jdbcTemplate.query(sql,
new UserRowMapper(),
new Object[]{"%admin%", "%password%", "1,2,3"});
Anybody give me guidance? Thanks a lot.
I think you can create a List and pass it as 3rd parameter. Also You need to use LIKE in place of = in first two column filters.
List<Integer> classIds = new ArrayList<Integer>();
classIds.add(1);
classIds.add(2);
classIds.add(3);
String sql = "SELECT * FROM T_USER WHERE "+
"USERNAME LIKE ? AND PASSWORD LIKE ? AND CLASS_ID IN (?)";
jdbcTemplate.query(sql, new Object[]{"%admin%", "%password%", classIds},
new UserRowMapper());
Please note: Here is the syntax:
public List query(String sql, Object[] args, RowMapper rowMapper)
throws DataAccessException
EDIT: Please try namedParameterJdbcTemplate as bwlow:
String sql = "SELECT * FROM T_USER WHERE "+
"USERNAME LIKE :uname AND PASSWORD LIKE :passwd AND CLASS_ID IN (:ids)";
Map<String, Object> namedParameters = new HashMap<String, Object>();
namedParameters.put("uname", "%admin%);
namedParameters.put("passwd", "%password%");
namedParameters.put("ids", classIds);
List result = namedParameterJdbcTemplate.query(sql, namedParameters,
new UserRowMapper());
Three options:
Generate different JDBC queries for each length of the IN LIST, and parameterize each INDIVIDUAL item, e.g. this answer
For small tables, you can cheat and use a LIKE statement, e.g. this answer
Use a SPLIT function (anti-LISTAGG) to turn the delimited list into individual rows of one column each, and JOIN against it. Example SPLIT function
You'll parameterize the argument to the function as a single string

Categories

Resources