jpa抓取策略详解fetch(lazy ,eager)
时间:2010-12-23 javaeye sefcertyu
在jpa中jpa默认的加载方式是lazy方式也就是在实际使用到数据的时候才加 载相关数据,使用lazy时可以不用显示注明fetch=FetchType.LAZY
实体bean:carage
Java代码
package com.hibernate.jpa.bean1;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity
public class Garage {
/**
* many to one 多对一
*/
private Integer gid;
private String garagenum;
private Set<Auto> autos = new HashSet<Auto> ();
@Id @GeneratedValue
public Integer getGid() {
return gid;
}
public void setGid(Integer gid) {
this.gid = gid;
}
@Column(length=20)
public String getGaragenum() {
return garagenum;
}
public void setGaragenum(String garagenum) {
this.garagenum = garagenum;
}
@OneToMany(cascade={CascadeType.PERSIST},mappedBy="garage")
public Set<Auto> getAutos() {
return autos;
}
public void setAutos(Set<Auto> autos) {
this.autos = autos;
}
public void addGarageAuto(Auto auto) {
auto.setGarage(this);
this.autos.add(auto);
}
}
jpa抓取策略详解fetch(lazy ,eager)(2)
时间:2010-12-23 javaeye sefcertyu
实体bean:auto
Java代码
package com.hibernate.jpa.bean1;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Entity
public class Auto {
/**
* one to many 一对多关联
*/
private Integer autoId;
private String autotype;
private String autonum;
private Garage garage;
@Id @GeneratedValue
public Integer getAutoId() {
return autoId;
}
public void setAutoId(Integer autoId) {
this.autoId = autoId;
}
public String getAutotype() {
return autotype;
}
public void setAutotype(String autotype) {
this.autotype = autotype;
}
public String getAutonum() {
return autonum;
}
public void setAutonum(String autonum) {
this.autonum = autonum;
}
@ManyToOne()
@JoinColumn(name="garageid")
public Garage getGarage() {
return garage;
}
public void setGarage(Garage garage) {
this.garage = garage;
}
}
junit的测试方法
Java代码
@Test public void query() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpa-hibernate");
EntityManager em = factory.createEntityManager();
Garage garage = em.find(Garage.class, 1);
em.close();
factory.close();
}
jpa抓取策略详解fetch(lazy ,eager)(3)
时间:2010-12-23 javaey |