(1)实体类
@Entity @Table(name = "erp_role") public class Role { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name; private String description; @ManyToMany @JoinTable(name = "erp_role_priv", joinColumns = @JoinColumn(name = "roleid"), inverseJoinColumns = @JoinColumn(name = "privid")) private Set<Priv> privs = new HashSet<>(); //省略get和set方法 }
1 @Entity 2 @Table(name = "erp_priv") 3 public class Priv { 4 @Id 5 private Integer id; 6 private String name; 7 private String link; 8 private Integer parentid; 9 private String icon; 10 //省略get和set方法 11 }
(2)测试类
1 public class RoleTest { 2 private static EntityManagerFactory emf; 3 private EntityManager em; 4 private EntityTransaction tx; 5 6 @BeforeClass 7 public static void init() { 8 emf = Persistence.createEntityManagerFactory("jpa"); 9 } 10 11 @AfterClass 12 public static void destory() { 13 emf = null; 14 } 15 16 @Before 17 public void setUp() { 18 em = emf.createEntityManager(); 19 tx = em.getTransaction(); 20 tx.begin(); 21 } 22 23 @After 24 public void tearDown() { 25 tx.commit(); 26 em.close(); 27 } 28 29 @Test 30 public void testAddRole() { 31 Role role = new Role(); 32 role.setName("新增角色"); 33 role.setDescription("新增角色描述"); 34 35 role.getPrivs().add(em.getReference(Priv.class, 23)); 36 role.getPrivs().add(em.getReference(Priv.class, 24)); 37 38 em.persist(role); 39 } 40 41 @Test 42 public void testDeleteRole() { 43 Role role = em.find(Role.class, 5); 44 em.remove(role); 45 } 46 47 @Test 48 public void testGetRoles() { 49 TypedQuery<Role> query = em.createQuery("from Role", Role.class); 50 query.getResultList().forEach(role -> System.out.println(role.getPrivs())); 51 } 52 }