zoukankan      html  css  js  c++  java
  • JPA-Hibernate 多对多关系映射

    (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 }
  • 相关阅读:
    红黑树的修正过程
    配置文件elasticsearch.yml详解
    HEAD插件安装
    css reset.css
    vue-router之router-link
    vue2.0 代码功能片段
    vue2.0的常用功能简介
    electron 的中文文档的地址 以及 窗口改变的步骤
    ph 的使用步骤
    git 提交的步骤
  • 原文地址:https://www.cnblogs.com/mituxiaogaoyang/p/8397643.html
Copyright © 2011-2022 走看看