简体   繁体   English

Java Hibernate / Spring,做部分匹配查询(“包含”)?

[英]Java Hibernate / Spring, doing partial match query (“contains”)?

I'm still fairly new to hibernate and can't seem to find how to do this, maybe I'm searching using the wrong terminology. 我仍然相当熟悉hibernate并且似乎无法找到如何做到这一点,也许我正在使用错误的术语进行搜索。 I am passing in a user provided value from my UI, in the example below this is the variable testvalue . 我从我的UI传递用户提供的值,在下面的示例中,这是变量testvalue It is for doing a search so if what the user enters is contained anywhere in an entry e.filenametxt I want it to return that row as a match. 这是为了进行搜索,所以如果用户输入的内容包含在条目e.filenametxt中的任何位置,我希望它将该行作为匹配返回。

For example, testvalue = "file1" , I would want it to be able to find a row where e.filenametxt = "file1/someotherinfo/" 例如, testvalue = "file1" ,我希望它能够找到一行e.filenametxt = "file1/someotherinfo/"

String SQL_QUERY = "from EdrmTest e where e.filenametxt is :foreignkeytest ";
Query query = session.createQuery(SQL_QUERY);
query.setParameter("foreignkeytest", testvalue);

Any advice is appreciated. 任何建议表示赞赏。

String SQL_QUERY = "from EdrmTest e where e.filenametxt LIKE :foreignkeytest ";
Query query = session.createQuery(SQL_QUERY);
query.setParameter("foreignkeytest", "%" + testvalue + "%");\

Try that. 试试吧。 The wild cards need to be in the variable (for some reason). 外卡需要在变量中(出于某种原因)。

You can also use the Criteria API to set these types of clauses programatically; 您还可以使用Criteria API以编程方式设置这些类型的子句; sometimes it can be much nicer to handle queries with this API as opposed to a HQL/String based query if you need to add any sort of dynamic logic (ie include certain clauses based on a condition). 有时,使用此API处理查询可能会更好,而不是基于HQL / String的查询,如果您需要添加任何类型的动态逻辑(即根据条件包含某些子句)。

Criteria crit = session.createCriteria(EdrmTest.class); //the persistent class goes here
crit.add( Restrictions.like("filenametxt", testvalue + "%") );
//execute the query:
List<EdrmTest> results = (List<EdrmTest>) crit.list();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM