我正在使用 Play Framework、JPA 和 MySQL,但在 SQL 查询中使用 concat()
函数时遇到一些问题。当我在 MySQL GUI 中使用它时,它会输出连接列的正确值,但是当我在代码中将它与 JPA 一起使用时,它会返回 byte[]
,即字节数组。
我的实体:
@Entity
public class NumberData{
@javax.persistence.Id @GeneratedValue(strategy = GenerationType.AUTO)
Long Id;
@Column(unique = true)
private Long numbr;
@Column(unique = true)
private String somekey;
}
我的选择查询:
String query="SELECT concat(somekey,id) as uid,numbr from numberdata";
List<Object[]> numList = JPA.em().createNativeQuery(query).getResultList();
但是当我尝试打印它时,它给了我一个字节数组:
for (Object[] ob : numList) {
Logger.info("output "+ob[0]+""); //output [B@48927
}
我知道我可以执行 new String(ob[0])
将其转换为字符串,但由于 MySQL GUI 给了我正确的结果,这是 JPA 的问题吗?如何直接从 MySQL 查询中获取字符串 (varchar)?
最佳答案
我想答案可以在 official documentation 中找到对于CONCAT
:
Returns the string that results from concatenating the arguments. May have one or more arguments. If all arguments are nonbinary strings, the result is a nonbinary string. If the arguments include any binary strings, the result is a binary string.
This部分 JDBC 文档提示,如果 CHAR
和 VARCHAR
是二进制字符串,则将其转换为 byte[]
:
java.lang.String (unless the character set for the column is BINARY, then byte[] is returned.
正如上面第一个链接中所建议的,非字符串参数的转换应该可以解决问题:
SELECT CONCAT(CAST(int_col AS CHAR), char_col);
就您而言,它看起来像这样:
String query= "SELECT concat(somekey,CAST(id AS CHAR)) as uid,numbr from numberdata";
关于java - 使用 concat() 时,JPA native 查询返回字节数组而不是字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32156081/