帮我写一个级联和联动的java后端代码以及前端页面
时间: 2024-09-23 15:01:49 浏览: 44
由于篇幅限制,我将给出一个简单的Java Spring Boot后端和HTML前端的例子,用于演示级联和联动的基本概念。请注意,这是一个简化版的示例,实际项目中可能需要更多的错误处理和详细配置。
### 后端(Spring Boot + JPA)
```java
// 假设我们有两张关联的实体:Department和Employee
@Entity
public class Department {
@Id
private Long id;
private String name;
// 省略getter/setter和List<Employee> employees属性
@OneToMany(mappedBy = "department")
public List<Employee> getEmployees() {
return employees;
}
}
@Entity
public class Employee {
@Id
private Long id;
private String name;
@ManyToOne
private Department department; // 这就是级联的体现
// 省略getter/setter
}
```
### 配置级联删除
在`application.properties`或`application.yml`中添加Spring Data JPA的相关配置:
```properties
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.enforce_single_table_per_query=true
```
然后在Repository中启用级联:
```java
public interface DepartmentRepository extends JpaRepository<Department, Long> {
default void deleteWithEmployees(Department department) {
department.getEmployees().forEach(employee -> employee.setDepartment(null));
super.delete(department);
}
}
```
### 前端(HTML + JavaScript - jQuery为例)
```html
<!-- 部门选择框 -->
<select id="parentDepartment" data-toggle="select2" style="width: 100%">
<option value="">请选择</option>
<!-- 由后端填充选项 -->
</select>
<!-- 员工选择框,初始为空 -->
<select id="childEmployee" style="width: 100%; display:none;">
<!-- 由后端填充选项 -->
</select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0/dist/js/select2.full.min.js"></script>
<script>
$(document).ready(function() {
// 初始化联动
$('#parentDepartment').on('change', function() {
var parentId = $(this).val();
if (parentId) {
$.get('/api/departments/' + parentId + '/employees', function(data) {
$('#childEmployee').html('').append('<option value="">-- 请选择 --</option>');
data.forEach(employee => $('#childEmployee').append(`<option value="${employee.id}">${employee.name}</option>`));
});
} else {
$('#childEmployee').html('');
}
});
});
</script>
```
这个例子展示了基本的级联(通过外键关联)和联动查询。在实际项目中,你需要连接到数据库、使用Ajax获取数据,并可能需要引入更复杂的前端库或框架来优化用户体验。
阅读全文