-2

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

hop
  • 2,518
  • 11
  • 40
  • 56
TarasLviv
  • 1,411
  • 3
  • 12
  • 17
  • This is a very basic questions. Read hibernate docs http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html – hop Feb 04 '12 at 08:02

1 Answers1

1

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.

Adam Batkin
  • 51,711
  • 9
  • 123
  • 115
  • I need get list of objects (for ex. I have rows in table with id 123, 1233, 23123, 12...) and want to find objects that have id like '12' – TarasLviv Feb 03 '12 at 11:27
  • I tried Restrictions.sqlRestriction("id like '%" + myFilterValue + '%''), but still not working – TarasLviv Feb 03 '12 at 11:33
  • Do you mean where the `id` contains the digits (for example) "`12`" anywhere within the number? In most databases you can't do that with integer columns (`LIKE` works for strings only), and it sounds like you may have a more fundamental design issue with your schema if that's really what you want to do – Adam Batkin Feb 03 '12 at 12:19