开发者

Dynamic Hibernate Query

I have a method that I use to return a dynamic query. This method is shown below


public Query getLastId(String sProvider)
{
       String serviceProvider = sProvider.toLowerCase();     
       String query2 = "SELECT MAX(:serviceProvider.id) " + 
                   " FROM :sProvider :serviceProvider ";

       return em.createQuery(query2)
              .setParameter("sProvider", sProvider)
              .setParameter("serviceProvider", serviceProvider);

}

I want this method to return this

SELECT MAX(multichoice.id) FROM Multichoice multichoice

when I call 开发者_如何学JAVAthe method like this

getLastId("Multichoice");

Please how do I write the query variable to return the answer?


To do this task you can use Criteria object model and projections to run your query over different types: Take a look at this article (15.7. Projections, aggregation and grouping)

here is the code :

List results = session.createCriteria(class)
.setProjection( Projections.max("id"))
.list();

Then instead of a string you should send a class to your method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜