Просмотр исходного кода

feat: group dao层完善(未可用)

370774330@qq.com 5 лет назад
Родитель
Сommit
72f78fe1e8

+ 61 - 19
web/src/main/java/seecoder/devcloud/web/dao/InsertUpdateSqlProvider.java

@@ -1,11 +1,10 @@
 package seecoder.devcloud.web.dao;
 package seecoder.devcloud.web.dao;
 
 
-import org.apache.ibatis.annotations.Param;
 import org.apache.ibatis.jdbc.SQL;
 import org.apache.ibatis.jdbc.SQL;
 
 
 import java.lang.reflect.Field;
 import java.lang.reflect.Field;
-import java.util.HashMap;
-import java.util.Map;
+import java.util.*;
+import java.util.stream.Collectors;
 
 
 
 
 /**
 /**
@@ -16,7 +15,6 @@ import java.util.Map;
 public class InsertUpdateSqlProvider {
 public class InsertUpdateSqlProvider {
 
 
     /**
     /**
-     * 忽视部分
      * @param obj 插入对象, 用来获取字段和表名
      * @param obj 插入对象, 用来获取字段和表名
      * @param ignoredCols 插入时需要忽略的列名 列名格式是Underscore,如created_at
      * @param ignoredCols 插入时需要忽略的列名 列名格式是Underscore,如created_at
      * @return sql
      * @return sql
@@ -24,7 +22,7 @@ public class InsertUpdateSqlProvider {
     public static String insert(Object obj,String... ignoredCols){
     public static String insert(Object obj,String... ignoredCols){
         Map<String, String> map;
         Map<String, String> map;
         try {
         try {
-            map = getFieldsMap(obj, true);
+            map = getFieldsMap(obj, true, false);
             // 创建 需要赋当前的时间的timestamp字段 在这里排除,否则无法正常赋值
             // 创建 需要赋当前的时间的timestamp字段 在这里排除,否则无法正常赋值
             for (String col: ignoredCols){
             for (String col: ignoredCols){
                 map.remove(col);
                 map.remove(col);
@@ -32,11 +30,10 @@ public class InsertUpdateSqlProvider {
         } catch (IllegalArgumentException | IllegalAccessException e) {
         } catch (IllegalArgumentException | IllegalAccessException e) {
             throw new RuntimeException(e);
             throw new RuntimeException(e);
         }
         }
-        return insert(obj, map);
+        return getInsertSQL(obj, map);
     }
     }
 
 
-
-    private static String insert(Object obj,Map<String, String> map){
+    private static String getInsertSQL(Object obj, Map<String, String> map){
         return new SQL() {
         return new SQL() {
             {
             {
                 INSERT_INTO(getTableName(obj));
                 INSERT_INTO(getTableName(obj));
@@ -47,14 +44,47 @@ public class InsertUpdateSqlProvider {
         }.toString();
         }.toString();
     }
     }
 
 
-    private static String updateById(Object obj, boolean includeNullValueField) {
+    /**
+     * 更新obj所含的字段,但是不包括为null的字段
+     */
+    public static String updateById(Object obj) {
+        return updateById(obj, false);
+    }
+
+    /**
+     * 更新obj所含的字段,但是包括为null的字段
+     */
+    public static String updateWithNullById(Object obj) {
+        return updateById(obj, true);
+    }
+
+    /**
+     * 按传入的列名更新字段
+     */
+    public static String updateWithColsById(Object obj, String... cols) {
+        return updateById(obj, true, cols);
+    }
+
+    private static String updateById(Object obj, boolean includeNullValueField, String... cols) {
         Map<String, String> map;
         Map<String, String> map;
         try {
         try {
-            map = getFieldsMap(obj, includeNullValueField);
+            map = getFieldsMap(obj, includeNullValueField, cols.length == 0);
             map.remove("id");
             map.remove("id");
+            //有可变长参数就保留可边长参数
+            if (cols.length!=0){
+                Set<String> colsSet = Arrays.stream(cols).collect(Collectors.toSet());
+                map = map.entrySet().stream()
+                        .filter(e -> colsSet.contains(e.getKey()))
+                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
+
+            }
         } catch (IllegalArgumentException | IllegalAccessException e) {
         } catch (IllegalArgumentException | IllegalAccessException e) {
             throw new RuntimeException(e);
             throw new RuntimeException(e);
         }
         }
+        return getUpdateSQL(obj,map);
+    }
+
+    private static String getUpdateSQL(Object obj, Map<String, String> map){
         return new SQL() {
         return new SQL() {
             {
             {
                 UPDATE(getTableName(obj));
                 UPDATE(getTableName(obj));
@@ -66,15 +96,17 @@ public class InsertUpdateSqlProvider {
         }.toString();
         }.toString();
     }
     }
 
 
-    public static String updateById(Object obj) {
-        return updateById(obj, true);
-    }
 
 
-    public static String updateNonNullById(Object obj) {
-        return updateById(obj, false);
-    }
-
-    private static Map<String, String> getFieldsMap(Object obj, boolean includeNullValue)
+    /**
+     *
+     * @param obj 获取字段名的对象
+     * @param includeNullValue 是否要获取为null的字段名
+     * @param singleParam sql参数只有一个实体类的时候 设置为true,多个参数的时候设置false
+     * @return
+     * @throws IllegalArgumentException
+     * @throws IllegalAccessException
+     */
+    private static Map<String, String> getFieldsMap(Object obj, boolean includeNullValue, boolean singleParam)
             throws IllegalArgumentException, IllegalAccessException {
             throws IllegalArgumentException, IllegalAccessException {
         HashMap<String, String> result = new HashMap<>();
         HashMap<String, String> result = new HashMap<>();
         Class<?> cls = obj.getClass();
         Class<?> cls = obj.getClass();
@@ -89,8 +121,18 @@ public class InsertUpdateSqlProvider {
             } catch (NoSuchMethodException | SecurityException e) {
             } catch (NoSuchMethodException | SecurityException e) {
                 continue;
                 continue;
             }
             }
+            /**
+             * 单参数的时候
+             * #{colname}可以直接取到实体的属性
+             * 多参数的时候
+             * #{param1.colname}来取实体的属性
+             */
+            String paramPrefix =  singleParam? "#{" : "#{param1.";
             if ((!"id".equals(col) && includeNullValue) || f.get(obj) != null) {
             if ((!"id".equals(col) && includeNullValue) || f.get(obj) != null) {
-                result.put(camelCase2Underscore(col), "#{param1."+ col + "}");
+
+
+
+                result.put(camelCase2Underscore(col), paramPrefix + col + "}");
             }
             }
         }
         }
         return result;
         return result;

+ 13 - 1
web/src/main/java/seecoder/devcloud/web/dao/user/GroupMapper.java

@@ -28,9 +28,21 @@ public interface GroupMapper {
     @UpdateProvider(type= InsertUpdateSqlProvider.class, method="updateById")
     @UpdateProvider(type= InsertUpdateSqlProvider.class, method="updateById")
     int update(Group group);
     int update(Group group);
 
 
-
+    @Select("select * from group where id = #{id}")
     Group findGroupById(Integer id);
     Group findGroupById(Integer id);
+
+    @Select("select * from group where id = #{id}")
+    @Result(column = "id", property = "member",many = @Many(
+            select = ""
+    ))
+    Group findWithMembersById(Integer id);
+
+    @Deprecated
     Group findGroupByShareLink(String shareLink);
     Group findGroupByShareLink(String shareLink);
 
 
 
 
+
+
+
+
 }
 }

+ 37 - 0
web/src/main/java/seecoder/devcloud/web/dao/user/GroupMemberMapper.java

@@ -0,0 +1,37 @@
+package seecoder.devcloud.web.dao.user;
+
+import jnr.ffi.annotations.In;
+import org.apache.ibatis.annotations.*;
+import seecoder.devcloud.web.po.user.Group;
+import seecoder.devcloud.web.po.user.User;
+
+import java.util.List;
+
+/**
+ * @author PuHong Weng
+ * @date 2021/3/4
+ * @description:
+ */
+public interface GroupMemberMapper {
+
+    @Insert("insert into group_member (group_id,user_id) values (#{groupId},#{userId}) ")
+    int insert(int groupId,int userId);
+
+    @Delete("delete from group_member where group_id = #{groupId} and user_id = #{userId}")
+    int delete(int groupId, int userId);
+
+    @Select("select user_id from group_member where group_id = #{groupId}")
+    List<Integer> selectUserIdsByGroupId(int groupId);
+
+    @Select("select group_id from group_member where user_id = #{userId}")
+    List<Integer> selectGroupIdsByUserId(int groupId);
+
+    @Select("select user_id from group_member where group_id = #{groupId}")
+    @Result(column = "user_id", one = @One(select = "seecoder.devcloud.web.service.impl.user.findById"))
+    List<User> selectUserByGroupId(int groupId);
+
+
+    @Select("select group_id from group_member where user_id = #{userId}")
+    List<Group> selectGroupByUserId(int groupId);
+
+}

+ 2 - 3
web/src/main/java/seecoder/devcloud/web/dao/user/UserMapper.java

@@ -7,6 +7,7 @@ import org.springframework.data.domain.Pageable;
 import seecoder.devcloud.web.dao.InsertUpdateSqlProvider;
 import seecoder.devcloud.web.dao.InsertUpdateSqlProvider;
 import seecoder.devcloud.web.po.user.User;
 import seecoder.devcloud.web.po.user.User;
 
 
+import java.sql.Timestamp;
 
 
 
 
 @Mapper
 @Mapper
@@ -19,7 +20,7 @@ public interface UserMapper {
 	int insert(User user,String... ignoredCols);
 	int insert(User user,String... ignoredCols);
 
 
 	@UpdateProvider(type= InsertUpdateSqlProvider.class, method="updateById")
 	@UpdateProvider(type= InsertUpdateSqlProvider.class, method="updateById")
-	int updateById(Object bean);
+	int updateById(User user);
 
 
 	@Delete("delete from user where id = #{id}")
 	@Delete("delete from user where id = #{id}")
 	int delete(User user);
 	int delete(User user);
@@ -34,7 +35,5 @@ public interface UserMapper {
 	@Select("select * from user where email = #{email}")
 	@Select("select * from user where email = #{email}")
 	User findByEmail(String email);
 	User findByEmail(String email);
 
 
-	@Select("select * from user where email = #{email}")
-	Page<User> findAllByUsernameLike(String search, Pageable pageable);
 
 
 }
 }

+ 92 - 118
web/src/main/java/seecoder/devcloud/web/service/impl/user/GroupServiceImp.java

@@ -1,118 +1,92 @@
-//package seecoder.devcloud.web.service.impl.user;
-//
-//
-//import org.gitlab4j.api.GitLabApiException;
-//import org.springframework.beans.factory.annotation.Autowired;
-//import org.springframework.context.ApplicationContext;
-//import org.springframework.stereotype.Service;
-//import org.springframework.transaction.annotation.Transactional;
-//import seecoder.devcloud.api.gitlab.GitlabApi;
-//import seecoder.devcloud.api.gitlab.model.GitlabGroup;
-//import seecoder.devcloud.common.exceptions.EntityNotFoundException;
-//import seecoder.devcloud.web.dao.user.GroupMapper;
-//import seecoder.devcloud.web.dao.user.UserMapper;
-//import seecoder.devcloud.web.enums.GroupType;
-//import seecoder.devcloud.web.po.user.Group;
-//import seecoder.devcloud.web.po.user.User;
-//import seecoder.devcloud.web.service.user.GroupService;
-//import seecoder.devcloud.web.vo.user.CustomUserDetails;
-//import seecoder.devcloud.web.vo.user.GroupVO;
-//
-//import java.util.ArrayList;
-//import java.util.List;
-//import java.util.UUID;
-//
-///**
-// * @ClassName GroupServiceImp
-// * @PackageName com.moekr.moocoder.logic.service.impl
-// * @Author sheen
-// * @Date 2019/1/9
-// * @Version 1.0
-// * @Description //TODO
-// **/
-//@Service
-//public class GroupServiceImp implements GroupService {
-//    private final GroupMapper groupMapper;
-//    private final UserMapper userMapper;
-//    private final GitlabApi gitlabApi;
-//    @Autowired
-//    ApplicationContext applicationContext;
-//
-//    @Autowired
-//    public GroupServiceImp(GroupMapper groupMapper, UserMapper userMapper, GitlabApi gitlabApi) {
-//        this.groupMapper = groupMapper;
-//        this.userMapper = userMapper;
-//        this.gitlabApi = gitlabApi;
-//    }
-//
-//    @Override
-//    @Transactional
-//    public GroupVO createGroup(String name,  Integer userId) throws EntityNotFoundException {
-//        User user = userMapper.findById(userId);
-//
-//        List<User> members = new ArrayList<>();
-//        members.add(user);
-//        GitlabGroup gitGroup;
-//        try {
-//            gitGroup = gitlabApi.createGroup(name);
-//            gitlabApi.addMemberToGroup(gitGroup.getId(), user.getId());
-//        } catch (GitLabApiException e) {
-//            throw new RuntimeException("创建Group时发生异常[" + e.getMessage() + "]");
-//        }
-//        Group group = Group.builder()
-//                .id(gitGroup.getId())
-//                .name(name)
-//                .namespace(gitGroup.getNamespace())
-//                .shareLink(UUID.randomUUID().toString().replace("-", ""))
-//                .type(GroupType.GROUP)
-//                .members(members)
-//                .build();
-//        groupMapper.insert(group, "members");
-//
-//        //todo 组用户表
-//        userMapper.save(user);
-//        // 发出小组创建的事件
-//        GroupVO groupVO = new GroupVO(group);
-//        //applicationContext.publishEvent(new GroupCreateEvent(this, courseId, groupVO));
-//        return groupVO;
-//    }
-//
-//
-//    @Override
-//    @Transactional
-//    public GroupVO addMember(String code, CustomUserDetails userDetails) throws EntityNotFoundException {
-//        Group group = groupMapper.findGroupByShareLink(code);
-//        if (group == null) {
-//            throw new EntityNotFoundException("小组码错误!");
-//        }
-//        User user = userMapper.findByUsername(userDetails.getUsername());
-//        final boolean haveCourse = user.getCourses().contains(group.getCourses());
-//        if (!haveCourse) {
-//            throw new RuntimeException("尚未加入课程!");
-//        } else {
-//            final boolean isJoin = user.getGroup().stream()
-//                    .anyMatch(g -> g.getCourses().getId().equals(group.getCourses().getId()));
-//            if (isJoin) {
-//                throw new RuntimeException("已经加入小组!");
-//            }
-//            group.getMembers().add(user);
-//            try {
-//                gitlabApi.addMemberToGroup(group.getId(), user.getId());
-//            } catch (GitLabApiException e) {
-//                throw new RuntimeException("将成员加入Group时发生异常[" + e.getMessage() + "]");
-//            }
-//            groupMapper.save(group);
-//            userMapper.save(user);
-//            return new GroupVO(group);
-//        }
-//
-//    }
-//
-//
-//    @Override
-//    public GroupVO getGroupsById(Integer groupId) {
-//        Group get= groupMapper.findById(groupId).orElseGet(Group::new);
-//
-//        return new GroupVO(get);
-//    }
-//}
+package seecoder.devcloud.web.service.impl.user;
+
+
+import org.gitlab4j.api.GitLabApiException;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.ApplicationContext;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import seecoder.devcloud.api.gitlab.GitlabApi;
+import seecoder.devcloud.api.gitlab.model.GitlabGroup;
+import seecoder.devcloud.common.exceptions.EntityNotFoundException;
+import seecoder.devcloud.web.dao.user.GroupMapper;
+import seecoder.devcloud.web.dao.user.GroupMemberMapper;
+import seecoder.devcloud.web.dao.user.UserMapper;
+import seecoder.devcloud.web.enums.GroupType;
+import seecoder.devcloud.web.po.user.Group;
+import seecoder.devcloud.web.po.user.User;
+import seecoder.devcloud.web.service.user.GroupService;
+import seecoder.devcloud.web.vo.user.CustomUserDetails;
+import seecoder.devcloud.web.vo.user.GroupVO;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+
+
+@Service
+public class GroupServiceImp implements GroupService {
+    private final GroupMapper groupMapper;
+    private final UserMapper userMapper;
+    private final GroupMemberMapper groupMemberMapper;
+    private final GitlabApi gitlabApi;
+
+    @Autowired
+    public GroupServiceImp(GroupMapper groupMapper, UserMapper userMapper, GroupMemberMapper groupMemberMapper, GitlabApi gitlabApi) {
+        this.groupMapper = groupMapper;
+        this.userMapper = userMapper;
+        this.groupMemberMapper = groupMemberMapper;
+        this.gitlabApi = gitlabApi;
+    }
+
+    @Override
+    @Transactional
+    public GroupVO createGroup(String name,  Integer userId) throws EntityNotFoundException {
+        User user = userMapper.findById(userId);
+
+        List<User> members = new ArrayList<>();
+        members.add(user);
+        GitlabGroup gitGroup;
+        try {
+            gitGroup = gitlabApi.createGroup(name);
+            gitlabApi.addMemberToGroup(gitGroup.getId(), user.getId());
+        } catch (GitLabApiException e) {
+            throw new RuntimeException("创建Group时发生异常[" + e.getMessage() + "]");
+        }
+        Group group = Group.builder()
+                .id(gitGroup.getId())
+                .name(name)
+                .namespace(gitGroup.getNamespace())
+                .shareLink(UUID.randomUUID().toString().replace("-", ""))
+                .type(GroupType.GROUP)
+                .members(members)
+                .build();
+        groupMapper.insert(group, "members");
+        groupMemberMapper.insert(gitGroup.getId(),userId);
+        return new GroupVO(group);
+    }
+
+
+    @Override
+    @Transactional
+    public GroupVO addMember(Integer userId, Integer invitedUserId, Integer groupId) throws EntityNotFoundException {
+        List<Integer> userIds = groupMemberMapper.selectUserIdsByGroupId(groupId);
+        if (!userIds.contains(userId)) {
+            throw new EntityNotFoundException("小组邀请发生错误,用户没有权限!");
+        }
+        if (userIds.contains(invitedUserId)) {
+            throw new RuntimeException("邀请的用户已经加入小组!");
+        }
+        try {
+            gitlabApi.addMemberToGroup(groupId, invitedUserId);
+        } catch (GitLabApiException e) {
+            throw new RuntimeException("将成员加入Group时发生异常[" + e.getMessage() + "]");
+        }
+        groupMemberMapper.insert(groupId,invitedUserId);
+
+        return new GroupVO(group);
+        }
+
+    }
+
+}

+ 10 - 0
web/src/main/resources/SQLscripts/group.sql

@@ -0,0 +1,10 @@
+create table if not exists devcloud.`group`
+(
+    id         int                      not null
+        primary key,
+    name       varchar(23) charset utf8 not null,
+    namespace  int                      not null,
+    share_link varchar(63)              not null,
+    type       varchar(15) charset utf8 null
+);
+

+ 11 - 0
web/src/main/resources/SQLscripts/group_member.sql

@@ -0,0 +1,11 @@
+create table if not exists devcloud.group_member
+(
+    group_id int not null,
+    user_id  int not null,
+    constraint group_member_group_id_fk
+        foreign key (group_id) references devcloud.`group` (id)
+            on delete cascade,
+    constraint group_member_user_id_fk
+        foreign key (user_id) references devcloud.user (id)
+            on delete cascade
+);

+ 14 - 0
web/src/main/resources/SQLscripts/user.sql

@@ -0,0 +1,14 @@
+create table if not exists devcloud.user
+(
+    id         int                                 not null
+        primary key,
+    username   varchar(23)                         not null,
+    nickname   varchar(23)                         null,
+    password   char(64)                            not null,
+    phone      varchar(23)                         null,
+    email      varchar(63)                         not null,
+    role       varchar(15) charset utf8            null,
+    created_at timestamp default CURRENT_TIMESTAMP null,
+    namespace  int                                 null,
+    token      varchar(63)                         not null
+);

+ 3 - 3
web/src/test/java/seecoder/devcloud/web/service/user/UserServiceTest.java

@@ -67,8 +67,8 @@ class UserServiceTest {
     @Test
     @Test
     void delete() {
     void delete() {
         try {
         try {
-            //userService.delete(26);
-            gitLabApi.getUserApi().deleteUser(30);
+            //userService.delete(33);
+            gitLabApi.getUserApi().deleteUser(35);
             System.out.println(gitLabApi.getUserApi().getActiveUsers().stream().map(AbstractUser::getId).collect(Collectors.toList()));
             System.out.println(gitLabApi.getUserApi().getActiveUsers().stream().map(AbstractUser::getId).collect(Collectors.toList()));
         } catch (Exception e) {
         } catch (Exception e) {
             e.printStackTrace();
             e.printStackTrace();
@@ -92,7 +92,7 @@ class UserServiceTest {
     @Test
     @Test
     void changeUserInfo() {
     void changeUserInfo() {
         try {
         try {
-            userService.changeUserInfo(25,"gogoing");
+            userService.changeUserInfo(31,"gogoing");
         } catch (ServiceException e) {
         } catch (ServiceException e) {
             e.printStackTrace();
             e.printStackTrace();
             Assert.fail(e.getMessage());
             Assert.fail(e.getMessage());