Java 學習記錄132 — 員工管理系統專案練習-Create JPA Entity

張小雄
1 min readAug 3, 2022

src\main\java 新增四個資料夾

分別是 controller、exception、model、repository

在 model 裡新增 Employee.java

package com.example.springbootbackend.model;import javax.persistence.*;@Entity
@Table(name = "employees")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName; private String lastName; private String emailId; public Employee() {
}
public Employee(String firstName, String lastName, String emailId) {
this.firstName = firstName;
this.lastName = lastName;
this.emailId = emailId;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getemailId() {
return emailId;
}
public void setemailId(String emailId) {
this.emailId = emailId;
}
}

若是用 Intellij 的話,在 @Table(name = "employees") 應該會報錯

解決方法

All your domain models must be annotated with @Entity annotation. It is used to mark the class as a persistent Java class.

@Table annotation is used to provide the details of the table that this entity will be mapped to.

@Id annotation is used to define the primary key.

@GeneratedValue annotation is used to define the primary key generation strategy.

沒有註明的話就是自增長

等同於 @GeneratedValue(strategy=GenerationType.AUTO)

參考1參考2

GenerationType.AUTO vs GenerationType.IDENTITY in hibernate

--

--