Hibernate JPA注解多对多

一、实体类

User:

/**
 * 用户(多方)
 * @author http://www.yiidian.com
 */
@Entity
@Table(name="t_user")
public class User implements Serializable{
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	@Column(name="id")
	private Integer id;
	@Column(name="user_name")
	private String userName;
	
	//关联角色
	@ManyToMany(targetEntity=User.class)
	//@JoinTable: 用于映射中间表
	//joinColumns: 当前方在中间表的外键字段名称
	//inverseJoinColumns:对方在中间表的外键字段名称
	@JoinTable(
			name="t_user_role",
			joinColumns=@JoinColumn(name="user_id"),
			inverseJoinColumns=@JoinColumn(name="role_id"))
	private Set<Role> roles = new HashSet<Role>();

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public Set<Role> getRoles() {
		return roles;
	}

	public void setRoles(Set<Role> roles) {
		this.roles = roles;
	}
	
	
}

Role:

/**
 * 角色(多方)
 * @author http://www.yiidian.com
 */
@Entity
@Table(name="t_role")
public class Role implements Serializable{
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	@Column(name="id")
	private Integer id;
	@Column(name="role_name")
	private String roleName;
	
	//关联用户
	@ManyToMany(targetEntity=User.class,mappedBy="roles")
	private Set<User> users = new HashSet<User>();

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getRoleName() {
		return roleName;
	}

	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}

	public Set<User> getUsers() {
		return users;
	}

	public void setUsers(Set<User> users) {
		this.users = users;
	}
	
}

二、配置hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
	
<hibernate-configuration>	
	<!-- 连接数据库的参数 -->
<session-factory>
	<!-- 1.连接数据库参数 -->
	<property name="hibernate.connection.driver_class">
		com.mysql.jdbc.Driver
	</property>
	<property name="hibernate.connection.url">
		jdbc:mysql://localhost:3306/hibernate
	</property>
	<property name="hibernate.connection.username">root</property>
	<property name="hibernate.connection.password">root</property>

	<!-- 整合c3p0 -->
	<property name="hibernate.connection.provider_class">
		org.hibernate.c3p0.internal.C3P0ConnectionProvider
	</property>
	<!-- c3p0详细配置 -->
	<property name="c3p0.min_size">10</property>
	<property name="c3p0.max_size">20</property>

	<!-- hibernate方言 -->
	<property name="hibernate.dialect">
		org.hibernate.dialect.MySQLDialect
	</property>

	<!-- 2.hibernate扩展参数 -->
	<property name="hibernate.show_sql">true</property>
	<property name="hibernate.format_sql">true</property>
	<property name="hibernate.hbm2ddl.auto">update</property>

	<!-- 让session被TheadLocal管理 -->
	<property name="hibernate.current_session_context_class">
		thread
	</property>
	<property name="dialect"></property>
	<mapping class="com.yiidian.domain.Role" />
	<mapping class="com.yiidian.domain.User" />

</session-factory>
</hibernate-configuration>	

三、编写测试类

/**
 * 演示多对多的映射
 * @author http://www.yiidian.com
 */
public class Demo {
	
	@Test
	public void test1(){
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		
		User u1 = new User();
		u1.setUserName("小泽");
		
		User u2 = new User();
		u2.setUserName("小仓");
		
		Role r1 = new Role();
		r1.setRoleName("视觉总监");
		
		Role r2 = new Role();
		r2.setRoleName("动作指导");
		
		
		u1.getRoles().add(r1);
		r1.getUsers().add(u1);
		
		u2.getRoles().add(r2);
		r2.getUsers().add(u2);
		
		session.save(u1);
		session.save(u2);
		session.save(r1);
		session.save(r2);
		
		tx.commit();
	}
	
}

执行程序,控制台输出:

Hibernate: 
    insert 
    into
        t_user
        (user_name) 
    values
        (?)
Hibernate: 
    insert 
    into
        t_user
        (user_name) 
    values
        (?)
Hibernate: 
    insert 
    into
        t_role
        (role_name) 
    values
        (?)
Hibernate: 
    insert 
    into
        t_role
        (role_name) 
    values
        (?)
Hibernate: 
    insert 
    into
        t_user_role
        (user_id, role_id) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        t_user_role
        (user_id, role_id) 
    values
        (?, ?)

一共生成三张表:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现Spring Boot JPA中的多对多增删改操作,可以按照以下步骤进行操作: 1. 首先,在Spring Boot项目中创建两个实体类,表示多对多关系的两个实体对象。这两个实体类需要使用`@ManyToMany`注解来定义它们之间的关联关系。同时,需要在两个实体类中分别定义对方实体类的集合属性,并使用`@JoinTable`注解来指定关联表的名称和关联字段的配置。 2. 接下来,创建两个Repository接口分别用于操作这两个实体类。在这两个接口中,可以使用Spring Data JPA提供的方法来进行增删改查的操作。 3. 在需要进行多对多关系操作的地方,可以通过调用相关的Repository方法来实现增删改的功能。例如,可以使用`save()`方法来保存对象,使用`delete()`方法来删除对象。 4. 如果需要进行关联表的增删改操作,可以使用`cascade`属性来定义级联操作。例如,可以在一方实体类的集合属性上使用`cascade = {CascadeType.PERSIST, CascadeType.MERGE}`来指定级联保存和更新操作。 5. 最后,可以通过Controller来实现对多对多关系的增删改操作的接口。可以使用`@PostMapping`来处理增加操作,使用`@DeleteMapping`来处理删除操作,使用`@PutMapping`来处理更新操作。 请注意,以上是一种通用的实现方式,具体的代码实现需要根据你的实际需求和实体类设计进行相应的调整。同时,为了更好地理解和实践这个过程,建议参考引用中提供的教程,其中提供了关于Spring Boot JPA的增删改查的详细示例代码。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [springbootjpa实现增删改](https://blog.csdn.net/qq_57392213/article/details/128450489)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [Springboot整合Hibernate thymeleaf,添删改查,分页查询等,单元测试,亲测百分之白可运行](https://download.csdn.net/download/s54156s4/10606800)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [SpringBoot JPAJPARepository的增删改(简单理解)](https://blog.csdn.net/qq_43055855/article/details/110144484)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值