使用java代码实现简单的ID自增demo
时间: 2023-10-02 21:08:28 浏览: 108
可以使用Java中的AtomicInteger类实现简单的ID自增。
以下是一个示例代码:
```java
import java.util.concurrent.atomic.AtomicInteger;
public class IdGenerator {
private static final AtomicInteger counter = new AtomicInteger(0);
public static int getNextId() {
return counter.incrementAndGet();
}
}
```
在这个示例中,我们使用了AtomicInteger类来维护一个计数器。getNextId()方法将计数器的值自增,并返回此时的值作为新的ID。由于AtomicInteger类是线程安全的,因此不需要使用synchronized关键字来保证并发安全。
可以在需要生成新ID时调用getNextId()方法即可。
相关问题
springboot+ajax+layui+mysql实现注册(id自增,姓名,密码,部门,入职时间,性别,年龄)
1. 创建数据库表
在MySQL中创建一个名为user的表,表结构如下:
```sql
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL,
`department` varchar(20) DEFAULT NULL,
`hire_date` date DEFAULT NULL,
`gender` varchar(10) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
```
2. 创建SpringBoot项目
创建一个SpringBoot项目,并在pom.xml文件中添加以下依赖:
```xml
<!-- SpringBoot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
```
3. 配置数据库连接
在application.properties文件中配置数据库连接信息:
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/demo?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
```
4. 创建实体类
创建一个名为User的实体类,并使用Lombok注解简化代码:
```java
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String name;
private String password;
private String department;
private Date hireDate;
private String gender;
private Integer age;
}
```
5. 创建Mapper接口
创建一个名为UserMapper的Mapper接口,并在其中定义增加用户的方法:
```java
@Mapper
public interface UserMapper {
@Insert("INSERT INTO user(name, password, department, hire_date, gender, age) VALUES(#{name}, #{password}, #{department}, #{hireDate}, #{gender}, #{age})")
void addUser(User user);
}
```
6. 创建Controller
创建一个名为UserController的Controller,并在其中定义增加用户的方法:
```java
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserMapper userMapper;
@PostMapping("/addUser")
public String addUser(@RequestBody User user) {
userMapper.addUser(user);
return "success";
}
}
```
7. 创建前端页面
使用Layui框架创建一个名为register.html的前端页面,并在其中添加以下代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户注册</title>
<link rel="stylesheet" href="layui/css/layui.css">
<script src="layui/layui.js"></script>
</head>
<body>
<div class="layui-container">
<form class="layui-form" action="">
<div class="layui-form-item">
<label class="layui-form-label">姓名</label>
<div class="layui-input-block">
<input type="text" name="name" required lay-verify="required" placeholder="请输入姓名" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">密码</label>
<div class="layui-input-block">
<input type="password" name="password" required lay-verify="required" placeholder="请输入密码" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">部门</label>
<div class="layui-input-block">
<input type="text" name="department" required lay-verify="required" placeholder="请输入部门" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">入职时间</label>
<div class="layui-input-block">
<input type="text" name="hireDate" required lay-verify="required" placeholder="请选择入职时间" autocomplete="off" class="layui-input" id="hireDate">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">性别</label>
<div class="layui-input-block">
<input type="radio" name="gender" value="男" title="男" checked>
<input type="radio" name="gender" value="女" title="女">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">年龄</label>
<div class="layui-input-block">
<input type="number" name="age" required lay-verify="required" placeholder="请输入年龄" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button>
<button type="reset" class="layui-btn layui-btn-primary">重置</button>
</div>
</div>
</form>
</div>
<script>
//Demo
layui.use('laydate', function(){
var laydate = layui.laydate;
//执行一个laydate实例
laydate.render({
elem: '#hireDate' //指定元素
});
});
layui.use('form', function(){
var form = layui.form;
//监听提交
form.on('submit(formDemo)', function(data){
console.log(data.field);
$.ajax({
url: "/user/addUser",
type: "POST",
contentType: "application/json;charset=utf-8",
data: JSON.stringify(data.field),
success: function(res) {
if (res === "success") {
alert("注册成功!");
} else {
alert("注册失败!");
}
}
});
return false;
});
});
</script>
</body>
</html>
```
8. 运行项目
在浏览器中输入http://localhost:8080/register.html,即可进入用户注册页面。在页面中填写用户信息并点击“立即提交”按钮,即可完成用户注册。注册成功后会弹出提示框。可以在MySQL中查看是否添加了新的用户。
springboot+mybatis-plus+Ajax+layui+mysql实现员工注册(id自增,姓名,年龄,性别,部门,入职时间,密码)
首先,我们需要创建一个员工实体类,包含上述属性。假设这个实体类的名字为Employee。
```
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String sex;
private String department;
private Date hireDate;
private String password;
}
```
在pom.xml文件中加入以下依赖:
```xml
<!-- springboot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>latest-version</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
<!-- layui -->
<dependency>
<groupId>com.clay</groupId>
<artifactId>layui-spring-boot-starter</artifactId>
<version>latest-version</version>
</dependency>
```
配置Mybatis-plus的分页插件、数据源和Mapper扫描路径。在application.yml文件中加入以下配置:
```yml
mybatis-plus:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.example.demo.entity.*
global-config:
db-config:
id-type: auto
table-prefix: emp_
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
map-undeserialized-object: true
use-generated-keys: true
default-fetch-size: 1000
default-statement-timeout: 30000
use-column-label: true
call-setters-on-nulls: true
plugins:
- com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor
spring:
datasource:
url: jdbc:mysql://localhost:3306/demo?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
maximum-pool-size: 5
minimum-idle: 5
auto-commit: true
idle-timeout: 180000
mybatis:
mapper-locations: classpath:mapper/**/*.xml
type-aliases-package: com.example.demo.entity.*
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
```
创建Mapper接口,用于对Employee的增删改查操作。
```java
@Mapper
public interface EmployeeMapper extends BaseMapper<Employee> {
}
```
创建Controller类,包含员工注册的接口方法。
```java
@RestController
@RequestMapping("/employee")
public class EmployeeController {
@Autowired
private EmployeeMapper employeeMapper;
@PostMapping("/register")
public Object register(@RequestBody Employee employee) {
employeeMapper.insert(employee);
return Result.success();
}
}
```
在前端页面中,使用Layui框架实现员工注册的表单页面。在JavaScript代码中使用Ajax提交表单数据。
```html
<div class="layui-form-item">
<label class="layui-form-label">姓名</label>
<div class="layui-input-inline">
<input type="text" name="name" id="name" required
lay-verify="required" autocomplete="off"
class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">年龄</label>
<div class="layui-input-inline">
<input type="number" name="age" id="age" required
lay-verify="required|number" autocomplete="off"
class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">性别</label>
<div class="layui-input-inline">
<select name="sex" id="sex" required lay-verify="required">
<option value="">请选择</option>
<option value="male">男</option>
<option value="female">女</option>
</select>
</div>
</div>
<!-- 其他表单项略 -->
<button class="layui-btn" onclick="register()">注册</button>
<script>
function register() {
$.ajax({
type: "POST",
url: "/employee/register",
data: $("#form").serialize(),
dataType: "json",
success: function (data) {
if (data.code === 0) {
layer.msg("注册成功!");
} else {
layer.msg("注册失败!");
}
},
error: function () {
layer.msg("请求失败!");
}
});
}
</script>
```
阅读全文