欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Hibernate:JPA的多对多操作

程序员文章站 2022-04-24 10:30:58
...

实体类User.java

@Entity
@Table(name = "user")
public class User {

	@Id
	@Column(name = "user_id")
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Integer userId;
	@Column(name = "user_name")
	private String userName;
	@ManyToMany(mappedBy = "user", cascade = CascadeType.ALL)
	private Set<Role> role = new HashSet<>(0);

实体类Role.java

@Entity
@Table(name = "role")
public class Role {

	@Id
	@Column(name = "role_id")
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Integer roleId;
	@Column(name = "role_name")
	private String roleName;
	@ManyToMany(cascade = CascadeType.ALL)
	@JoinTable(name = "user_role", joinColumns = { @JoinColumn(name = "role_id", referencedColumnName = "role_id") }, // 写的是当前实体在中间表的外键字段
			inverseJoinColumns = { @JoinColumn(name = "user_id", referencedColumnName = "user_id") }) // 写的是对方实体在中间表的外键字段
	private Set<User> user = new HashSet<>(0);

级联保存

public void save() {
	User user1 = new User();
	User user2 = new User();
	user1.setUserName("用户一");
	user2.setUserName("用户二");

	Role role1 = new Role();
	Role role2 = new Role();
	Role role3 = new Role();
	role1.setRoleName("角色一");
	role2.setRoleName("角色二");
	role3.setRoleName("角色三");

	user1.getRole().add(role1);
	user1.getRole().add(role2);
	user2.getRole().add(role2);
	user2.getRole().add(role3);

	role1.getUser().add(user1);
	role2.getUser().add(user1);
	role2.getUser().add(user2);
	role3.getUser().add(user2);

	EntityManager entityManager = JPAUtils.createEntityManager();
	EntityTransaction entityTransaction = entityManager.getTransaction();
	entityTransaction.begin();
	entityManager.persist(role1);
	entityManager.persist(role2);
	entityManager.persist(role3);
	entityTransaction.commit();
	entityManager.close();
}

级联删除:双向级联删除,多对多中不能配置,会删除所有表中数据

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