新建Spring Boot空項目
打開Intellij IDEA,選擇File -> New -> New Project -> 左側的Spring Initializr。按照向導的提示進行操作,當遇到依賴包選擇頁面時候,勾選JPA和MySQL。如下圖所示:
image.png
配置數據庫連接:
在application.properties文件中寫入以下內容:
# driver 類名
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# 數據庫用戶名
spring.datasource.username=root
# 數據庫密碼
spring.datasource.password=123456
# 數據庫連接URL
spring.datasource.url=jdbc:mysql://localhost:3306/demo
# 數據庫表生成策略,create表示會自動創建表,并且會破壞之前的數據
spring.jpa.hibernate.ddl-auto=create
編寫實體類
// @Entity注解聲明該類為實體類
@Entity
public class Student implements Serializable {
// @Id此字段為主鍵字段
// @GeneratedValue 主鍵的生成策略,此處采用主鍵自增
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
if (id != student.id) return false;
return name != null ? name.equals(student.name) : student.name == null;
}
@Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
}
編寫Repository
@Service
public interface StudentRepo extends JpaRepository<Student, Long> {
List<Student> findByName(String name);
}
注意:
- 該接口繼承了JpaRepository接口。泛型的寫法為<實體類型,主鍵類型>。
- JpaRepository接口繼承了PagingAndSortingRepository和CrudRepository。顧名思義它們分別提供了分頁排序查找以及基本的CRUD功能。
編寫測試類
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
// 注入Repository
@Autowired
private StudentRepo studentRepo;
@Test
public void contextLoads() {
Student student = new Student();
student.setName("Paul");
// 調用CRUDRepository接口中的save方法保存數據
studentRepo.save(student);
// 按照name字段查找數據
student = studentRepo.findByName("Paul").get(0);
}
}