【问题标题】:How to execute query that will separate by certain symbol in Repository Springboot using java如何使用java在Repository Spring Boot中执行将由某个符号分隔的查询
【发布时间】:2018-06-11 13:23:41
【问题描述】:

我想在同一个实体中通过"~"将查询结果数据分开,通过","将另一个实体数据分开

我的代码

ma​​inRepository.java

public interface mainRepository extends CrudRepository<Error, Long> {

    @Query(value= "SELECT * FROM Error t where t.applicationID = :applicationid", nativeQuery= true)
    List<Error> findListByApp(@Param("applicationid") String applicationid);
}

在另一个类中我调用该函数

String cb = errorRepository.findListByApp("application1").toString();
System.out.println(cb);

如果我执行 cb 的结果是

[com.info.main.Error@6ec8b40e, com.info.main.Error@6ec8b40e, com.info.main.Error@6ec8b40e]

我想先按应用程序排序,然后是名称,然后是电子邮件。

我想要达到的结果是这样的:

[app1~name1~email1, app2~name2~email2, app3~name3~email3]

【问题讨论】:

    标签: java mysql spring spring-boot spring-data-jpa


    【解决方案1】:

    为什么你在结果列表中使用 toString?

    String cb = errorRepository.findListByApp("application1").toString();//why toString?
    

    相反,您必须使用这样的列表:

    List<Error> result = errorRepository.findListByApp("application1");
    //this will print the list or Error it will call to String for each error
    System.out.println(result);
    

    要显示结果,您只需使用您想要的格式覆盖错误实体中的 toString 方法即可。

    @Entity
    public class Error {
    
        private String app;
        private String name;
        private String email;
    
        //getter setter
    
        @Override
        public String toString() {
            return app + "~" + name + "~" + email;
        }
    }
    

    【讨论】:

    • 我只是把它改成 List result = errorRepository.findListByApp("application1");正如你所说,然后我用 result.toString() 打印它。但仍然出现同样的错误
    • @user_22 你是什么意思?
    • no 不要打印 result.toString() 像这样打印列表 System.out.println(result); 检查我的编辑
    • 我只是添加了@Override toString,正如您在编辑中提到的那样,它可以工作。谢谢
    猜你喜欢
    • 1970-01-01
    • 2013-12-20
    • 2018-06-02
    • 2019-07-18
    • 1970-01-01
    • 2020-02-26
    • 2019-10-16
    • 1970-01-01
    • 2020-02-21
    相关资源
    最近更新 更多