This week's book giveaway is in the Programmer Certification forum.
We're giving away four copies of OCP Oracle Certified Professional Java SE 11 Programmer I Study Guide: Exam 1Z0-815 and have Jeanne Boyarsky & Scott Selikoff on-line!
See this thread for details.
Win a copy of OCP Oracle Certified Professional Java SE 11 Programmer I Study Guide: Exam 1Z0-815 this week in the Programmer Certification forum!
  • 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
  • Junilu Lacar
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Paweł Baczyński
  • Piet Souris
  • Vijitha Kumara

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.
 
Rancher
Posts: 4329
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.
 
If I had asked people what they wanted, they would have said faster horses - Ford. 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!