java - 使用 concat() 时,JPA native 查询返回字节数组而不是字符串

标签 java mysql string jpa arrays

我正在使用 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 文档提示,如果 CHARVARCHAR 是二进制字符串,则将其转换为 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/

相关文章:

php - MySQL 变量不能立即可用

mysql - Django save() 不起作用

arrays - 加入算法,例如字符串数组

string - 将 Common Lisp 中的宏参数视为(区分大小写的)字符串

c++ - 我如何(干净利落地!)将 std::stringstream 子类化以进行自定义?

java - Hadoop map-reducer 没有写入任何输出

java - 如何在同一版本的flyway中执行多个sql脚本

java - PreparedStatement 缓存 - 这是什么意思(它是如何工作的)

mysql - 想在求和 1 列时从 3 个表中获取数据

java - 程序结束时关闭java执行器服务