有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用concat()时返回字节数组而不是字符串的java JPA本机查询

我正在使用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)


共 (1) 个答案

  1. # 1 楼答案

    我认为答案可以在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.

    JDBC文档的This部分提示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";