简体   繁体   English

在Spring Data JPA查询中将整数转换为字符串

[英]Convert Integer to String in Spring Data JPA Query

I need to optimize a query that iterates over several objects and I wanted Spring Data to let the database handle it. 我需要优化一个遍历多个对象的查询,并且我希望Spring Data让数据库处理它。 I want to end up with a HashMap<String,String> that looks like 我想以一个类似的HashMap<String,String>结尾

2134_9877, 9877
2134_2344, 2344
3298_9437, 9437

The SQL would be select convert(varchar,b.id)+'_'+convert(varchar,a.id)',a.id from t1 a join t2 b on a.jc = b.jc SQL将是select convert(varchar,b.id)+'_'+convert(varchar,a.id)',a.id from t1 a join t2 b on a.jc = b.jc

So far, I've got Whatever-QL in the repository that looks like: 到目前为止,我在存储库中获得了Whatever-QL,如下所示:

@Query("SELECT new map (a.bkey, a.akey) FROM mergeTable a WHERE a.discr= ?1")

The problem is, bkey is not unique, it is only unique when paired with akey and the monstrosity that I have to feed it to wants them combined with an underscore: 2345_2177 . 问题是, bkey不是唯一的,它仅在与akey配对时才是唯一的,而我必须将其喂给想要它们加下划线的2345_21772345_2177

I have tried a.bkey.toString and ''+a.bkey and new String(a.bkey) and just string(a.bkey) (that last gives a new exception but still doesn't work) but Spring doesn't like any of these. 我尝试了a.bkey.toString''+a.bkey以及new String(a.bkey)和只是string(a.bkey) (最后给出了一个新的异常,但仍然无法正常工作),但是Spring却没有像其中任何一个。 I can find no questions asking this and it seems I cannot use SQLServer's convert() function as this ain't SQL. 我找不到任何问题要问,看来我不能使用SQLServer的convert()函数,因为这不是SQL。

How can I concatenate the Integers as Strings with an underscore in this @Query? 如何在此@Query中将带下划线的整数连接为字符串?

PS: Using the native query that's been debugged in SQLServer throws some weird alias exception in Hibernate so I think 'going native' is predetermined to be a dead end. PS:使用在SQLServer中调试的本机查询会在Hibernate中引发一些奇怪的别名异常,因此我认为“转为本机”已定为死胡同。

If I have understood it right, the 'Whatever-QL' is called JPQL, and the operator CONCAT can be used. 如果我理解正确,那么“ Whatever-QL”称为JPQL,并且可以使用运算符CONCAT。 Only the use of it, as it accepts two or more parameters depends on the JPA version you are running. 由于它接受两个或多个参数,因此仅使用它取决于您运行的JPA版本。

Here is the answer. 这是答案。

JPA concat operator JPA concat运算符

You could add a getter to your entity like this: 您可以像这样向您的实体添加吸气剂:

public String getCombinedKey(){
  return a.akey + "_" + a.bkey;
}

The advantage is you could handle here null's and other things if you want and it's more reusable in case you need this in another place. 好处是您可以在这里处理null和其他内容,并且在需要在其他地方使用时可以重用。 If you do it just in the repository you will have to copy it everytime. 如果仅在存储库中执行此操作,则每次都必须复制它。

Your query would then be: 您的查询将是:

@Query("SELECT new map (a.combinedKey, a.akey) FROM mergeTable a WHERE a.discr= ?1")

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

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