@Bean public CommandLineRunner demo(CustomerRepository repository) { return (args) -> { // save a few customers repository.save(newCustomer("Jack", "Bauer")); repository.save(newCustomer("Chloe", "O'Brian")); repository.save(newCustomer("Kim", "Bauer")); repository.save(newCustomer("David", "Palmer")); repository.save(newCustomer("Michelle", "Dessler"));
// fetch all customers log.info("Customers found with findAll():"); log.info("-------------------------------"); for (Customer customer : repository.findAll()) { log.info(customer.toString()); } log.info("");
// fetch an individual customer by ID Customercustomer= repository.findById(1L); log.info("Customer found with findById(1L):"); log.info("--------------------------------"); log.info(customer.toString()); log.info("");
// fetch customers by last name log.info("Customer found with findByLastName('Bauer'):"); log.info("--------------------------------------------"); repository.findByLastName("Bauer").forEach(bauer -> { log.info(bauer.toString()); }); // for (Customer bauer : repository.findByLastName("Bauer")) { // log.info(bauer.toString()); // } log.info(""); }; }
}
执行主启动类的main方法启动项目,成功输出
1 2 3 4 5 6 7 8 9 10 11 12 13
== Customers found with findAll(): Customer[id=1, firstName='Jack', lastName='Bauer'] Customer[id=2, firstName='Chloe', lastName='O'Brian'] Customer[id=3, firstName='Kim', lastName='Bauer'] Customer[id=4, firstName='David', lastName='Palmer'] Customer[id=5, firstName='Michelle', lastName='Dessler']
== Customer found with findById(1L): Customer[id=1, firstName='Jack', lastName='Bauer']
== Customer found with findByLastName('Bauer'): Customer[id=1, firstName='Jack', lastName='Bauer'] Customer[id=3, firstName='Kim', lastName='Bauer']