Java 从 CrudRepository 中的 FindAll() 打印记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23935662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 09:12:57  来源:igfitidea点击:

Print Records from FindAll() in CrudRepository

javaentitymanagerhibernate-entitymanager

提问by user1324418

I am extending CrudRepository in my Repository class. I want to print the records in my table using the findAll method. So far, I have written a test class, and I can see the result query is correct. How can I print the individual records in the table?

我正在我的 Repository 类中扩展 CrudRepository 。我想使用 findAll 方法打印表中的记录。到目前为止,我已经写了一个测试类,可以看到结果查询是正确的。如何打印表中的单个记录?

Here is a snippet of my code: Repository Class

这是我的代码片段:Repository Class

public interface RepositoryAda extends CrudRepository{


}

Service Class

服务等级

@Service
public class Service{

@Autowired private RepositoryAda repository;

@Transactional
public List selectRecords(){
  return  (List) repository.findAll();
 }

}

Test Case:

测试用例:

@Test
public void getAllRecords() {
    service.selectRecords();
}

How can I print the individual records from the table to a console?

如何将表中的单个记录打印到控制台?

回答by Paul Samsotha

I prefer to use Google's Guavawhen using the repository interfaces. You can turn findAll()Iterableinto a List<Type>with one line.

在使用存储库接口时,我更喜欢使用Google 的 Guava。您可以打开findAll()Iterable变成List<Type>一个有一行。

public RecordRepository extends CrudRepository<Record, Long> {}

public class RecordServiceImple implements RecordService {
    RecordRepository recordRepository;

    public List<Record> selectRecord() {
        return Lists.newArrayList(recordRepository.findAll()); // Guava library 
        // or just simply cast it. 
        // return (List<Record>)recordRepository.findAll();
    }
}

Then just loop through the list

然后循环遍历列表

for (Record record : records) {
    System.out.println(record);
}

Just overrive the toString()in your Recordclass, or whatever your class name is, to tabular formatting using String.format()

只需覆盖toString()Record班级中的 ,或者无论您的班级名称是什么,都可以使用String.format()