Home  >  Q&A  >  body text

spring-mvc - 问个Java 遇见数据库时的对象设计问题

用的 spring mvc + mybatis3 框架,假设有 用户与角色两张表, 以及一张关联表,分别对应的实体 userroleuser_role. 在 service 层, 为这 2 个对象分别建立 IUserService, IRoleService

我想问的是:

  1. 需要为中间表建对象user_role吗?
  2. 如果建了user_role, 需要建IUserRoleService吗?
  3. 中间表的关系维护职责应该放哪个service, 如删除用户同时需删除与角色的关系,删除角色,需删除与用户的关系等等。。

多谢指点!

黄舟黄舟2716 days ago379

reply all(3)I'll reply

  • 高洛峰

    高洛峰2017-04-17 13:03:24

    No need at all. The database design does not have to be consistent with the Java object design. Just include role in your user object, or the role object contains user.

    Supplement:

    public class UserService {
        @Autowired
        private UserRepository userRepository;
    
        @Autowired
        private UserRoleRepository userRoleRepository;
    
        public void deleteUser(User user) {
            userRepository.delete(user);
            userRoleRepository.deleteRoles(user);
        }
    }
    
    public class RoleService {
        @Autowired
        private RoleRepository roleRepository;
    
        @Autowired
        private UserRoleRepository userRoleRepository;
    
        public void deleteRole(Role role) {
            roleRepository.delete(role);
            userRoleRepository.deleteUsers(role);
        }
    }    
    

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 13:03:24

    I would like to ask again, to obtain the role corresponding to the user, should it be placed in getUserRoles(User user), UserService or RoleService? What is the basis for judgment?

    reply
    0
  • 迷茫

    迷茫2017-04-17 13:03:24

    It seems that it can be placed anywhere. If you want to avoid arguments, put it in a separate command

    reply
    0
  • Cancelreply