Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何确保帐户是唯一的_Mysql_Spring_Spring Boot - Fatal编程技术网

Mysql 如何确保帐户是唯一的

Mysql 如何确保帐户是唯一的,mysql,spring,spring-boot,Mysql,Spring,Spring Boot,我正在用spring boot、mysql和mybatis开发一个帐户系统 我在表字段上使用了一个唯一的索引,当新请求出现时,我使用try-catch来处理它 我觉得不好 @RestController 公共类用户控制器{ @自动连线 私人用户服务; @RequestMappingquery/{id} 公共字符串query@PathVariable整数id{ 返回userService.queryid.toString; } @请求映射插入 公共字符串addUser{ 用户=新用户; user.

我正在用spring boot、mysql和mybatis开发一个帐户系统

我在表字段上使用了一个唯一的索引,当新请求出现时,我使用try-catch来处理它

我觉得不好

@RestController 公共类用户控制器{ @自动连线 私人用户服务; @RequestMappingquery/{id} 公共字符串query@PathVariable整数id{ 返回userService.queryid.toString; } @请求映射插入 公共字符串addUser{ 用户=新用户; user.setAccountaaa; user.setPasswordpassword; 试一试{ userService.insertuser; }捕获异常e{ 如果e.getLocalizedMessage.containsDuplicate条目{ //重复条目索引 user.setId-1; }否则{ //其他例外 user.setId-2; } } 返回user.toString; } } 创建表“用户” `id`int11非空自动增量, `帐户'varchar255非空默认值, `密码'varchar255非空默认值, 主键'id`, 唯一密钥“iacc”帐户` ENGINE=InnoDB自动增量=35默认字符集=utf8
考虑到您使用的是SpringBoot,myBatis建议您可以在注册用户之前对存储库进行额外调用,以检查用户是否存在

@Select("select * from user where account= #{accountVar}")
User findById(@Param("accountVar") String accountName);
若你们有一个和accountName相同的用户,你们应该抛出自定义异常和/或响应消息,说明用户已经存在或类似的东西

记住要遵守Spring Boot或基于HTTP的标准,以便从端点进行响应

如果成功,您应返回200 OK以及消息或 什么最适合你 如果出现故障/异常,您可以 应随消息一起返回400个错误请求
先查询后插入不是原子的,因为Servlet是多线程的。如果还有一个并发请求,在哪里使用Servlet?你能说得更具体一点吗?Tomcat是嵌入在spring-boot中的。下面是堆栈com.example.controller.UserController.java addUser。。。org.springframework.web.servlet.FrameworkServlet FrameworkServlet.java doGet javax.servlet.http.HttpServlet-HttpServlet.java服务org.springframework.web.servlet.FrameworkServlet-FrameworkServlet.java服务javax.servlet.http.HttpServlet-HttpServlet.java服务我认为您完全不了解servlet和spring靴子当您使用SpringBoot时,您将不得不使用@Restcontroller而不是servlet…您可以发布有问题的Usercontroller代码吗?