How does oracle db internally store 'NULL' [duplicate] - java

In Java I'm trying to test for a null value, from a ResultSet, where the column is being cast to a primitive int type.
int iVal;
ResultSet rs = magicallyAppearingStmt.executeQuery(query);
if (rs.next()) {
if (rs.getObject("ID_PARENT") != null && !rs.wasNull()) {
iVal = rs.getInt("ID_PARENT");
}
}
From the code fragment above, is there a better way to do this, and I assume that the second wasNull() test is redundant?
Educate us, and Thanks

The default for ResultSet.getInt when the field value is NULL is to return 0, which is also the default value for your iVal declaration. In which case your test is completely redundant.
If you actually want to do something different if the field value is NULL, I suggest:
int iVal = 0;
ResultSet rs = magicallyAppearingStmt.executeQuery(query);
if (rs.next()) {
iVal = rs.getInt("ID_PARENT");
if (rs.wasNull()) {
// handle NULL field value
}
}
(Edited as #martin comments below; the OP code as written would not compile because iVal is not initialised)

Another solution:
public class DaoTools {
static public Integer getInteger(ResultSet rs, String strColName) throws SQLException {
int nValue = rs.getInt(strColName);
return rs.wasNull() ? null : nValue;
}
}

Just check if the field is null or not using ResultSet#getObject(). Substitute -1 with whatever null-case value you want.
int foo = resultSet.getObject("foo") != null ? resultSet.getInt("foo") : -1;
Or, if you can guarantee that you use the right DB column type so that ResultSet#getObject() really returns an Integer (and thus not Long, Short or Byte), then you can also just typecast it to an Integer.
Integer foo = (Integer) resultSet.getObject("foo");

I think, it is redundant. rs.getObject("ID_PARENT") should return an Integer object or null, if the column value actually was NULL. So it should even be possible to do something like:
if (rs.next()) {
Integer idParent = (Integer) rs.getObject("ID_PARENT");
if (idParent != null) {
iVal = idParent; // works for Java 1.5+
} else {
// handle this case
}
}

AFAIK you can simply use
iVal = rs.getInt("ID_PARENT");
if (rs.wasNull()) {
// do somthing interesting to handle this situation
}
even if it is NULL.

Just an update with Java Generics.
You could create an utility method to retrieve an optional value of any Java type from a given ResultSet, previously casted.
Unfortunately, getObject(columnName, Class) does not return null, but the default value for given Java type, so 2 calls are required
public <T> T getOptionalValue(final ResultSet rs, final String columnName, final Class<T> clazz) throws SQLException {
final T value = rs.getObject(columnName, clazz);
return rs.wasNull() ? null : value;
}
In this example, your code could look like below:
final Integer columnValue = getOptionalValue(rs, Integer.class);
if (columnValue == null) {
//null handling
} else {
//use int value of columnValue with autoboxing
}
Happy to get feedback

You can call this method using the resultSet and the column name having Number type. It will either return the Integer value, or null. There will be no zeros returned for empty value in the database
private Integer getIntWithNullCheck(ResultSet rset, String columnName) {
try {
Integer value = rset.getInt(columnName);
return rset.wasNull() ? null : value;
} catch (Exception e) {
return null;
}
}

For convenience, you can create a wrapper class around ResultSet that returns null values when ResultSet ordinarily would not.
public final class ResultSetWrapper {
private final ResultSet rs;
public ResultSetWrapper(ResultSet rs) {
this.rs = rs;
}
public ResultSet getResultSet() {
return rs;
}
public Boolean getBoolean(String label) throws SQLException {
final boolean b = rs.getBoolean(label);
if (rs.wasNull()) {
return null;
}
return b;
}
public Byte getByte(String label) throws SQLException {
final byte b = rs.getByte(label);
if (rs.wasNull()) {
return null;
}
return b;
}
// ...
}

Just in case someone comes here while programming in Kotlin (as I did), the answer suggested by BalusC works fine. Just be aware that Short and Float are instantiated as Integer and Double (respectively) inside ResultSet, and we should cast them to the correct type after calling getObject(). In my case the final code was:
when {
propKClass.isSubclassOf(Int::class) -> rs.getObject(colName) as Int?
propKClass.isSubclassOf(Short::class) -> (rs.getObject(colName) as Int?)?.toShort()
propKClass.isSubclassOf(Long::class) -> rs.getObject(colName) as Long?
propKClass.isSubclassOf(Boolean::class) -> rs.getObject(colName) as Boolean?
propKClass.isSubclassOf(Double::class) -> rs.getObject(colName) as Double?
propKClass.isSubclassOf(Float::class) -> (rs.getObject(colName) as Double?)?.toFloat()
else -> rs.getString(colName)
}

With java 8 you can do this:
Long nVal = Optional.ofNullable(resultSet.getBigDecimal("col_name"))
.map(BigDecimal::longValue).orElse(null));
In that case you ensure that the nVal will be null (and not zero) if the SQL value is NULL

If you want an alternative to calling ResultSet.wasNull() you can use getObject() and cast to the correct type.
Long val = (Long)rs.getObject(pos++);
You can also set null values in a Statement with setObject().
pstmt.setObject(pos++, null);

In Kotlin I would just solve it once and be done with the issue forever with this:
fun <K : Any> ResultSet.getNullable(columnLabel: String, type: KClass<K>): K? =
this.getObject(columnLabel, type.java)
So later you can just do this:
rs.getNullable("ID_PARENT", Int::class)
I guess if you want you could also do this too
fun <K> ResultSet.getNullable(columnLabel: String, type: Class<K>): K? =
this.getObject(columnLabel, type)
So you can just do this:
rs.getNullable("ID_PARENT", Int::class.java)
Or better still make both methods available if you happen to be dealing with developers that can't agree on even the simplest of things.
fun <K : Any> ResultSet.getNullable(columnLabel: String, type: KClass<K>): K? =
this.getNullable(columnLabel, type.java)
fun <K> ResultSet.getNullable(columnLabel: String, type: Class<K>): K? =
this.getObject(columnLabel, type)
Edit: if the library is still being fussy you can finally do something like:
rs.getNullable("ID_PARENT", String::class)?.let {FOO.valueOf(it) }

Another nice way of checking, if you have control the SQL, is to add a default value in the query itself for your int column. Then just check for that value.
e.g for an Oracle database, use NVL
SELECT NVL(ID_PARENT, -999) FROM TABLE_NAME;
then check
if (rs.getInt('ID_PARENT') != -999)
{
}
Of course this also is under the assumption that there is a value that wouldn't normally be found in the column.

Related

how to send null to an integer field - JAVA REST

preparedStatement1.setInt(1,jsonObject1.getInteger("userid"));
database is mySQL. My userID field in the database is int type and is an optional field.
How can I easily pass NULL into this from json?
{"userid":null} is getting me error.
The way you set an int field to null is with setNull rather than setInt. setInt takes an int argument, so it cannot receive null as a value.
In your case you can use this to cover the case where the field may or may not be null:
Integer userId = jsonObject1.getInteger("userid");
if (userId==null) {
preparedStatement1.setNull(1, Types.INTEGER);
} else {
preparedStatement1.setInt(1, userId);
}
If you wanted you could write a helper method to do this more conveniently.
public static void setInteger(PreparedStatement stmt, int index, Integer value) {
if (value==null) {
stmt.setNull(index, Types.INTEGER);
} else {
stmt.setInt(index, value);
}
}
then in context your operation is back to one line:
setInteger(preparedStatement1, 1, jsonObject1.getInteger("userid"));

calling function should return default value, if object (or any function result) is null

Is it possible to wrap following code in a reusable function?
EDIT: this is just an example, I want a working solution for ALL recursion depths
what I want is that following code is generated:
if (MyObject o == null ||
o.getSubObject() == null ||
o..getSubObject().getSubSubObject() == null /*||
... */)
return defaultValue;
return o.getSubObject().getSubObject()/*...*/.getDesiredValue();
by calling something like
Object defaultValue = null;
Object result = NullSafeCall(o.getSubObject().getSubObject()/*...*/.getDesiredValue(), defaultValue);
The seond code block is just an idea, I don't care how it looks like, all I want is that I, if desired, can avoid all the null checks before calling a deeper function...
Injection could do this propably, but is there no other/easier solution? Never looked at injection before yet...
EDIT2: example in another language: http://groovy.codehaus.org/Operators#Operators-SafeNavigationOperator
Not really, any code you would write this way would look horrible and/or use very slow reflection. Unless you use an actual Java preprocessor that can understand and change the code you've written.
A better (but associated with quite a bit of refactoring) approach would be to make sure that the values in question cannot possibly be null. For example, you could modify the individual accessors (getSubObject(), getDesiredValue()) to never return null in the first place: make them return default values. The accessors on the default values return default values in turn.
Java8 helps to get the closest you'll get to your syntax with decent performance I suspect;
// Evaluate with default 5 if anything returns null.
int result = Optional.eval(5, o, x->x.getSubObject(), x->x.getDesiredValue());
This can be done with this utility class;
class Optional {
public static <T, Tdef, T1> Tdef eval(Tdef def, T input, Function<T,T1> fn1,
Function<T1, Tdef> fn2)
{
if(input == null) return def;
T1 res1 = fn1.apply(input);
if(res1 == null) return def;
return fn2.apply(res1);
}
}
Sadly, you'll need a separate eval() defined per number of method calls in the chain, so you may want to define a few, but compile time type safe and reusable with just about any calls/types.
You can do something like this
public static Object NullSafeCall(MyObject o,Object defaultValue){
if ( o == null || o.getSubObject() == null)
{
return defaultValue;
}
else
{
return o.getSubObject().getDesiredValue();
}
}
Now you can call this method as follows
Object result = NullSafeCall(o, defaultValue);
i would suggest just replace
Object result = NullSafeCall(o.getSubObject().getDesiredValue(), defaultValue);
by the
Object result = (o == null || o.subObject == null) ? defaultVlue : o.getSubObject().getDesiredValue();
Create method only if you can reuse it......
What you want is not possible. It is essential to understand that using this syntax: Object result = NullSafeCall(o.getSubObject().getSubObject() ...); the part of o.getSubObject().getSubObject() will be evaluated before any control passes to the function/method thus throwing the exception.
It is required to have some type of context before executing such code. The closest to this I could think of, can be done using anonymous inner classes like the example below:
// intended to be implemented by an anonymous inner class
interface NullSafeOperation<T> {
public T executeSafely();
};
// our executor that executes operations safely
public static class NullSafeExecutor<T> {
public NullSafeExecutor() {}
public T execute(T defaultValue, NullSafeOperation<T> nso) {
T result = defaultValue;
try {
result = nso.executeSafely();
} catch(NullPointerException e) {
// ignore
}
return result;
}
// utility method to create a new instance and execute in one step
public static <T> T executeOperation(T defaultValue, NullSafeOperation<T> nso) {
NullSafeExecutor<T> e = new NullSafeExecutor<T>();
T result = e.execute(defaultValue, nso);
return result;
}
}
public static void main(String[] args) {
final String aNullString = null;
String result = NullSafeExecutor.executeOperation("MyDefault", new NullSafeOperation<String>() {
#Override
public String executeSafely() {
// trying to call a method on a null string
// it will throw NullPointerException but it will be catched by the executor
return aNullString.trim();
}
});
System.out.println("Output = " + result); // prints: Output = MyDefault
}

Returning a value from a void method in Java

I have a method :
public void dbQuery(String query, String what) {
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(what.equals("temp_table")) {
String temporary_table = rs.getString("table_name_temp");
System.out.println(temporary_table);
return;
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
}
}
String query = "EXEC temptables.dbo.create_temp_cdr 'SIP'";
String temporary_table = db.dbQuery(query,"temp_table");
How do I get the return of a void to use it in another db.dbQuery() ?
PS : I need a value from dbQuery() so I can construct another query to call dbQuery() again
How do I get the return of a void to use it in another db.dbQuery() ?
What do you mean by "the return of a void"? If you mean "the return value" then there isn't one - that's the point of the method being declared as void.
If you want to return a value, then don't make it a void method... given this:
String temporary_table = db.dbQuery(query,"temp_table");
it looks like you just want to change dbQuery to return String. Note that you'll need to work out what to return if what isn't temp_table. (You should also fix your exception handling - just printing out the stack trace to stdout and then continuing regardless is almost never the right approach.)
You can either have your method not be void, and have a return type, then you can have the line
return temporary_table;
which would return the temporary_table variable.
Another way would be to pass by reference to the method. For example, you can pass a StringBuilder object to the method. Any changes to this object in the method will then also apply after the method has returned.
public void addToString(StringBuilder query, String toAdd) {
query.append(toAdd);
}
A call to this method of
StringBuilder query = new StringBuilder("start");
System.out.println(query.toString());
addToString(query, "end");
System.out.println(query.toString());
would have the output of:
start
startend
You can't return a value from a method that is defined as void - by definition this means it doesn't return any value.
If you see a return; statement in a void method, it basically means that this will end the current method and return processing back to the caller.
I'd make your method string instead of bool. Void won't return anything ever.
A void method is something that does not return anything.
But, your requirement seems like you have to use value generated in this method in the previous layer.
One obvious solution for this is to change it's return type from void to String.
But, if you don't want to do this , simply pass one more string parameter to your method. String is an object, so when you are passing it to a method, you are actually passing reference of that object to it. Simply set your generated value in this string and you will be able to access it in previous layer with that string variable(It's sort of similar to Pass by Reference in C).
I hope this workaround will solve your problem.
Please correct me if I am wrong.
In fact he wants to have something similar like functions in VB or so.
First, create your void as usual.
private Void getheightoflistview(ListView nameOfListView){
//do whatever you want to do
int numberOfItems = nameOfListView.getCount();
//You want to return the numberOfItems
}
So if you want to return an Integer value, just replace the Void with Integer
private Integer getheightoflistview(ListView nameOfListView){
//do whatever you want to do
int numberOfItems = nameOfListView.getCount();
//You want to return the numberOfItems
return numberOfItems; //this is the Integer you want to return
}
and add the return value

How do I cast from int to generic type Integer?

I'm relatively new to Java and am used to generics in C# so have struggled a bit with this code. Basically I want a generic method for getting a stored Android preference by key and this code, albeit ugly, works for a Boolean but not an Integer, when it blows up with a ClassCastException. Can anyone tell me why this is wrong and maybe help me improve the whole routine (using wildcards?)?
public static <T> T getPreference(Class<T> argType, String prefKey, T defaultValue,
SharedPreferences sharedPreferences) {
...
try {
if (argType == Boolean.class) {
Boolean def = (Boolean) defaultValue;
return argType.cast(sharedPreferences.getBoolean(prefKey, def));
} else if (argType == Integer.class) {
Integer def = (Integer) defaultValue;
return argType.cast(new Integer(sharedPreferences.getInt(prefKey, def)));
} else {
AppGlobal.logWarning("getPreference: Unknown type '%s' for preference '%s'. Returning default value.",
argType.getName(), prefKey);
return defaultValue;
}
} catch (ClassCastException e) {
AppGlobal.logError("Cast exception when reading pref %s. Using default value.", prefKey);
return defaultValue;
}
}
My calling code is:
mAccuracy = GlobalPreferences.getPreference(Integer.class, prefKey, mAccuracy, sharedPreferences);
Here is the Android code for getInt():
public int getInt(String key, int defValue) {
synchronized (this) {
Integer v = (Integer)mMap.get(key);
return v != null ? v : defValue;
}
}
I've tried various ways - using the native int, casting to an Integer, but nothing works.
May I suggest:
Integer i = new Integer(42);
It turns out the preference I'm trying to read is stored as a string so the cast exception is coming from inside the Android code not mine. Thanks for your help. But as I am a Java-newbie, if you think there is anything generally wrong with my routine, please teach me a better way.
Try defining a bunch of functions with the same name that take a different type for the default, and let the compiler figure it out. Java really ties your hands when working with types, especially primitive types.
public function int getPreference( String key , int missing ) { return sharedPreferences.getInt( key , missing ); }
public function boolean getPreference( String key , boolean missing ) { return sharedPreferences.getBoolean( key , missing ); }
public function String getPreference( String key , String missing ) { return sharedPreferences.getString( key , missing ); }
Edit:
If you are trying to get an object (not primitive) regardless of the type, you can use:
public function Object getPreference( String key , Object missing ) { return sharedpreferences.contains( key ) ? sharedPreferences.getAll().get( key ) : missing; }
If you are trying to get a specific type like int regardless of what is stored, you can use:
public function int getPreference( String key , int missing ) {
int result = missing;
Object value = sharedpreferences.contains( key ) ? sharedPreferences.getAll().get( key ) : null;
if ( value instanceof Integer ) result = ((Integer)value).intValue();
if ( value instanceof Boolean ) result = ((Boolean)value).booleanValue() ? 1 : 0;
// repeat for every other primitive wrapper type you care about
return result;
}
If you are trying to get a result only if it is a certain type, you can use something like:
public function Object getPreference( Class inRequire , String key , Object missing ) {
Object value = sharedpreferences.contains( key ) ? sharedPreferences.getAll().get( key ) : null;
if ( !( value instanceof inRequire ) ) {
value = null;
}
return ( value == null ) ? missing : value;
}

JPA getSingleResult() or null

I have an insertOrUpdate method which inserts an Entity when it doesn't exist or update it if it does. To enable this, I have to findByIdAndForeignKey, if it returned null insert if not then update. The problem is how do I check if it exists? So I tried getSingleResult. But it throws an exception if the
public Profile findByUserNameAndPropertyName(String userName, String propertyName) {
String namedQuery = Profile.class.getSimpleName() + ".findByUserNameAndPropertyName";
Query query = entityManager.createNamedQuery(namedQuery);
query.setParameter("name", userName);
query.setParameter("propName", propertyName);
Object result = query.getSingleResult();
if (result == null) return null;
return (Profile) result;
}
but getSingleResult throws an Exception.
Thanks
Throwing an exception is how getSingleResult() indicates it can't be found. Personally I can't stand this kind of API. It forces spurious exception handling for no real benefit. You just have to wrap the code in a try-catch block.
Alternatively you can query for a list and see if its empty. That doesn't throw an exception. Actually since you're not doing a primary key lookup technically there could be multiple results (even if one, both or the combination of your foreign keys or constraints makes this impossible in practice) so this is probably the more appropriate solution.
Try this in Java 8:
Optional first = query.getResultList().stream().findFirst();
I encapsulated the logic in the following helper method.
public class JpaResultHelper {
public static Object getSingleResultOrNull(Query query){
List results = query.getResultList();
if (results.isEmpty()) return null;
else if (results.size() == 1) return results.get(0);
throw new NonUniqueResultException();
}
}
Here's a good option for doing this:
public static <T> T getSingleResult(TypedQuery<T> query) {
query.setMaxResults(1);
List<T> list = query.getResultList();
if (list == null || list.isEmpty()) {
return null;
}
return list.get(0);
}
I've done (in Java 8):
query.getResultList().stream().findFirst().orElse(null);
From JPA 2.2, instead of .getResultList() and checking if list is empty or creating a stream you can return stream and take first element.
.getResultStream()
.findFirst()
.orElse(null);
Spring has a utility method for this:
TypedQuery<Profile> query = em.createNamedQuery(namedQuery, Profile.class);
...
return org.springframework.dao.support.DataAccessUtils.singleResult(query.getResultList());
If you wish to use the try/catch mechanism to handle this problem.. then it can be used to act like if/else. I used the try/catch to add a new record when I didn't find an existing one.
try { //if part
record = query.getSingleResult();
//use the record from the fetched result.
}
catch(NoResultException e){ //else part
//create a new record.
record = new Record();
//.........
entityManager.persist(record);
}
Here's a typed/generics version, based on Rodrigo IronMan's implementation:
public static <T> T getSingleResultOrNull(TypedQuery<T> query) {
query.setMaxResults(1);
List<T> list = query.getResultList();
if (list.isEmpty()) {
return null;
}
return list.get(0);
}
There is an alternative which I would recommend:
Query query = em.createQuery("your query");
List<Element> elementList = query.getResultList();
return CollectionUtils.isEmpty(elementList ) ? null : elementList.get(0);
This safeguards against Null Pointer Exception, guarantees only 1 result is returned.
So don't do that!
You have two options:
Run a selection to obtain the COUNT of your result set, and only pull in the data if this count is non-zero; or
Use the other kind of query (that gets a result set) and check if it has 0 or more results. It should have 1, so pull that out of your result collection and you're done.
I'd go with the second suggestion, in agreement with Cletus. It gives better performance than (potentially) 2 queries. Also less work.
Combining the useful bits of the existing answers (limiting the number of results, checking that the result is unique) and using the estabilshed method name (Hibernate), we get:
/**
* Return a single instance that matches the query, or null if the query returns no results.
*
* #param query query (required)
* #param <T> result record type
* #return record or null
*/
public static <T> T uniqueResult(#NotNull TypedQuery<T> query) {
List<T> results = query.setMaxResults(2).getResultList();
if (results.size() > 1) throw new NonUniqueResultException();
return results.isEmpty() ? null : results.get(0);
}
The undocumented method uniqueResultOptional in org.hibernate.query.Query should do the trick. Instead of having to catch a NoResultException you can just call query.uniqueResultOptional().orElse(null).
I solved this by using List<?> myList = query.getResultList(); and checking if myList.size() equals to zero.
Look this code :
return query.getResultList().stream().findFirst().orElse(null);
When findFirst() is called maybe can be throwed a NullPointerException.
the best aproach is:
return query.getResultList().stream().filter(Objects::nonNull).findFirst().orElse(null);
Here's the same logic as others suggested (get the resultList, return its only element or null), using Google Guava and a TypedQuery.
public static <T> getSingleResultOrNull(final TypedQuery<T> query) {
return Iterables.getOnlyElement(query.getResultList(), null);
}
Note that Guava will return the unintuitive IllegalArgumentException if the result set has more than one result. (The exception makes sense to clients of getOnlyElement(), as it takes the result list as its argument, but is less understandable to clients of getSingleResultOrNull().)
Here's another extension, this time in Scala.
customerQuery.getSingleOrNone match {
case Some(c) => // ...
case None => // ...
}
With this pimp:
import javax.persistence.{NonUniqueResultException, TypedQuery}
import scala.collection.JavaConversions._
object Implicits {
class RichTypedQuery[T](q: TypedQuery[T]) {
def getSingleOrNone : Option[T] = {
val results = q.setMaxResults(2).getResultList
if (results.isEmpty)
None
else if (results.size == 1)
Some(results.head)
else
throw new NonUniqueResultException()
}
}
implicit def query2RichQuery[T](q: TypedQuery[T]) = new RichTypedQuery[T](q)
}
So all of the "try to rewrite without an exception" solution in this page has a minor problem. Either its not throwing NonUnique exception, nor throw it in some wrong cases too (see below).
I think the proper solution is (maybe) this:
public static <L> L getSingleResultOrNull(TypedQuery<L> query) {
List<L> results = query.getResultList();
L foundEntity = null;
if(!results.isEmpty()) {
foundEntity = results.get(0);
}
if(results.size() > 1) {
for(L result : results) {
if(result != foundEntity) {
throw new NonUniqueResultException();
}
}
}
return foundEntity;
}
Its returning with null if there is 0 element in the list, returning nonunique if there are different elements in the list, but not returning nonunique when one of your select is not properly designed and returns the same object more then one times.
Feel free to comment.
I achieved this by getting a result list then checking if it is empty
public boolean exist(String value) {
List<Object> options = getEntityManager().createNamedQuery("AppUsers.findByEmail").setParameter('email', value).getResultList();
return !options.isEmpty();
}
It is so annoying that getSingleResult() throws exceptions
Throws:
NoResultException - if there is no result
NonUniqueResultException - if more than one result
and some other exception that you can get more info on from their documentation
I prefer #Serafins answer if you can use the new JPA features, but this is one fairly straight forward way to do it which I'm surprised hasn't been mentioned here before:
try {
return (Profile) query.getSingleResult();
} catch (NoResultException ignore) {
return null;
}
`public Example validate(String param1) {
// TODO Auto-generated method stub
Example example = new Example();
Query query =null;
Object[] myResult =null;
try {
query = sessionFactory.getCurrentSession()
.createQuery("select column from table where
column=:p_param1");
query.setParameter("p_param1",param1);
}
myResult = (Object[])query.getSingleResult();//As your problem occurs here where the query has no records it is throwing an exception
String obj1 = (String) myResult[0];
String obj2 = (String) myResult[1];
example.setobj1(ISSUtil.convertNullToSpace(obj1))
example.setobj2(ISSUtil.convertNullToSpace(obj2));
return example;
}catch(Exception e) {
e.printStackTrace();
example.setobj1(ISSUtil.convertNullToSpace(""));//setting
objects to "" in exception block
example.setobj1(ISSUtil.convertNullToSpace(""));
}
return example;
}`
Answer : Obviously when there is no records getsingleresult will throw an exception i have handled it by setting the objects to "" in the exception block even though it enter the exception you JSON object will set to ""/empty
Hope this is not a perfect answer but it might help
If some needs to modify my code more precisely and correct me always welcome.
Thats works to me:
Optional<Object> opt = Optional.ofNullable(nativeQuery.getSingleResult());
return opt.isPresent() ? opt.get() : null;

Categories