• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • paul wheaton
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Tim Holloway
  • Carey Brown
  • salvin francis

Hibernate Restrictions.eq() does not consider trailing white space?

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am querying MS SQL Server using Hibernate Criteria, but I have found that queries on varchar columns with Restrictions.eq() do not consider trailing white space.

For example, if my DB has the value "ABC     " (5 trailing white space), and I pass the value "ABC" (no white space) to Restrictions.eq(), it finds a match.  (The reverse is also true.  If my DB has "ABC", and I pass "ABC     " to Restrictions.eq(), it finds a match.)

This is not my desired behavior, as the strings are not actually equal.


Oddly, Restrictions.like() does respect Strings' trailing white space... but I don't actually want regex pattern matching.

My ugly hack for now is to add the Restrictions.eq() Criterion, and if the input value is a String also add the Restrictions.like() Criterion.  Can anybody think of a better workaround?  I'd rather not switch everything from Criteria to HQL.
 
Master Rancher
Posts: 4208
47
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's SQL Server causing the issue:

https://www.brentozar.com/archive/2017/04/surprising-behavior-trailing-spaces/

ETA:
And here's the KB the article above refers to:
https://support.microsoft.com/en-us/help/316626/inf-how-sql-server-compares-strings-with-trailing-spaces

That SQL Server chooses to do this with (by the look of it) VARCHARs and not just CHARs strikes me as a little odd.
 
He's giving us the slip! Quick! Grab this tiny ad!
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!