副标题:
JPA主键生成策略、日期_枚举等字段类型的JPA映射、大数据字段映射与字段延迟加载
//Person类
package cn.itcast.bean;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
@Entity
@Table(name="person")
public class Person {
private Long id;
private String name;
private Date birthday;
private Gender gender = Gender.MAN; // 设置默认值
private String infoString;
private Byte[] file;
private String imagepath;
@Transient //设置不与数据库相关
public String getImagepath() {
return imagepath;
}
public void setImagepath(String imagepath) {
this.imagepath = imagepath;
}
@Lob //大文本
public String getInfoString() {
return infoString;
}
public void setInfoString(String infoString) {
this.infoString = infoString;
}
@Enumerated(EnumType.STRING) @Column(length=5,nullable=false)
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public Person() {}
public Person(String name) {
this.name = name;
}
@Id @GeneratedValue //设置主键和自增长方式,默认为auto,根据方言来确定
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(length=20,nullable=false) //设置长度和能否为空
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Temporal(TemporalType.DATE) //设置时间格式
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Lob @Basic(fetch=FetchType.LAZY) //延时加载(一般放大数据>1M就可以用了)
public Byte[] getFile() {
return file;
}
public void setFile(Byte[] file) {
this.file = file;
}
//测试程序
package junit.test;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.junit.BeforeClass;
import org.junit.Test;
import cn.itcast.bean.Person;
public class PersonTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test public void save(){
EntityManagerFactory factory = Persistence.createEntityManagerFactory("itcast");
//sessionFactory-->session-->begin事务
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();//开始事务
em.persist(new Person("传智播客"));
em.getTransaction().commit();
em.close();
factory.close();
}
}