創建項目
打開IDEA -> Create New Project
創建目錄
創建實體
package com.example.demo.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Customer {
@Id
@GeneratedValue
private Long id;
private String firstName;
private String lastName;
protected Customer() {
}
public Customer(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return "Customer{" +
"id=" + id +
", firstName=" + firstName +
", lastName=" + lastName +
'}';
}
}
創建 Repository
創建與實體對應的Repository
package com.example.demo.repository;
import com.example.demo.entity.Customer;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface CustomerRepository extends CrudRepository<Customer, Long> {
List<Customer> findByLastName(String lastName);
}
通過繼承CrudRepository繼承幾種增刪改查方法,也可以通過方法名支定義其他查詢方法。
添加啓動加載類 CommandLineRunner 測試
package com.example.demo;
import com.example.demo.entity.Customer;
import com.example.demo.repository.CustomerRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class SpringDataJpaDemoApplication {
public static final Logger log = LoggerFactory.getLogger(SpringDataJpaDemoApplication.class);
public static void main(String[] args) {
SpringApplication.run(SpringDataJpaDemoApplication.class, args);
}
@Bean
public CommandLineRunner demo(CustomerRepository repository) {
return (args -> {
repository.save(new Customer("Jack", "Bauer"));
repository.save(new Customer("Chloe", "Brian"));
repository.save(new Customer("Kim", "Bauer"));
repository.save(new Customer("David", "Palmer"));
repository.save(new Customer("Michelle", "Dessler"));
log.info("Customer found with save() finish");
log.info("Customer found with findAll()");
log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
for (Customer customer : repository.findAll()) {
log.info(customer.toString());
}
log.info("");
repository.findById(1L).ifPresent(customer -> {
log.info("Customer found with findById()");
log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
log.info(customer.toString());
log.info("");
});
log.info("Customer found with findByLastName('findByLastName')");
log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
repository.findByLastName("Bauer").forEach(bauer -> {
log.info(bauer.toString());
});
log.info("");
});
}
}
運行程序,通過 log 查看效果