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
Print Records from FindAll() in CrudRepository
提问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()
Iterable
into 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 Record
class, or whatever your class name is, to tabular formatting using String.format()
只需覆盖toString()
您Record
班级中的 ,或者无论您的班级名称是什么,都可以使用String.format()