在該範例中,我是手動幫
Employee
設定id
,但在JPA中,可以使用GeneratedValue這個Annotation來產生主鍵,使用的策略(strategy)有四種:
public enum GenerationType { TABLE, SEQUENCE, IDENTITY, AUTO };詳細說明,可以參考這裡。
這裡要使用
strategy=GenerationType.TABLE
,使用一個TableGenerator來產生主鍵。
先在資料庫中建立一個資料表,名為
ID_GEN
create table ID_GEN(GEN_KEY varchar(100), GEN_VALUE BIGINT, primary key(GEN_KEY))再來新一筆資料:
insert into ID_GEN (GEN_KEY, GEN_VALUE) values('EMP_ID', 0)把先前
Employee
這個Entity的程式碼改成:
package examples.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.TableGenerator; @TableGenerator( table="ID_GEN", pkColumnName="GEN_KEY", valueColumnName="GEN_VALUE", pkColumnValue="EMP_ID", allocationSize=1, name = "empGen" ) @Entity public class Employee { @Id @GeneratedValue(strategy=GenerationType.TABLE, generator="empGen") private int id; private String name; private long salary; public Employee() {} public int getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getSalary() { return salary; } public void setSalary(long salary) { this.salary = salary; } public String toString() { return "Employee id: " + getId() + " name: " + getName() + " salary: " + getSalary(); } }然後修改
EmployeeService
中的createEmployee
方法,改成不用手動設定id
:
public Employee createEmployee(int id, String name, long salary) { Employee emp = new Employee(); emp.setName(name); emp.setSalary(salary); em.persist(emp); return emp; }然後把執行的主程式改成:
package examples.client; import java.util.Collection; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import examples.model.Employee; import examples.model.EmployeeService; public class EmployeeMain { public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("EmployeeService"); EntityManager em = emf.createEntityManager(); EmployeeService service = new EmployeeService(em); // create and persist an employee em.getTransaction().begin(); Employee emp = service.createEmployee("Bio Young", 90000); em.getTransaction().commit(); System.out.println("Persisted " + emp); // find all employees Collection<Employee> emps = service.findAllEmployees(); for (Employee e : emps) { System.out.println("Found Employee: " + e); } em.close(); emf.close(); } }最後,執行主程式看結果。
沒有留言:
張貼留言