Browse Source

1、用户角色关联

2、开启事务,确保表单数据的一致性
3、新增README.md文件
chubin
郑楚滨 3 months ago
parent
commit
a4d146df2e
  1. 21
      demo/demo/README.md
  2. 14
      demo/demo/src/main/java/demo/Controller/RoleController.java
  3. 44
      demo/demo/src/main/java/demo/Controller/UserController.java
  4. 26
      demo/demo/src/main/java/demo/Controller/UserRoleController.java
  5. 2
      demo/demo/src/main/java/demo/DemoApplication.java
  6. 25
      demo/demo/src/main/java/demo/Entity/UserDTO.java
  7. 25
      demo/demo/src/main/java/demo/Entity/UserRole.java
  8. 9
      demo/demo/src/main/java/demo/Mapper/UserMapper.java
  9. 26
      demo/demo/src/main/java/demo/Mapper/UserRoleMapper.java
  10. 52
      demo/demo/src/main/java/demo/Service/UserRoleService.java
  11. 7
      demo/demo/src/main/java/demo/Service/UserService.java
  12. 9
      demo/demo/src/test/java/demo/DemoApplicationTests.java

21
demo/demo/README.md

@ -0,0 +1,21 @@
用户管理
1、注册时要往用户表和用户_角色关联表里面添加信息
2、删除时,先删除用户_角色关联表里面的信息,再删除用户表里面的信息
3、修改时,先修改用户表里面的信息,再修改用户_角色关联表里面的信息
4、查询时,要查询角色表和用户_角色关联表里面的信息
注意:1、2、3要开启事务,一致性
角色管理
1、新增时直接新增即可
2、删除时,先判断用户_角色关联表里面的信息,则不能删除角色表里面的信息
3、修改时,直接修改即可,关联表只是存储角色ID,不可变
4、查询时,直接查询即可

14
demo/demo/src/main/java/demo/Controller/RoleController.java

@ -2,6 +2,7 @@ package demo.Controller;
import demo.Entity.*;
import demo.Service.RoleService;
import demo.Service.UserRoleService;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
@ -25,6 +26,9 @@ public class RoleController {
@Autowired
private RoleService roleService;
@Autowired
private UserRoleService userroleService;
//角色增删改查
/**
@ -62,8 +66,14 @@ public class RoleController {
if (role==null){
return Result.error(401, "角色不存在");
}else {
roleService.deleteByRoleName(roleName);
return Result.success("删除成功");
List<UserRole> userRole = userroleService.findByRoleId(role.getId());
if(userRole.size()==0){
roleService.deleteByRoleName(roleName);
return Result.success("删除成功");
}
else {
return Result.error(401, "角色已被使用,暂且删除不了");
}
}
}

44
demo/demo/src/main/java/demo/Controller/UserController.java

@ -2,14 +2,15 @@ package demo.Controller;
import demo.Entity.*;
import demo.Service.RoleService;
import demo.Service.UserRoleService;
import demo.Service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.transaction.Transactional;
import javax.validation.Valid;
import javax.validation.constraints.Pattern;
import java.time.Duration;
@ -18,7 +19,6 @@ import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.List;
import java.util.Set;
@Slf4j
@RestController
@ -29,6 +29,9 @@ public class UserController {
@Autowired
private UserService userService;
@Autowired
private UserRoleService userroleService;
@Autowired
private StringRedisTemplate redisTemplate;
@ -43,13 +46,20 @@ public class UserController {
* @param userVO
* @return
*/
@Transactional(rollbackOn = Exception.class)
@PostMapping("/register")
public Result<String> register(@RequestBody UserVO userVO) {
public Result<String> register(@Valid UserVO userVO, @Valid int roleId) {
// 查询用户名是否被占用
User user = userService.findByUserName(userVO.getLoginName());
if (user==null){
// 没有占用,进行注册
userService.register(userVO.getLoginName(), userVO.getUserChnName(), userVO.getPassword());
User newUser = userService.findByUserName(userVO.getLoginName());
userroleService.insert(newUser.getId(), roleId);
UserRole userRole = userroleService.findByUserId(newUser.getId());
if(userRole==null){
throw new RuntimeException("注册失败");
}
return Result.success("注册成功");
}else {
return Result.error(401, "用户名已被占用");
@ -61,13 +71,21 @@ public class UserController {
* @param loginName
* @return
*/
@Transactional(rollbackOn = Exception.class)
@DeleteMapping("/delete")
public Result<String> delete(@Pattern(regexp = "^\\S{5,16}$") String loginName){
// 查询用户名是否被占用
User user = userService.findByUserName(loginName);
if (user!=null){
// 存在,进行删除
userService.deleteByUserName(loginName);
User newUser = userService.findByUserName(loginName);
userroleService.delete(newUser.getId());
UserRole userRole = userroleService.findByUserId(user.getId());
userroleService.delete(userRole.getId());
User newUser1 = userService.findByUserName(loginName);
if(userRole!=null && newUser1!=null){
throw new RuntimeException("删除失败");
}
return Result.success("删除成功");
}else {
return Result.error(401, "用户名不存在");
@ -79,8 +97,9 @@ public class UserController {
* @param userVo
* @return
*/
@Transactional(rollbackOn = Exception.class)
@PutMapping("/update")
public Result<String> update(@Valid UserVO userVo){
public Result<String> update(@Valid UserVO userVo, @Valid int roleId){
// 查询用户名是否被占用
User user = userService.findByUserName(userVo.getLoginName());
if (user!=null){
@ -92,6 +111,13 @@ public class UserController {
// 将Instant转换为Date
Date date = Date.from(instant);
userService.updateByUserName(userVo.getLoginName(), userVo.getUserChnName(), date, userVo.getPassword());
UserRole userRole = userroleService.findByUserId(user.getId());
if(userRole!=null){
userroleService.update(user.getId(), roleId);
}
else{
throw new RuntimeException("用户角色关联数据不存在,无法更新");
}
return Result.success("更新成功");
}else {
return Result.error(401, "用户名不存在");
@ -149,14 +175,14 @@ public class UserController {
}
@GetMapping("/query")
public Result<List<User>> query(){
public Result<List<UserDTO>> query(){
return Result.success(userService.query());
}
@PostMapping("/queryByUserName")
public Result<User> queryByUserName(@Valid String loginName){
User user = userService.queryByUserName(loginName);
if(user==null){
public Result<UserDTO> queryByUserName(@Valid String loginName){
UserDTO userDTO = userService.queryByUserName(loginName);
if(userDTO==null){
return Result.error(401, "用户不存在");
}
return Result.success(userService.queryByUserName(loginName));

26
demo/demo/src/main/java/demo/Controller/UserRoleController.java

@ -0,0 +1,26 @@
package demo.Controller;
import demo.Entity.*;
import demo.Service.RoleService;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/role")
@Validated
public class UserRoleController {
}

2
demo/demo/src/main/java/demo/DemoApplication.java

@ -2,8 +2,10 @@ package demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication
@EnableTransactionManagement//开启事务支持
//@MapperScan("demo.Mapper") // 指定扫描的包路径
public class DemoApplication {

25
demo/demo/src/main/java/demo/Entity/UserDTO.java

@ -0,0 +1,25 @@
package demo.Entity;
import lombok.Data;
import javax.persistence.*;
@Entity
@Data
public class UserDTO {
@Id
@Column(length = 32, nullable = false)
private int id;
@Column(length = 50)
private String loginName;
@Column(length = 50)
private String userChnName;
@Column(length = 50)
private String roleName;
@Column(length = 50)
private String roleCode;
}

25
demo/demo/src/main/java/demo/Entity/UserRole.java

@ -0,0 +1,25 @@
package demo.Entity;
import lombok.Data;
import javax.persistence.*;
import java.util.Date;
@Entity
@Data
@Table(name = "user_role_relation")
public class UserRole {
@Id
@Column(length = 32, nullable = false)
private int id;
@Column(length = 32)
private int userID;
@Column(length = 32)
private int roleID;
@Temporal(TemporalType.TIMESTAMP)
@Column()
private Date createTime;
}

9
demo/demo/src/main/java/demo/Mapper/UserMapper.java

@ -1,6 +1,7 @@
package demo.Mapper;
import demo.Entity.User;
import demo.Entity.UserDTO;
import org.apache.ibatis.annotations.*;
import java.util.Date;
@ -24,9 +25,9 @@ public interface UserMapper {
@Update("UPDATE user SET USER_CHN_NAME = #{userChnName}, UPDATE_TIME = #{updateTime}, PASSWORD = #{password} WHERE LOGIN_NAME = #{loginName}")
void updateByUserName(@Param("loginName") String loginName, @Param("userChnName") String userChnName, @Param("updateTime") Date updateTime, @Param("password") String password);
@Select("SELECT * FROM user")
List<User> findAll();
@Select("SELECT user.ID, user.LOGIN_NAME, user.USER_CHN_NAME, role.ROLE_NAME, role.ROLE_CODE FROM user, role, user_role_relation WHERE user.ID = user_role_relation.USER_ID and role.ID = user_role_relation.ROLE_ID")
List<UserDTO> findAll();
@Select("SELECT * FROM user WHERE LOGIN_NAME = #{loginName}")
User queryByUserName(@Param("loginName")String loginName);
@Select("SELECT user.ID, user.LOGIN_NAME, user.USER_CHN_NAME, role.ROLE_NAME, role.ROLE_CODE FROM user, role, user_role_relation WHERE user.LOGIN_NAME = #{loginName} and user.ID = user_role_relation.USER_ID and role.ID = user_role_relation.ROLE_ID")
UserDTO queryByUserName(@Param("loginName")String loginName);
}

26
demo/demo/src/main/java/demo/Mapper/UserRoleMapper.java

@ -0,0 +1,26 @@
package demo.Mapper;
import demo.Entity.Role;
import demo.Entity.UserRole;
import org.apache.ibatis.annotations.*;
import java.util.Date;
import java.util.List;
@Mapper
public interface UserRoleMapper {
@Insert("INSERT INTO user_role_relation (USER_ID, ROLE_ID, CREATE_TIME) values (#{userId}, #{roleId}, #{createTime})")
void insert(@Param("userId") int userId, @Param("roleId") int roleId, @Param("createTime") Date createTime);
@Delete("DELETE FROM user_role_relation WHERE USER_ID = #{userId}")
void delete(@Param("userId") int userId);
@Select("SELECT * FROM user_role_relation WHERE ROLE_ID = #{roleId}")
List<UserRole> findByRoleId(@Param("roleId") int roleId);
@Update("UPDATE user_role_relation SET ROLE_ID = #{roleId} WHERE USER_ID = #{userId}")
void update(@Param("userId") int userId, @Param("roleId") int roleId);
@Select("SELECT * FROM user_role_relation WHERE USER_ID = #{userId}")
UserRole findByUserId(@Param("userId") int userId);
}

52
demo/demo/src/main/java/demo/Service/UserRoleService.java

@ -0,0 +1,52 @@
package demo.Service;
import demo.Entity.Role;
import demo.Entity.RoleVO;
import demo.Entity.User;
import demo.Entity.UserRole;
import demo.Mapper.RoleMapper;
import demo.Mapper.UserMapper;
import demo.Mapper.UserRoleMapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.List;
@Slf4j
@Service
public class UserRoleService {
@Autowired
private UserRoleMapper userroleMapper;
public void insert(int userId, int roleId) {
// 创建一个LocalDateTime对象
LocalDateTime localDateTime = LocalDateTime.now();
// 将LocalDateTime转换为Instant
Instant instant = localDateTime.toInstant(ZoneOffset.UTC);
// 将Instant转换为Date
Date date = Date.from(instant);
userroleMapper.insert(userId, roleId, date);
}
public void delete(int userId) {
userroleMapper.delete(userId);
}
public List<UserRole> findByRoleId(int roleId) {
return userroleMapper.findByRoleId(roleId);
}
public void update(int userId, int roleId) {
userroleMapper.update(userId, roleId);
}
public UserRole findByUserId(int userId) {
return userroleMapper.findByUserId(userId);
}
}

7
demo/demo/src/main/java/demo/Service/UserService.java

@ -1,9 +1,8 @@
package demo.Service;
import demo.Entity.Role;
import demo.Entity.User;
import demo.Entity.UserDTO;
import demo.Mapper.UserMapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@ -46,11 +45,11 @@ public class UserService {
userMapper.updateByUserName(loginName, userChnName, updateTime, password);
}
public List<User> query(){
public List<UserDTO> query(){
return userMapper.findAll();
}
public User queryByUserName(String loginName){
public UserDTO queryByUserName(String loginName){
return userMapper.queryByUserName(loginName);
}
}

9
demo/demo/src/test/java/demo/DemoApplicationTests.java

@ -9,15 +9,8 @@ import javax.sql.DataSource;
@SpringBootTest
class DemoApplicationTests {
@Autowired
private DataSource dataSource;
@Autowired
private UserMapper userMapper;
@Test
void contextLoads() throws Exception {
System.out.println(dataSource.getConnection());
void contextLoads(){
}
}

Loading…
Cancel
Save