引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
定义数据库实体
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public 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;
}
//Get/Set略public String toString() {
return String.format("Customer[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName);
}
}
定义仓库接口
import org.springframework.data.repository.CrudRepository;
import com.aaron.springBootDemo.domain.Customer;
public interface CustomerRepository extends CrudRepository<Customer, Long> {
List<Customer> findByLastName(String lastName);
}
定义Controller
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.aaron.springBootDemo.domain.Customer;
import com.aaron.springBootDemo.service.CustomerRepository;
@RestController
public class JpaController {
private final Logger LOG = LoggerFactory.getLogger(JpaController.class);
@Autowired
private CustomerRepository repository;
@Bean
public CommandLineRunner demo(CustomerRepository repository) {
return (args) -> {
repository.save(new Customer("Jack", "Bauer"));
repository.save(new Customer("Chloe", "O'Brain"));
repository.save(new Customer("Kim", "Bauer"));
repository.save(new Customer("David", "Palmer"));
repository.save(new Customer("Michelle", "Dessler"));
for(Customer c : repository.findAll()) {
LOG.info("findAll " + c.toString());
}
repository.findById(1L).ifPresent(customer -> {
LOG.info("findById " + customer.toString());
});
repository.findByLastName("Bauer").forEach(bauer -> {
LOG.info("findByLastName " + bauer.toString());
});
};
}
@RequestMapping("/getCustomerById")
public Customer getCustomerById(@RequestParam(value="id", defaultValue="1") Long id) {
return repository.findById(id).get();
}
}