How to get null and filled values from database using hibernate - java

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);
}

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();
}

Java String appending with comma as a separator

I have a requirement where I need to append multiple values from multiple web service calls into one final string with comma as a separator.
Some of the values might be null, in that case I need to check for not null and then append it as empty string.
If there is no value for one of the string, comma should not get appended.
Please help me resolving this. here is the code what I did.
StringBuilder sb = new StringBuilder();
if (usersList.totalCount != 0 && usersList.totalCount >= 1) {
logger.info("usersList.totalCount ----->"
+ usersList.totalCount);
for (KalturaUser user : usersList.objects) {
if (user.id != null) {
sb.append(userId);
}
if (user.firstName != null) {
sb.append(",").append(userFirstName);
}
if (user.lastName != null) {
sb.append(",").append(user.lastName);
}
if (user.email != null) {
sb.append(",").append(user.email);
}
if (user.roleNames != null) {
sb.append(",").append(user.roleNames);
}
if (user.partnerData != null) {
sb.append(",").append(user.partnerData);
}
}
System.out.println(sb);
}
Thanks,
Raji
I think you are looking for something like this:
public static String asString(Object value) {
return value == null ? "" : value.toString();
}
for (KalturaUser user : usersList.objects) {
sb.append(asString(user.id));
sb.append(",").append(asString(user.firstName));
sb.append(",").append(asString(user.lastName));
sb.append(",").append(asString(user.email));
sb.append(",").append(asString(user.roleNames));
sb.append(",").append(asString(user.partnerData));
}
Well, in your tests like
if (user.id != null) {
sb.append(userId);
}
you are checking user.id but appending userId. These are two different variables.
You should probably change it into
if (user.id != null) {
sb.append(user.id); //instead of sb.append(userId);
}
It is not clear what your problem is, but if you are looking for a better or different approach, I found that it is best to append to a List<String> and then use StringUtils.join to produce the final string.
You can use a class from a google library called Joiner.
String concatenedString = Joiner.on(",").skipNulls().join(itemToAdd);
You can find this class on google-collections-1.0.jar
I would do something like that. It's based on Java8 streams, but here you don't need to do the non-null check on every property(.filter does this for you). I assumed that users.object is an array list, if it's not you might need to convert it into stream in other way
if (userList.totalCount > 0) {
logger.info("usersList.totalCount ----->" + usersList.totalCount);
String result = userList
.objects
.stream()
.map(user -> {
return Stream.of(user.firstName, user.id, user.lastName, user.email, user.roleNames, user.partnerData) //get the properties you need into the stream
.filter(property -> property != null) // filter out null properties
.collect(Collector.joining(",")); //join them by comma
})
.collect(Collector.joining(",")); //join user strings with comma
System.out.println(result);
}

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.

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

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");

Categories