springboot对数据库排序前后端示例代码
时间: 2023-10-14 20:16:15 浏览: 65
Springboot 示例代码
以下是一个使用Spring Boot开发的排序示例,包含前后端代码。
后端代码:
1. 实体类:
```java
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "age")
private Integer age;
// 省略getter和setter方法
}
```
2. Repository:
```java
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
```
3. Service:
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
public List<User> getAllUsers(String sortColumn, String sortDirection) {
Sort sort = Sort.by(Sort.Direction.fromString(sortDirection), sortColumn);
return userRepository.findAll(sort);
}
}
```
4. Controller:
```java
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public ResponseEntity<List<User>> getAllUsers(@RequestParam String sortColumn, @RequestParam String sortDirection) {
List<User> users = userService.getAllUsers(sortColumn, sortDirection);
return ResponseEntity.ok(users);
}
}
```
前端代码:
1. HTML:
```html
<table>
<thead>
<tr>
<th><a href="#" onclick="sortUsers('id')">ID</a></th>
<th><a href="#" onclick="sortUsers('name')">Name</a></th>
<th><a href="#" onclick="sortUsers('age')">Age</a></th>
</tr>
</thead>
<tbody id="usersTableBody">
</tbody>
</table>
```
2. JavaScript:
```javascript
function sortUsers(sortColumn) {
const sortDirection = getSortDirection(sortColumn);
const url = `/users?sortColumn=${sortColumn}&sortDirection=${sortDirection}`;
fetch(url)
.then(response => response.json())
.then(users => {
const usersTableBody = document.getElementById('usersTableBody');
usersTableBody.innerHTML = '';
users.forEach(user => {
const row = document.createElement('tr');
row.innerHTML = `<td>${user.id}</td><td>${user.name}</td><td>${user.age}</td>`;
usersTableBody.appendChild(row);
});
});
}
function getSortDirection(sortColumn) {
const currentSortColumn = document.querySelector(`th a[href='#'][onclick*='${sortColumn}']`);
if (currentSortColumn.classList.contains('asc')) {
currentSortColumn.classList.remove('asc');
currentSortColumn.classList.add('desc');
return 'desc';
} else {
currentSortColumn.classList.remove('desc');
currentSortColumn.classList.add('asc');
return 'asc';
}
}
```
说明:
1. 后端接收前端传来的sortColumn和sortDirection参数,通过JPA的findAll方法实现排序查询。
2. 前端通过JavaScript动态生成HTML表格,并使用fetch方法异步请求后端接口查询数据。通过点击表头的链接实现排序。
阅读全文