當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
011_Spring Data JPA多对多关系
生活随笔
收集整理的這篇文章主要介紹了
011_Spring Data JPA多对多关系
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1. 多對多的關(guān)聯(lián)關(guān)系
1.1. 權(quán)限和用戶是多對多的關(guān)聯(lián)關(guān)系
權(quán)限類(對應(yīng)表名: t_auth): 多方
角色類(對應(yīng)表名: t_role): 多方
權(quán)限角色類(對應(yīng)表名: t_auth_role): 中間表
1.2. 權(quán)限表
1.3. 角色表?
1.4. 權(quán)限角色表?
2. 多對多的關(guān)聯(lián)關(guān)系例子
2.1. 創(chuàng)建一個名為spring-data-jpa-many2many的Java項目, 同時添加相關(guān)jar包, 并添加JUnit能力。
?
2.2. 新建Role.java?
package com.bjbs.pojo;import java.io.Serializable; 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.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table;@Entity // 指定該類是實(shí)體類 @Table(name = "t_role") // 指定數(shù)據(jù)庫表名(表名和實(shí)體類對應(yīng)) public class Role implements Serializable {private static final long serialVersionUID = 1L;@Id // 指定為主鍵@GeneratedValue(strategy = GenerationType.IDENTITY) // 指定主鍵生成策略@Column(name = "id") // 指定表中列名(列名和屬性名對應(yīng))private Integer id;@Column(name = "name")private String name; // 角色名// fetch=FetchType.EAGER立即加載@ManyToMany(cascade=CascadeType.PERSIST, fetch=FetchType.EAGER)// @JoinTable: 配置中間表信息// joinColumns: 建立當(dāng)前表在中間表中的外鍵字段@JoinTable(name="t_auth_role", joinColumns=@JoinColumn(name="r_id"), inverseJoinColumns=@JoinColumn(name="a_id"))private Set<Auth> auths = new HashSet<Auth>();public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Set<Auth> getAuths() {return auths;}public void setAuths(Set<Auth> auths) {this.auths = auths;}@Overridepublic String toString() {return "Role [id=" + id + ", name=" + name + "]";}}2.3. 新建Auth.java
package com.bjbs.pojo;import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table;@Entity // 指定該類是實(shí)體類 @Table(name = "t_auth") // 指定數(shù)據(jù)庫表名(表名和實(shí)體類對應(yīng)) public class Auth implements Serializable {private static final long serialVersionUID = 1L;@Id // 指定為主鍵@GeneratedValue(strategy = GenerationType.IDENTITY) // 指定主鍵生成策略@Column(name = "id") // 指定表中列名(列名和屬性名對應(yīng))private Integer id;@Column(name = "name")private String name; // 權(quán)限名@ManyToMany(mappedBy="auths")private Set<Role> roles = new HashSet<Role>();public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Set<Role> getRoles() {return roles;}public void setRoles(Set<Role> roles) {this.roles = roles;}@Overridepublic String toString() {return "Auth [id=" + id + ", name=" + name + "]";}}2.4. 新建RoleRepository.java
package com.bjbs.dao;import org.springframework.data.jpa.repository.JpaRepository; import com.bjbs.pojo.Role;/*** 參數(shù)一T: 當(dāng)前需要映射的實(shí)體; 參數(shù)二 T: 當(dāng)前映射的實(shí)體中的id的類型*/ public interface RoleRepository extends JpaRepository<Role, Integer> {}2.5. 新建TestRoleRepository.java
package com.bjbs.test;import java.util.Set; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.bjbs.dao.RoleRepository; import com.bjbs.pojo.Role; import com.bjbs.pojo.Auth;@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class TestRoleRepository {@Autowiredprivate RoleRepository roleRepository;@Testpublic void findOne() {Role role = roleRepository.findOne(1);System.out.println(role);Set<Auth> auths = role.getAuths();for (Auth auth : auths) {System.out.println(auth);}}@Testpublic void save() {// 創(chuàng)建角色Role role = new Role();role.setName("張三");// 創(chuàng)建權(quán)限Auth auth = new Auth();auth.setName("注冊用戶");// 建立關(guān)系role.getAuths().add(auth);auth.getRoles().add(role);// 保存數(shù)據(jù)roleRepository.save(role);} }2.6. 在src下新建application.properties
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://192.168.25.138:3306/StudyMybatis?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai spring.datasource.username=root spring.datasource.password=lyw1234562.7. 在src下新建applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:jpa="http://www.springframework.org/schema/data/jpa"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"><!-- 配置讀取properties文件的工具類 --><context:property-placeholder location="classpath:application.properties" /><!-- 配置c3p0數(shù)據(jù)庫連接池 --><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="jdbcUrl" value="${spring.datasource.url}" /><property name="driverClass" value="${spring.datasource.driverClassName}" /><property name="user" value="${spring.datasource.username}" /><property name="password" value="${spring.datasource.password}" /></bean><!-- Spring整合JPA 配置EntityManagerFactory --><bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"><property name="dataSource" ref="dataSource" /><property name="jpaVendorAdapter"><bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"><!-- hibernate相關(guān)的屬性的注入 --><!-- 配置數(shù)據(jù)庫類型 --><property name="database" value="MYSQL" /><!-- 正向工程 自動創(chuàng)建表 --><!-- <property name="generateDdl" value="true" /> --><!-- 顯示執(zhí)行的SQL --><property name="showSql" value="true" /></bean></property><!-- 掃描實(shí)體的包 --><property name="packagesToScan"><list><value>com.bjbs.pojo</value></list></property></bean><!-- 配置Hibernate的事務(wù)管理器 --><bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"><property name="entityManagerFactory" ref="entityManagerFactory" /></bean><!-- 配置開啟注解事務(wù)處理 --><tx:annotation-driven transaction-manager="transactionManager" /><!-- 配置springIOC的注解掃描 --><context:component-scan base-package="com.bjbs.service" /><!-- Spring Data JPA 的配置 --><!-- base-package: 掃描dao接口所在的包 --><jpa:repositories base-package="com.bjbs.dao" /> </beans>2.8. 查詢角色
2.9. 保存角色?
總結(jié)
以上是生活随笔為你收集整理的011_Spring Data JPA多对多关系的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 010_Spring Data JPA一
- 下一篇: 012_Spring Data Redi