【问题标题】:Print Records from FindAll() in CrudRepository从 CrudRepository 中的 FindAll() 打印记录
【发布时间】:2014-05-29 14:22:32
【问题描述】:

我在我的 Repository 类中扩展 CrudRepository。我想使用 findAll 方法打印表中的记录。至此,我写了一个测试类,可以看到结果查询是正确的。如何打印表格中的各个记录?

这是我的代码的 sn-p: 存储库类

public interface RepositoryAda extends CrudRepository{


}

服务类

@Service
public class Service{

@Autowired private RepositoryAda repository;

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

}

测试用例:

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

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

【问题讨论】:

  • 另外,将它们打印到表格是什么意思?您是否只想以表格格式将记录打印到控制台?或者你不知道如何遍历Iterable
  • 我需要将它们打印到控制台。

标签: java entitymanager hibernate-entitymanager


【解决方案1】:

在使用存储库接口时,我更喜欢使用Google's 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();
    }
}

然后循环遍历列表

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

只需覆盖 Record 类中的 toString() 或任何您的类名,即可使用 String.format() 进行表格格式设置

【讨论】:

  • 列表来自哪个进口?基于这一行: return Lists.newArrayList(recordRepository.findAll());
  • 它来自 Guava 库。查看链接
  • 在不使用 Guava 库的情况下还有其他方法吗?
  • 是的,直接投吧return (List&lt;Record&gt;)recordRepository.findAll();
猜你喜欢
  • 2015-10-31
  • 1970-01-01
  • 2018-11-29
  • 1970-01-01
  • 2020-08-16
  • 2018-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多