Spring queryForList not working - java

I have the following query and the following piece of code to get the results.
List<Map<String, Object>> rows = this.getBemsConnection().queryForList(ItemWorkflowDetails.BEMS_CREATION_DATE_QUERY, new Object[]{itemName});
if (rows != null && !rows.isEmpty()) {
for (Map<String, Object> row : rows) {
itemSetupObj.setBemsCreation((String) row.get("BEMS_CREATION"));
LOGGER.info("Bems Creation Date: {}", itemSetupObj.getBemsCreation());
}
}
String BEMS_CREATION_DATE_QUERY = "SELECT creation_date bems_creation FROM xxref_cg1_o.mtl_system_items_b WHERE segment1 = ? AND organization_id = 1";
I am getting data for this from the backend database but nothing happens when I execute the query in Java. Am I missing something?

Figured the issue, the input from Java was going in small case where as the data was stored in upper case in the table. Plus the query I ran in DB had the value in upper case. So indeed, I was not getting data as it was not able to make a match.

Related

Why can't I query by String value when I can query by equivalent int value in Hibernate JPA with java

I was given a project at work including JPA / Hibernate
I have an object for example that is let s say described as
class SampleObject {
string value;
string othervalue;
}
and lets say that the value in the database is populated with 2 rows
table - SampleObject
row 1 - value = "21", othervalue = "some other value"
row 2 - value = "31", othervalue = "some other other value"
I can write a query that returns rows that follows
Query q = entityManager.createQuery("select s from SampleObject s where value = 21")
and I can write a query that returns rows that follows
Query q = entityManager.createNativeQuery("select * from dbo.SampleObject s where value = 21", SampleObject.class)
but what i cannot do is write those same queries as a string value and return data
ex 1:
entityManager.createQuery("select s from SampleObject s where value = '21'")
ex 2:
entityManager.createQuery("select s from SampleObject s where value = :val").setParameter("val", "21")
ex 3:
entityManager.createNativeQuery("select * from dbo.SampleObject s where value = '21'", SampleObject.class)
but as you can see this is stored as a varchar and IS REQUIRED to remain a string so i need to be able to query by a string
Disclaimer:
I am new to hibernate - very new .... very very new!
I should add in SQL SSMS I can directly query by string
I also tried using one of the suggestions below and for context it didn't resolve
You could use:
entityManager.unwrap(Session.class)
.createQuery("<your query>")
.setParameter("identifier", "3", StringType.INSTANCE);
That implementation works with the exact type that you want to pass.
I have to apologize I had an old connection string
and I was directly querying the current data in ssms and the connection string was grabbing old data in the java
my fault it was working the whole time
walking through the debugger showed old data
thank you for your help

How to read CLOB type to Spring Boot? [duplicate]

I have a table in Database where datatype of a column(STATUS) is CLOB.I need to read that STATUS
create table STATUS_TABLE
(
STATE_ID number(20,0),
STATUS clob
)
I am trying to read CLOB column as below
String getStatus = "SELECT STATUS FROM STATUS_TABLE WHERE STATE_ID="+id;
Query statusResults = session.createSQLQuery(getStatus);
List statusRes = statusResults.list();
if ((statusRes != null) && (statusRes.size() > 0)) {
oracle.sql.CLOB clobValue = (oracle.sql.CLOB) statusRes.get(0);
status = clobValue.getSubString(1, (int) clobValue.length());
log.info("Status->:" + status.toString());
}
And getting the error as
java.lang.ClassCastException: $Proxy194 cannot be cast to oracle.sql.CLOB
How can i read clob data from DB and convert to String ?
Here is the corrected version, and an explanation appears below the code:
Query query = session.createSQLQuery("SELECT STATUS FROM STATUS_TABLE WHERE STATE_ID = :param1");
query.setInt("param1", id);
query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
List statusRes = query.list();
if (statusRes != null) {
for (Object object : statusRes) {
Map row = (Map)object;
java.sql.Clob clobValue = (java.sql.Clob) row.get("STATUS");
status = clobValue.getSubString(1, (int) clobValue.length());
log.info("Status->:" + status.toString());
}
}
Problems I saw with your code:
You were building a raw query string using concatenation. This leaves you vulnerable to SQL injection and other bad things.
For whatever reason you were trying to cast the CLOB to oracle.sql.CLOB. AFAIK JDBC will return a java.sql.Clob
You are performing a native Hibernate query, which will return a list result set whose type is not known at compile time. Therefore, each element in the list represents one record.

How to pass Hashmap into spring data jpa method and use that in update statement?

I would like to update multiple rows of a table using Case clause in the update query.
I have an Map<String, String> which contains values of 2 columns. Key acts as the identifier of the row and the value in the map is the value of the column I want to update.
How can I do this in a spring data JPA #Query?
I would like to achieve something like
#Modifying
#Query("update RequestDetail rd set value = VALUE(:statusDetails) where name='Status' and RequestUuid=KEY(:statusDetails)")
void updateBulkStatus(Map<String, String> statusDetails);
But this is giving the exception - antlr.SemanticException: node did not reference a map.
Goal is to avoid multiple update queries to DB.
What better ways we have to update multiple rows with multiple values to a single column.
You will need to execute something like:
Update RequestDetail rd set rd.value = CASE WHEN (rd.name = :name1) THEN :value1 WHEN (rd.name = :name2) THEN :value2 WHEN (rd.name = :name3) THEN :value3 END
But you will not necessarily know how many items will be in the map, so you will need to generate your query text, like
String sql = "Update RequestDetail rd set CASE ";
int index = 1;
for (Map.Entry<String,String> entry : statusDetails.entrySet()) {
sql += " WHEN (rd.name = :name" + index + ") THEN :value" + (index++) + " ";
}
sql += " END";
You will also need to pass the parameters to your query.

How to include two parameters for jdbctemplate.batchUpdate(String sql, List<Object[]> batchArgs)?

I am trying to perform an UPDATE on a MySQL database where I update only one single column full of values corresponding to the correct index position. Here is my current code:
JdbcTemplate temp = new JdbcTemplate(sqlDataSource);
List<Map<String, Object>> results = temp.queryForList("SELECT last_name FROM actor");
List<Object[]> params = new ArrayList<Object[]>();
for (Map<String, Object> row : results) {
params.add(new Object[]{row.get("last_name"), row.get("actor_id")});
}
String sql = "UPDATE actor SET first_name= ? WHERE actor_id=?";
temp.batchUpdate(sql, params)
In this example, I am trying to update all first names in my table to the last names. My main question is how can I include a parameter for the "SET first_name = ?" as well as the WHERE condition "WHERE actor_id = ?" as well? Is this possible with JdbcTemplate?
I think a simple Google search can solve your problem(s).
If you just look up JdbcTemplate batchUpdate, it should guide you in the right direction.
With that said, have a look at these:
https://www.tutorialspoint.com/springjdbc/springjdbc_jdbctemplate
why spring jdbcTemplate batchUpdate insert row by row

How to insert records faster

I have to read records from CSV file and store them in Mysql database.
I know about "LOAD DATA INFILE" but in my case I have to get single record from file, check if it is in valid format/length etc and then store it in database.
// list to store records from CSV file
ArrayList<String> list = new ArrayList<String>();
//Read one line at a time
while ((nextLine = reader.readNext()) != null)
{
for (String number : nextLine)
{
if (number.length() > 12 && number.startsWith("88"))
{
list.add(number);
} else if (number.length() > 9 && number.startsWith("54"))
{
list.add(number);
}
else if (number.length() > 8 && number.startsWith("99"))
{
list.add(number);
}
else
{
// ....
}
// method to insert data in database
insertInToDatabase(list);
}
}
and method to insert record in db: taken from here
private void insertInToDatabase(ArrayList<String> list)
{
try
{
String query = "INSERT INTO mytable(numbers) VALUES(?)";
prepStm = conn.prepareStatement(query);
for (String test : list)
{
prepStm.setString(1, test);
prepStm.addBatch();// add to batch
prepStm.clearParameters();
}
prepStm.executeBatch();
}
}
This is working, but the rate at which the records are inserting is very slow.
is there any way by which I can insert records faster.
You would need to use: "rewriteBatchedStatement" as that is a MYSQL optimization which attempts to reduce round trips to the server by consolidating the inserts or updates in as few packets as possible.
Please refer to:
https://anonymousbi.wordpress.com/2014/02/11/increase-mysql-output-to-80k-rowssecond-in-pentaho-data-integration/
Also, there are other optimizations as well in that article. Hope this speed up the batching.
EDIT 1:
There is a lucid explanation of this parameter on this site as well: refer to: MySQL and JDBC with rewriteBatchedStatements=true
#Khanna111's answer is good.
I don't know if it helps, but try checking the table engine type. I once encountered the problem in which records are inserting very slow. I changed the engine from InnoDB to MyISAM and insertion becomes very fast.
i think the better approach is to process the csv file with the rules defined and then create another csv out it, and once the output csv is prepared. do load data infile.
it'll be pretty quick.
If you want to insert through your own application create batch query like this and execute to MySQL server.
String query = "INSERT INTO mytable(numbers)
VALUES (0),
(1),
(2),
(3)";

Categories

Resources