Sql query call fails if no record is found - java

I am trying to fetch a string from sql db. I have the following query:
select DISTINCT HARDWARE.NAME
from HARDWARE INNER JOIN
HARDWARE_LINKING
on HARDWARE.ID = HARDWARE_LINKING.ID
where HARDWARE_LINKING.EXTERNALID='5528752'.
Now when there is no record against any id the function call fails.
here is my function code that I am calling to fetch data:
public String search(String externalId) {
String SQL = "select DISTINCT HARDWARE.NAME from HARDWARE INNER JOIN HARDWARE_LINKING on HARDWARE.ID = HARDWARE_LINKING.ID where HARDWARE_LINKING.EXTERNALID=?";
Object[] input = new Object[] {externalId};
String name = jdbcTemplate.queryForObject(SQL,input, String.class);
return name;
}
Is there any way I can return a default value? and sometimes there are multiple values return but I want only single string value to be returned, Is that possible? Thankyou in advance

One method is to put the default into the query itself. Use an aggregation function and COALESCE():
select coalesce(h.NAME, '<default value>') as NAME
from HARDWARE h INNER JOIN
HARDWARE_LINKING hl
on h.ID = hl.ID
where hl.EXTERNALID = '5528752';
An aggregation query with no GROUP BY always returns one row, so this would seem to be more what you are looking for.
Also note that I put table aliases into the query. These make the query easier to write and to read.

You should be able to check name for null or isEmpty and then decide if you should return the name from the query or a default value.
if(name != null && !name.isEmpty()){
return name;
} else {
return "default";
}

Related

How to I remove L from Long field's values in java spring

I put query param for my list services for example:
tablename/list?query=id:10
it is running but I added other param
'personTNo'
tablename/list?query=id:10&personTNo=101035678
id is Integer but personTNo is Long
when I try to this sql returns select * from TABLENAME WHERE personTNo=10L
but this I want to return without 'L' for Long value. It is my code's a bit section in RepositoryCustom class
public List<TABLENAME> getTable(Specification aTablenameSpec) {
CriteriaBuilder builder = mEntityManager.getCriteriaBuilder();
CriteriaQuery<Object> query = builder.createQuery();
Root<TABLENAME> root = query.from(TABLENAME.class);
String queryWhere = null;
org.hibernate.query.Query hibernateQuery = null;
Predicate predicate = aTablenameSpec.toPredicate(root, query, builder);
if (predicate != null) {
query.where(predicate);
query.select(root);
TypedQuery<Object> typedQuery = mEntityManager.createQuery(query);
hibernateQuery = typedQuery.unwrap(org.hibernate.query.Query.class);
String queryString = hibernateQuery.getQueryString();
This row returns with L result, How to remove 'L' value in sql
Use INTEGER() function in the sql query. You can also try CAST() or CONVERT() functions in the query
Based on the problem description and code, it seems safe to assume the tech stack includes: JPA and Spring Data JPA.
And I understand that you want to remove the Long value L suffixes, but it's not clear if that's because the suffixes are causing a problem or exactly why you want the suffixes removed.
I only say that because the example query string appears to be a valid JPA query:
select * from TABLENAME WHERE personTNo = 10L
JPA support for the use of literal values in queries includes support for standard Java numeric (integer/long/float/double) literal value syntax.
Which means the L suffix on the literal Long value of personTNo, as defined in your query (10L), is legitimate, valid, and should not cause a problem.
Please let me know if I've missed the point, made an incorrect assumption, or overlooked something, and I will follow up.

SQL in java return wrong data

I have a java method like this one below:
public String qE (String query, String selector) throws QSLException, IOException{
//I get my sqlQuery from properties
String sqlQuery = properties.getPRoperty(query);
//sqlQuery = SELECT count(?) FROM employees WHERE ? is not null
PreparedStatement ps = conn.preparedStatement(sqlQuery);
ps.setFetchSize(100);
ps.setString(1,selector);
ps.setString(2,selector);
ResultSet rs = ps.executeQuery();
String rs = "";
while(rs.next()){
queryValue = rs.getString(1);
}
return queryValue;
}
When I run it with parameters
qe(employees, second_name)
then this query should be executed:
SELECT count(second_name)
FROM employees
WHERE second_name is not null
The problem is that non of employees has second name and I should get 0 and the whole method should return 0 but I always get diffrent number greater than zero.
Can anyone tell me why this doesn't return 0 but always diffrent number like i.e. 2399?
A ? represents a value not an object name, so it is equivalent to using
SELECT count('second_name')
FROM employees
WHERE 'second_name' is not null
Which is always true and is always counted. In other words, your query counts all rows in table employees.
You cannot use parameters to parameterize object names. If you really need to do this dynamically, you will need to construct the query dynamically (by concatenating the name in the query string). Just be sure to guard yourself against SQL injection if you do that (eg by checking the name against a white list or comparing explicitly to the database metadata).

Using a NamedParamterJdbcTemplate object to specify a mysql field and value to query on

I am currently in the process of learning the Java Spring Framework, and I am having difficulty understanding why the following query is failing to return any results from the database.
I am ultimately trying to create a where method in my OffersDAO class that allows my to query on a specific field, for a specific value.
public List<Offer> where(String field, String value){
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("field", field);
params.addValue("value", value);
String sql = "select * from offers where :field = :value";
return jdbc.query(sql, params, new RowMapper<Offer>(){
public Offer mapRow(ResultSet rs, int arg1) throws SQLException {
Offer offer = new Offer();
offer.setId(rs.getInt("id"));
offer.setName(rs.getString("name"));
offer.setText(rs.getString("text"));
offer.setEmail(rs.getString("email"));
return offer;
}
});
}
I am able to successfully query the database for results when I specify the field explicitly, as follows:
String sql = "select * from offers where name = :value";
Obviously there is something wrong with specifying the field name dynamically. My guess is it is most likely due to the fact that the field key is being inserted as a mysql string (with ''), when in fact mysql expects a column name for the :field placeholder.
My questions are as follows:
Is there a way to accomplish what I am attempting to do above, using the jdbc NamedParameterJdbcTemplate class?
If I cannot accomplish the above, by what means can I?
Thank you
Edit: No exceptions are thrown. In the case when I am attempting to supply the column name, a empty result set is returned.
You can't specify the field name in a parameter - only the field value. Since you know the DB schema when you're writing the code, this shouldn't be much of a problem.
What about include all possible fields in the filter but restricting their usage by field name param. Like this:
select * from offers where
('name'=:field and name = :value)
OR
('field2'=:field and field2 = :value)
OR
('field3'=:field and field3 = :value)
I don't know how You can implement it with spring (I mean use variable column names) but I can suggest to use the following principle.
Keep your query like template:
String sql = "select * from offers where ##field = :value";
And every time before execution replace ##value parameter with the column You want.
And then You are gone.

How to process ResultSet you know has only one record in it

I'm struggling with a homework assignment and am getting hung up on some SQL queries.
My query is interrogating an inventory database for the quantity of some item. The query requests the column with the name quantity_in_stock from the table, given the primary key.
I have initialized some prepared statements. This is the one I'm using here:
stmtFindColumn = Database.getConnection().prepareStatement(String.format("select ? from %s where %s = ?",
INVENTORY_TABLE_NAME, SKU) );
Now a separate method is called. I pass it a static const QTY_IN_STOCK, which is defined as "quantity_in_stock" and the item's SKU number, which is the primary key in the table.
private int getIntegerFromTable(String column, String key) {
int toReturn = 0;
try {
// Complete the prepared statement
stmtFindColumn.setString(1, column);
stmtFindColumn.setString(2, key);
ResultSet result = stmtFindColumn.executeQuery();
toReturn = result.getInt(column);
} catch (SQLException e) {
LOG.error(e.getMessage());
e.printStackTrace();
}
return toReturn;
}
When I run the query I get an sql exception that tells me: Invalid column name quantity_in_stock.
I have tried using a while loop processing result.next() and get the same error. I can't find any examples of how to properly get the results when you know only a single record is being returned.
Help!
EDIT: OK, I've found that part of my problem is I'm not getting a result set, where I should expect one. Any ideas?
UPDATE: I've tested my code, using a garden variety statement and a plain string query instead and it works just fine. So the problem is in my use of the prepared statement. Can someone check if I'm using the ? wildcards correctly? Thanks!
as far as i know, the column name may not be a parameter ...
DarkSquirrel42 is right -- you can't replace the column list of the select using a ? parameter marker. Instead, you can String.format that into place too, for example.
bad:
*select ? from INVENTORY_TABLE_NAME where SKU = ?
good:
select QUANTITY_IN_STOCK from INVENTORY_TABLE_NAME where SKU = ?

Dynamic Hibernate Query

I have a method that I use to return a dynamic query. This method is shown below
public Query getLastId(String sProvider)
{
String serviceProvider = sProvider.toLowerCase();
String query2 = "SELECT MAX(:serviceProvider.id) " +
" FROM :sProvider :serviceProvider ";
return em.createQuery(query2)
.setParameter("sProvider", sProvider)
.setParameter("serviceProvider", serviceProvider);
}
I want this method to return this
SELECT MAX(multichoice.id) FROM Multichoice multichoice
when I call the method like this
getLastId("Multichoice");
Please how do I write the query variable to return the answer?
To do this task you can use Criteria object model and projections to run your query over different types:
Take a look at this article (15.7. Projections, aggregation and grouping)
here is the code :
List results = session.createCriteria(class)
.setProjection( Projections.max("id"))
.list();
Then instead of a string you should send a class to your method.

Categories