栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

2个外键从不同实体进入新表休眠

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

2个外键从不同实体进入新表休眠

您需要一个关联表,通常出于各种原因通常在JPA中构建该关联表,主要是为了控制表中的内容,或者在这种情况下映射n路M:N关系。

创建所有实体:

@Entitypublic class User {    @Id @GeneratedValue(strategy=GenerationType.AUTO)     private Integer id;    private String userName;    @oneToMany(mappedBy="user")    private Set<UserDepartmentRoleAssociation> associations;... etc}

@Entitypublic class Department {    @Id @GeneratedValue(strategy=GenerationType.AUTO)     private Integer id;    private String department;    @oneToMany(mappedBy="department")    private Set<UserDepartmentRoleAssociation> associations;    ... etc}

@Entitypublic class Role {    @Id @GeneratedValue(strategy=GenerationType.AUTO)     private Integer id;    private String role;    ... etc}

并创建关联表和ID类。

@Entitypublic class UserDepartmentRoleAssociation {    @EmbeddedId private UserDepartmentRoleAssociationId id;    @ManyToOne @MapsId("userId")    private User user;    @ManyToOne @MapsId("departmentId")    private Department department;    @ManyToOne @MapsId("roleId")    private Role role;    public UserDepartmentRoleAssociation() {        id = new UserDepartmentRoleAssociationId();    }    ... etc}

@Embeddablepublic class UserDepartmentRoleAssociationId implements Serializable {    private Integer userId;    private Integer departmentId;    private Integer roleId;    ... etc}

并保持一段感情然后…

        User user = new User();        user.setUserName("user1");        Department department = new Department();        department.setDepartment("department 1");        Role role = new Role();        role.setRole("Manager");        UserDepartmentRoleAssociation association = new UserDepartmentRoleAssociation();        association.setUser(user);        association.setDepartment(department);        association.setRole(role);        em.persist(user);        em.persist(department);        em.persist(role);        em.persist(association);

并通过join fetch读取它

User user = em.createQuery("select u from User u left join fetch u.associations ass left join fetch ass.department left join fetch ass.role where u.id = :id", User.class).setParameter("id", 1).getSingleResult();

请注意,在这些情况下,我使用了in

Set
而不是
List
in
Department
User
它引起的问题要少得多。另外,
associations
当我保留关系时,我也不必创建,因为它
UserDepartmentRoleAssociation
是拥有实体,因此也可以保留。这些
associations
集是由JPA在读取记录时创建的。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/615500.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号