springboot 实现增删改查,分页查询的mapper层,service层,serviceIpml层,controller层以及前端js的代码
时间: 2024-01-11 21:53:53 浏览: 67
以下是一个简单的示例:
Mapper层代码:
```java
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user")
List<User> findAll();
@Select("SELECT * FROM user WHERE id = #{id}")
User findById(@Param("id") Long id);
@Insert("INSERT INTO user(username, password) VALUES(#{username}, #{password})")
void save(User user);
@Update("UPDATE user SET username=#{username}, password=#{password} WHERE id=#{id}")
void update(User user);
@Delete("DELETE FROM user WHERE id=#{id}")
void deleteById(@Param("id") Long id);
@Select("SELECT COUNT(*) FROM user")
int count();
}
```
Service层代码:
```java
public interface UserService {
List<User> findAll();
User findById(Long id);
void save(User user);
void update(User user);
void deleteById(Long id);
int count();
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> findAll() {
return userMapper.findAll();
}
@Override
public User findById(Long id) {
return userMapper.findById(id);
}
@Override
public void save(User user) {
userMapper.save(user);
}
@Override
public void update(User user) {
userMapper.update(user);
}
@Override
public void deleteById(Long id) {
userMapper.deleteById(id);
}
@Override
public int count() {
return userMapper.count();
}
}
```
Controller层代码:
```java
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users")
public List<User> findAll() {
return userService.findAll();
}
@GetMapping("/users/{id}")
public User findById(@PathVariable Long id) {
return userService.findById(id);
}
@PostMapping("/users")
public void save(@RequestBody User user) {
userService.save(user);
}
@PutMapping("/users")
public void update(@RequestBody User user) {
userService.update(user);
}
@DeleteMapping("/users/{id}")
public void deleteById(@PathVariable Long id) {
userService.deleteById(id);
}
@GetMapping("/users/count")
public int count() {
return userService.count();
}
}
```
前端js代码:
```javascript
$(function() {
// 获取用户列表
$.get("/users", function(data) {
// 处理数据
});
// 获取指定用户
$.get("/users/1", function(data) {
// 处理数据
});
// 新增用户
$.ajax({
url: "/users",
type: "POST",
contentType: "application/json",
data: JSON.stringify({username: "test", password: "123456"}),
success: function() {
// 处理成功
}
});
// 修改用户
$.ajax({
url: "/users",
type: "PUT",
contentType: "application/json",
data: JSON.stringify({id: 1, username: "test", password: "abcdef"}),
success: function() {
// 处理成功
}
});
// 删除用户
$.ajax({
url: "/users/1",
type: "DELETE",
success: function() {
// 处理成功
}
});
// 获取用户数量
$.get("/users/count", function(data) {
// 处理数据
});
});
```
以上代码仅供参考,实际应用中需要根据具体情况进行调整。
阅读全文