Hibernate how to add restriction for filtering result by Integer id column

2.5k Views Asked by At

Want to ask how to add restriction for filtering result by Integer id column

I need something like

Restriction.like("id", myFilterValue) // id is Integer primary key

1

There are 1 best solutions below

3
On

If you want to retrieve an object by its primary key in Hibernate, you can use Session.get():

Foo foo = session.get(Foo.class, id);

Otherwise, if you want to add an equality restriction using Criteria:

Criteria crit = session.createCriteria(Foo.class);
crit.add(Restrictions.eq("id", id);
List foos = crit.list();

I suppose if what you really want is to find any rows where the decimal digits of the numeric column contain a certain substring of digits, then you would have to CAST the column to a VARCHAR (the syntax of which may vary between databases, and you didn't specify which one you are using) and then you would be able to use something like WHERE CAST(id AS VARCHAR) LIKE '%12%'. But if you are doing this, you may need to reconsider what you are trying to accomplish at a much higher level, as this would lead me to believe that there may be a problem with the basic design of your system.