@Table(name="customers")
@Entity
public class Customer {
private Integer id;
private String lastname;
private String email;
private Integer age;
private Date birthday;
private Date creattime;
@TableGenerator(name="id_generator",//和generator对应
pkColumnName="pk_name",
pkColumnValue="customers_id",
valueColumnName="pk_value",
allocationSize=100)
@GeneratedValue(strategy=GenerationType.TABLE,generator="id_generator")
@Id //strategy:战略,策略 generator:生成,生产
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name="last_name",nullable=false,length=50)
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Temporal(TemporalType.DATE)
//调整Date类型的精度
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Date getCreattime() {
return creattime;
}
public void setCreattime(Date creattime) {
this.creattime = creattime;
}
@Transient //表示该属性并非一个到数据库表的字段的映射,ORM框架将忽略该属性
public String getInfo(){
return "lastName : " + lastname + "email : "+ email;
}
}
Main.java类
public class Main {
public static void main(String[] args) {
//1.创建EntitymanagerFactory
//<persistence-unit name="jpa-1" transaction-type="RESOURCE_LOCAL">与下面unitname一致
String persistenceUnitName="jpa-1";
EntityManagerFactory factory=Persistence.createEntityManagerFactory(persistenceUnitName);
//2.创建Entitymanager
EntityManager manager=factory.createEntityManager();
//3.开启事务
EntityTransaction transaction = manager.getTransaction();
transaction.begin();
//4.进行持久化操作
Customer customer = new Customer();
customer.setAge(12);
customer.setEmail("jcc@163.com");
customer.setLastname("jcc");
customer.setBirthday(new Date());
customer.setCreattime(new Date());
manager.persist(customer);
//5.提交事务
transaction.commit();
//6.关闭Entitymanager
manager.close();
//7.关闭EntitymanagerFactory
factory.close();
}
}