if (specialmarkId != null) {.....} got ignored - java

I am using auto generated JPAController of Netbeans 8 using Java 1.8.
public void create(Physical physical) {
if (physical.getTalentCollection() == null) {
physical.setTalentCollection(new ArrayList<Talent>());
}
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Specialmark specialmarkId = physical.getSpecialmarkId();
System.out.println(specialmarkId+ "...nullValue");
if (specialmarkId != null) {
System.out.println(specialmarkId+ "...ain't right");
specialmarkId = em.getReference(specialmarkId.getClass(), specialmarkId.getId());
physical.setSpecialmarkId(specialmarkId);
}
.....
}
During physical object creation, Specialmark (part of physical object) is an optional.
It can have a value or be null.
Specialmark in the table physical allows you to have null values.
When Specialmark is null, the if (specialmarkId != null) {...} should skipped. Instead, it got ignored and proceed.
the error message is
"... An instance of a null PK has been incorrectly provided for this find operation.
at db.jpa.PhysicalJpaController.create(PhysicalJpaController.java:57)"
System.out.println(specialmarkId+ "...nullValue");
output "null...nullValue" it shows specialmarkId value is null
System.out.println(specialmarkId+ "...ain't right");
Output "null...ain't right" shows if (specialmarkId != null) {...} has been ignored even specialmarkId is null.
Why does (specialmarkId != null) {...} not work?

I guess specialmarkId is not really null, but specialmarkId.toString() is overwriten for it to return the string "null".
Instead of
System.out.println(specialmarkId+ "...nullValue");
try something like
System.out.println((specialmarkId != null?
specialmarkId.toString() + "(not null)": "(this IS REALLY NULL)")
+ "...nullValue");

Related

Operators in a table

There are 7 rows of output for table, how can I modify this so row 6 displays either of the three providers.
I tried something like this :
template.getProvider2() != null || template.getProvider3() != null ||
template.getProvider1() != null ?
template.getProvider2().getBusinessUnit(): "" ||
template.getProvider3().getBusinessUnit(): "" ||
template.getProvider3().getBusinessUnit(): "",
which gives me an error of StringBuilder not accepting the OR operator,
I'd appreciate any help on this.
Thanks
Here is my code:
public GetEmailTemplatesResponse getEmailTemplates() throws Exception {
StringBuilder stringBuilder = new StringBuilder();
String tableRow = "<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>";
Map<String, EmailTemplate> templates = templateRedisCacheReader.getTemplatesByCacheType(CacheType.EMAIL_TEMPLATE);
templates.values()
.forEach(template -> stringBuilder.append(String.format(tableRow,
template.getTemplateId(),
template.getProvider1() != null ? template.getProvider1().getId() : "",
template.getProvider2() != null ? template.getProvider2().getId() : "",
template.getProvider3() != null ? template.getProvider3().getId() : "",
template.getEnv(),
template.getProvider2() != null ? template.getProvider2().getBusinessUnit(): "", // <--
template.getPriority()))
);
I tried to check if all the providers are null and if one of them is not null , then display bussiness unit for that provider
There's a function commonly used in SQL that returns the first non-null parameter called "coalesce". You could write a Java equivalent of that.
Object coalesce(Object... objects) {
for (Object obj : objects) {
if(obj != null) return obj;
}
return null;
}
...
Provider firstNonNullTemplate=(Provider) coalesce(template.getProvider1(), template.getProvider2(), template.getProvider3());

Bulk update with hibernate

Currently we have two endpoints in our API :
One to update one entity
An various ones to update one field of a Collection of entity
The first one only use saveOrUpdate method of hibernate
While the second one create a custom HQL query to update the desired field.
I would like to make only one endpoint. The idea would be receiving a payload representing the entity. Each field of the entity that are not null would be field that we should update.
I wanted to do that in this way, but it doesn't work as setParameter could set parameters that are not in the String.
Any ideas ?
public long update(Collection<Long> toUpdate, SaleItemDTO newValues) {
if (toUpdate.size() == 0) return 0;
StringBuilder hql = new StringBuilder("UPDATE SaleItem SET ");
if (!newValues.getName().isEmpty()) hql.append("name = :name,");
if (newValues.getPrice() != null) hql.append("price = :price,");
if (newValues.getTag() != null) hql.append("tag = :tag,");
if (newValues.getCategory() != null) hql.append("category.id = :categoryId,");
if (newValues.isRecurringSale() != null) hql.append("isRecurringSale = :isRecurringSale,");
if (newValues.isCallProduct() != null) hql.append("callProduct = :callProduct,");
hql.deleteCharAt(hql.length() - 1).append(" WHERE id in :ids");
return this.sessionFactory
.getCurrentSession()
.createQuery(hql.toString())
.setParameter("name", newValues.getName())
.setParameter("price", newValues.getPrice())
.setParameter("tag", newValues.getTag())
.setParameter("categoryId", newValues.getCategory().getId())
.setParameter("isRecurringSale", newValues.isRecurringSale())
.setParameter("callProduct", newValues.isCallProduct())
.setParameter("ids", toUpdate)
.executeUpdate();
}
Okay, fix it with Criteria API
public long update(Collection<Long> toUpdate, SaleItemDTO newValues) {
if (toUpdate.size() == 0) return 0;
CriteriaBuilder criteriaBuilder = this.sessionFactory.getCriteriaBuilder();
// create update
CriteriaUpdate<SaleItem> update = criteriaBuilder.createCriteriaUpdate(SaleItem.class);
// set the root class
Root<SaleItem> saleItemRoot = update.from(SaleItem.class);
// set update and where clause
if (!newValues.getName().isEmpty()) update.set("name", newValues.getName());
if (newValues.getPrice() != null) update.set("price", newValues.getPrice());
//if (newValues.getCategory() != null) update.set("category.id", newValues.getCategory().getId());
if (newValues.getTag() != null) update.set("tag", newValues.getTag());
if (newValues.isRecurringSale() != null) update.set("isRecurringSale", newValues.isRecurringSale());
if (newValues.isCallProduct() != null) update.set("callProduct", newValues.getProduct());
update.where(saleItemRoot.get("id").in(toUpdate));
return this.sessionFactory.getCurrentSession().createQuery(update).executeUpdate();
}

How to get null and filled values from database using hibernate

I am using hibernate to get data from oracle.I have Criterion object to make filter for hibernate select like this
Criterion cr6=null;
if(reqrrn != null)
{
cr6=Restrictions.eq("rrn", reqrrn);//o
}
else{
cr6=Restrictions.like("rrn", "",MatchMode.ANYWHERE);
}
Criterion cr20=null;
if(cardPrefix != null && cardPrefix != "")
{
cr20=Restrictions.eq("prefix", cardPrefix);
}
else{
cr20=Restrictions.like("prefix", "",MatchMode.ANYWHERE);
}
criteria.add(Restrictions.and(cr6, cr20));
i have filters like this, but it is usseless when value is null, for example
cardPrefix value is null in database i want to get all values for cardPrefix ,which are filled and null too, how can i do this ?
i solved it. it will be for all parameters like
if(cardPrefix != null && cardPrefix != "")
{
cr20=Restrictions.eq("prefix", cardPrefix);
}
else{
cr20=Restrictions.like("prefix", "",MatchMode.ANYWHERE);
cr1=Restrictions.isNull("prefix");
cr20=Restrictions.or(cr20, cr1);
}

Retrieving Cursors from the GAE Datastore

I have a question on how Datastore generate cursors, I have this code below and even if the result list is empty a cursor is still returned:
if(asList){
if(startCursor != null && startCursor.getWebSafeString() != null){
fetchOptions.startCursor(Cursor.fromWebSafeString(startCursor.getWebSafeString()));
res = pq.asQueryResultList(fetchOptions);
} else if(startCursor != null && startCursor.getWebSafeString() == null) {
res = pq.asQueryResultList(fetchOptions);
} else {
res = pq.asList(fetchOptions);
}
} else {
if(startCursor != null && startCursor.getWebSafeString() != null){
fetchOptions.startCursor(Cursor.fromWebSafeString(startCursor.getWebSafeString()));
res = pq.asQueryResultIterable(fetchOptions);
} else if(startCursor != null && startCursor.getWebSafeString() == null){
res = pq.asQueryResultIterable(fetchOptions);
} else {
res = pq.asIterator(fetchOptions);
}
}
return res;
res here is a Query result:
String newCursor = res.getCursor().toWebSafeString();
Even if res list is empty a cursor is returned, it is normal? Or something is wrong with this?
You always get a cursor, because the datastore doesn't know or care if there are any more results. What you should do is check that the cursor actually returns something, and if not don't show the link for more results.
Having these "last position" cursors can be really useful for progressive handling of new data.
As in, if you persist the cursor somewhere, you can poll Datastore for new records every so often - and it's cheap because cursors mean Datastore won't scan rows.

dataContentHandler member variable being overwritten in javax.activation.DataHandler.getDataContentHandler?

The code below is for javax.activation.DataHandler.getDataContentHandler, 1.41, 07/05/14.
If the dataContentHandler member variable is null when the method is called, then it gets set by the 'if' clause at [1] (which is what happens in my program).
It then immediately gets overwritten in the if clause at [2].
Am I missing something, or is that unlikely to be the intended behaviour?
private synchronized DataContentHandler getDataContentHandler() {
// make sure the factory didn't change
if (factory != oldFactory) {
oldFactory = factory;
factoryDCH = null;
dataContentHandler = null;
transferFlavors = emptyFlavors;
}
if (dataContentHandler != null)
return dataContentHandler;
String simpleMT = getBaseType();
if (factoryDCH == null && factory != null)
factoryDCH = factory.createDataContentHandler(simpleMT);
if (factoryDCH != null)
dataContentHandler = factoryDCH;
if (dataContentHandler == null) { // [1]
if (dataSource != null)
dataContentHandler = getCommandMap().
createDataContentHandler(simpleMT, dataSource);
else
dataContentHandler = getCommandMap().
createDataContentHandler(simpleMT);
}
// getDataContentHandler always uses these 'wrapper' handlers
// to make sure it returns SOMETHING meaningful...
if (dataSource != null) // [2]
dataContentHandler = new DataSourceDataContentHandler(
dataContentHandler,
dataSource);
else
dataContentHandler = new ObjectDataContentHandler(
dataContentHandler,
object,
objectMimeType);
return dataContentHandler;
}
I
Am I missing something, or is that unlikely to be the intended behaviour?
Looks like that is the intended behavior per the comment:
// getDataContentHandler always uses these 'wrapper' handlers
// to make sure it returns SOMETHING meaningful...
If you look closely at the code, the 'dataContentHandler' is passed as an argument to 'new DataSourceDataContentHandler' and 'new ObjectDataContentHandler'. That is the 'wrapping' referred to in the comment.

Categories