1. Compile the object class with the following code:
Package learn. jpa. bean; import javax. persistence. entity; import javax. persistence. generatedValue; import javax. persistence. id; @ Entitypublic class Person {@ Id @ GeneratedValue private Integer id; private String name; public Person () {} public Person (String name) {this. name = name;} public Integer getId () {return id;} public void setId (Integer id) {this. id = id;} public String getName () {return name;} public void setName (String name) {this. name = name ;}}
@ Id: used to mark the primary key of an attribute
@ GeneratedValue
JPA provides four standard usage methods: TABLE, SEQUENCE, IDENTITY, and AUTO.
- -TABLE: use a specific database TABLE to save the primary key.
- -SEQUENCE: generates the primary key based on the SEQUENCE of the underlying database, provided that the database supports the SEQUENCE.
- -IDENTITY: the primary key is automatically generated by the database (mainly the auto-growth type)
- -AUTO: the primary key is controlled by the program (it is also the default value. If the primary key generation policy is not specified when the primary key is specified, the default value is AUTO)
2. Unit Test class, the code is as follows:
Package learn. jpa. junit. test; import static org. junit. assert. *; import javax. persistence. entityManager; import javax. persistence. entityManagerFactory; import javax. persistence. persistence; import learn. jpa. bean. person; import org. junit. test; public class PersonTest {@ Test public void save () {EntityManagerFactory factory = Persistence. createEntityManagerFactory ("learn_jpa"); EntityManager em = factory. createEntityManager (); em. getTransaction (). begin (); // start the transaction em. persist (new Person ("hwl"); em. getTransaction (). commit (); em. close (); factory. close ();}}
(1) When will a table be created?
When the following statement is executed, the table is created:
EntityManagerFactory factory = Persistence. createEntityManagerFactory ("learn_jpa ");
If the table is not created, the Entity bean is faulty.
JPA learning --- Section 4: Policies for generating JPA instances and JPA primary keys