1

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?

Here is a snippet of my code: 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?

user1324418
  • 267
  • 1
  • 6
  • 14

1 Answers1

9

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

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()

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720