其他分享
首页 > 其他分享> > Hibernate:JPA的一对多操作

Hibernate:JPA的一对多操作

作者:互联网

实体类Cla.java

@Entity
@Table(name = "cla")
public class Cla {

	@Id
	@Column(name = "cla_id")
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Integer claId;
	@Column(name = "cla_name")
	private String claName;
	@OneToMany(targetEntity = Stu.class, mappedBy = "cla", cascade = CascadeType.ALL, fetch = FetchType.LAZY) // mappedBy="对方的属性":表示两个表关系之间的控制权交给对方
	private Set<Stu> stu = new HashSet<Stu>(0);

实体类Stu.java

@Entity
@Table(name = "stu")
public class Stu {

	@Id
	@Column(name = "stu_id")
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Integer stuId;
	@Column(name = "stu_name")
	private String stuName;
	@ManyToOne(targetEntity = Cla.class)
	// joinColumns:建立主表与从表外键关系
	// name属性:从表的外键字段名
	// referencedColumnName属性:主表的主键字段名
	@JoinColumn(name = "cla_id", referencedColumnName = "cla_id")
	private Cla cla;

一对多保存

public void save() {
	Cla cla = new Cla();
	cla.setClaName("体育生");
	Stu stu = new Stu();
	stu.setStuName("赵云");

	cla.getStu().add(stu);
	stu.setCla(cla);

	EntityManager entityManager = JPAUtils.createEntityManager();
	EntityTransaction entityTransaction = entityManager.getTransaction();
	entityTransaction.begin();
	entityManager.persist(cla);
	entityManager.persist(stu);
	entityTransaction.commit();
	entityManager.close();
}

级联更新

public void update() {
	Stu stu = new Stu();
	stu.setStuName("吕布");

	EntityManager entityManager = JPAUtils.createEntityManager();
	EntityTransaction entityTransaction = entityManager.getTransaction();
	entityTransaction.begin();
	Cla cla = entityManager.find(Cla.class, 1);
	cla.getStu().add(stu);
	stu.setCla(cla);
	entityTransaction.commit();
	entityManager.close();
}

级联删除

public void remove() {
	EntityManager entityManager = JPAUtils.createEntityManager();
	EntityTransaction entityTransaction = entityManager.getTransaction();
	entityTransaction.begin();
	Cla cla = entityManager.find(Cla.class, 1);
	entityManager.remove(cla);
	entityTransaction.commit();
	entityManager.close();
}

对象导航查询

public void query() {
	EntityManager entityManager = JPAUtils.createEntityManager();
	EntityTransaction entityTransaction = entityManager.getTransaction();
	entityTransaction.begin();
	Cla cla = entityManager.find(Cla.class, 1);
	System.out.println(cla);
	Set<Stu> stus = cla.getStu();
	System.out.println(stus);
	entityTransaction.commit();
	entityManager.close();
}

标签:entityManager,name,JPA,cla,Cla,stu,Hibernate,一对,entityTransaction
来源: https://blog.csdn.net/lovecuidong/article/details/100134364