【发布时间】:2020-01-11 21:26:13
【问题描述】:
我是 spring-boot 的新手。在我的系统中,有两个模型名为 subject,course(两个具有相同名称并通过外键 course_id 连接的数据库)。我需要在 addSubject thymeleaf 表单的下拉列表中选择课程名称。有人可以告诉我如何做到这一点
Subject.DAO 文件
@Service
public class SubjectDAO {
@Autowired
SubjectRepository subjectRepository;
//to save a subject
public Subject save(Subject subject){
return subjectRepository.save(subject);
}
//to search all subjects
public List<Subject> findAll(){
return subjectRepository.findAll();
}
//get a subject by id
public Subject findById(Long id){
return subjectRepository.findById(id).orElse(null);
}
//delete a subject
public void delete(Long id){
subjectRepository.deleteById(id);
}
}
Course.DAO 文件
@Service
public class CourseDAO {
@Autowired
CourseRepository courseRepository;
//to save a course
public Course save(Course course){
return courseRepository.save(course);
}
//to search all courses
public List<Course> findAll(){
return courseRepository.findAll();
}
//get a course by id
public Course findById(Long id){
return courseRepository.findById(id).orElse(null);
}
//delete a course
public void delete(Long id){
courseRepository.deleteById(id);
}
}
主题控制者
@Controller
public class SubjectController {
@Autowired
private SubjectDAO subjectDAO;
@RequestMapping("/subject")
public String viewHomePage(Model model){
List<Subject> subjectDetails= subjectDAO.findAll();
model.addAttribute("subjectDetails",subjectDetails);
return "subject";
}
@RequestMapping("/subject/new")
public String addSubject(Model model){
Subject subject =new Subject();
model.addAttribute("subject",subject);
return "addSubject";
}
@RequestMapping(value="/subject/save",method= RequestMethod.POST)
public String saveCourse(@ModelAttribute("subject") Subject subject){
subjectDAO.save(subject);
return "redirect:/subject";
}
@RequestMapping("/subject/edit/{id}")
public ModelAndView updateSubjcet(@PathVariable(name="id")Long id){
ModelAndView mav=new ModelAndView(("updateSubject"));
Subject subject=subjectDAO.findById(id);
mav.addObject("subject",subject);
return mav;
}
@RequestMapping("/subject/delete/{id}")
public String deleteProduct(@PathVariable(name="id") Long id){
subjectDAO.delete(id);
return "redirect:/subject";
}
}
主题html文件
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Adding a Subject</title>
</head>
<body>
<div align="center">
<h1>Add a new Subject</h1>
<br/>
<form action="#" th:action="@{/subject/save}" th:object="${subject}" method="post">
<table border="0" cell[adding="10">
<tr>
<td>Subject code:</td>
<td><input type="text" th:field="*{course_code}" /></td>
</tr>
<tr>
<td>Subject Name:</td>
<td><input type="text" th:field="*{name}" /></td>
</tr>
<tr>
<td>Course:</td>
<td>
<select>
<option value=""></option>
</select>
Z
</td>
</tr>
<tr>
<td colspan="2"><button type="submit">Save</button></td>
</tr>
</table>
</form>
</div>
</body>
</html>
【问题讨论】:
-
github.com/Ayesh17/attendance 这是项目的 github 仓库
标签: java hibernate spring-boot thymeleaf