创建一个SpringBoot项目,依赖JPA and H2 dependencies.
package com.dongyu.springbootguide22.accessingdatajpa;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;@Entitypublic class Customer {@Id@GeneratedValue(strategy=GenerationType.AUTO)private Long id;private String firstName;private String lastName;protected Customer() {}public Customer(String firstName, String lastName) {this.firstName = firstName;this.lastName = lastName;}@Overridepublic String toString() {return String.format("Customer[id=%d, firstName='%s', lastName='%s']",id, firstName, lastName);}public Long getId() {return id;}public String getFirstName() {return firstName;}public String getLastName() {return lastName;}}
修改启动类增加Command.
package com.dongyu.springbootguide22;import com.dongyu.springbootguide22.accessingdatajpa.Customer;import com.dongyu.springbootguide22.accessingdatajpa.CustomerRepository;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.mandLineRunner;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.Bean;@SpringBootApplicationpublic class DemoApplication {private static final Logger log = LoggerFactory.getLogger(DemoApplication.class);public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}@Beanpublic CommandLineRunner demo(CustomerRepository repository) {return (args) -> {// save a few customersrepository.save(new Customer("Jack", "Bauer"));repository.save(new Customer("Chloe", "O'Brian"));repository.save(new Customer("Kim", "Bauer"));repository.save(new Customer("David", "Palmer"));repository.save(new Customer("Michelle", "Dessler"));// fetch all customerslog.info("Customers found with findAll():");log.info("-------------------------------");for (Customer customer : repository.findAll()) {log.info(customer.toString());}log.info("");// fetch an individual customer by IDCustomer customer = repository.findById(1L);log.info("Customer found with findById(1L):");log.info("--------------------------------");log.info(customer.toString());log.info("");// fetch customers by last namelog.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("");};}}
JPA是SpringBoot默认启动的。