1. 程式人生 > >JPA之大資料欄位對映與欄位延遲載入

JPA之大資料欄位對映與欄位延遲載入

1、修改Person.java中的程式碼

package cn.sunft.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.GenerationType;
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 Integer id;
	private String name;
	private Date birthday = new Date();//1987-12-10
	private Gender gender = Gender.MAN;//設定預設屬性
	private String info;               //大段文字資訊
	private Byte[] file;               //大段二進位制資料
	private String imagepth;           //希望該屬性不成為持久化欄位
	
	@Transient//該欄位不與資料庫進行對映
	public String getImagepth() {
		return imagepth;
	}

	public void setImagepth(String imagepth) {
		this.imagepth = imagepth;
	}

	@Lob//針對二進位制文字的配置
	@Basic(fetch=FetchType.LAZY) //指定延遲載入
	public Byte[] getFile() {
		return file;
	}

	public void setFile(Byte[] file) {
		this.file = file;
	}

	@Lob//針對大段文字的註解
	public String getInfo() {
		return info;
	}

	public void setInfo(String info) {
		this.info = info;
	}

	//@Enumerated(EnumType.ORDINAL)//儲存索引到資料庫中
	@Enumerated(EnumType.STRING)//儲存字面值到資料庫
	@Column(length=5, nullable=false)//一定要加上非空約束
	public Gender getGender() {
		return gender;
	}

	public void setGender(Gender gender) {
		this.gender = gender;
	}

	@Temporal(TemporalType.DATE)
	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	public Person() {
		super();
	}

	public Person(String name) {
		super();
		this.name = name;
	}

	//也可以直接標註在屬性上
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	public Integer getId() {
		return id;
	}
	
	public void setId(Integer id) {
		this.id = id;
	}
	
	//指定列的長度
	@Column(length=10, nullable=false,name="personName")
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
}
2、執行PersonTest.java中的save()方法(參見JPA第二篇部落格)之後生成的資料庫表結構