Saving data of a html table in mysql table - java

In my system user will see a basic timetable view and he can add subjects by using a dropdown in each list.I need to store all the subjects in the timetable in a sql table. when a user selects a subject using a dropdown a new sql row should be created with start,end time,day and subject_code.Can someone please help
Add Time Table view
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org">
<head>
<link rel="stylesheet" type="text/css" href="static/css/timeTableMapping.css" th:href="#{/css/timeTableMapping.css}">
<meta charset="UTF-8">
<title>Time Table</title>
</head>
<body>
</form>
<div class="container2">
<form action="#" th:action="#{/timeTableMapping/save}" th:object="${timeTableMapping}" method="post">
<table border="0" cell[adding="10">
<tr>
<td><h1>Time Table:</h1></td>
<td>
<select th:field="*{time_table_code}">
<option value="">Choose..</option>
<option th:each="timeTable: ${timeTables}" th:value="${timeTable.name}" th:text="${timeTable.name}"/>
</select>
</td>
</tr>
</table>
<table border="1" >
<thead>
<tr>
</tr>
<br>
<th></th>
<th:block th:each="day : ${days}">
<th th:text="${day.name}"></th>
</th:block>
</thead>
<tbody>
<th:block th:each="time : ${times}">
<tr>
<th th:text="${ time.start }+':00 - ' + ${ time.end }+':00'"></th>
<th:block th:each="day : ${days}">
<td>
<select th:field="*{subject_code}">
<option value=""></option>
<option th:each="subject: ${subjects}" th:value="${subject.subject_code}" th:text="${subject.name}"/>
</select>
</td>
</th:block>
</tr>
</th:block>
<tr>
<td colspan="2">
<button type="submit">Save</button>
</td>
</tr>
</tbody>
</table>
</form>
</div>
</body>
</html>
Controller
#Controller
public class TimeTableMappingController {
#Autowired
private TimeTableMappingDAO timeTableMappingDAO;
#Autowired
private TimeTableDAO timeTableDAO;
#Autowired
private SubjectDAO subjectDAO;
#Autowired
private StudentGroupDAO studentGroupDAO;
#Autowired
private DayDAO dayDAO;
#Autowired
private TimeDAO timeDAO;
#RequestMapping("/timeTableMapping")
public String viewHomePage(Model model){
List<TimeTableMapping> timeTableMappingDetails= timeTableMappingDAO.findAll();
model.addAttribute("timeTableMappingDetails",timeTableMappingDetails);
return "timeTableMapping";
}
#RequestMapping("/timeTableMapping/new")
public String addTimeTableMapping(Model model){
TimeTableMapping timeTableMapping =new TimeTableMapping();
model.addAttribute("timeTableMapping",timeTableMapping);
List<TimeTable> timeTableDetail = timeTableDAO.findAll();
model.addAttribute("timeTables", timeTableDetail);
List<Subject> subjectDetail = subjectDAO.findAll();
model.addAttribute("subjects", subjectDetail);
List<Day> dayDetails = dayDAO.findAll();
model.addAttribute("days",dayDetails);
List<Time> timeDetails = timeDAO.findAll();
model.addAttribute("times",timeDetails);
return "addTimeTableMapping";
}
#RequestMapping(value="/timeTableMapping/save",method= RequestMethod.POST)
public String saveTimeTable(#ModelAttribute("timeTableMapping") TimeTableMapping timeTableMapping){
timeTableMappingDAO.save(timeTableMapping);
return "redirect:/timeTableMapping";
}
#RequestMapping(value="/timeTableMapping/saveAll",method= RequestMethod.POST)
public String saveAll(#ModelAttribute("timeTable") TimeTable timeTable){
timeTableDAO.saveAll(timeTable);
return "redirect:/timeTable";
}
#RequestMapping("/timeTableMapping/edit/{id}")
public ModelAndView updateTimeTable(#PathVariable(name="id")Long id){
ModelAndView mav=new ModelAndView(("updateTimeTable"));
TimeTable timeTable = timeTableDAO.findById(id);
mav.addObject("timeTable",timeTable);
List<Subject> subjectDetails = subjectDAO.findAll();
mav.addObject("subjects", subjectDetails);
List<StudentGroup> studentGroupDetails = studentGroupDAO.findAll();
mav.addObject("studentGroups",studentGroupDetails);
List<Day> dayDetails = dayDAO.findAll();
mav.addObject("days",dayDetails);
List<Time> timeDetails = timeDAO.findAll();
mav.addObject("times",timeDetails);
return mav;
}
#RequestMapping("/timeTableMapping/delete/{id}")
public String deleteProduct(#PathVariable(name="id") Long id){
timeTableDAO.delete(id);
return "redirect:/timeTable";
}
}
I tried to do this but it seems what happens is trying to save all the data in the timeTable view in the same SQL record. And because of it, an error message occurs.
Exception:
There was an unexpected error (type=Internal Server Error, status=500).
could not execute batch; SQL [insert into timetablemappings (day, end, start, subject_code, time_table_code, id) values (?, ?, ?, ?, ?, ?)]; nested exception is org.hibernate.exception.DataException: could not execute batch
org.springframework.dao.DataIntegrityViolationException: could not execute batch; SQL [insert into timetablemappings (day, end, start, subject_code, time_table_code, id) values (?, ?, ?, ?, ?, ?)]; nested exception is org.hibernate.exception.DataException: could not execute batch
Caused by: com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Data too long for column 'subject_code' at row 1

Related

How to remove multiple rows via checkbox

I am new to spring and I need to be able to delete the selected rows by checkbox. How can I delete multiple rows from the database? I am using Thymeleaf as view.
Here is my code:
HTML
<div class="col-md-12">
<table class="table" id="tableImport">
<thead>
<tr>
<th scope="col">Remove</th>
<th scope="col">Debt Age Rule</th>
<th scope="col">Reminder</th>
<th scope="col">Frequency</th>
<th scope="col">Reorder</th>
</tr>
</thead>
<tbody>
<tr th:each="configCampaign:${listConfigCampaigns}">
<td>
<input type="checkbox" name="my-checkbox">
</td>
<td th:text="${configCampaign.debtagerule}"></td>
<td th:text="${configCampaign.remindebttype}"></td>
<td th:text="'Every '+${configCampaign.every} + ' ' + ${configCampaign.unit}"></td>
<td></td>
</tr>
</tbody>
</table>
<div class="col-md-12" style="text-align: center">
<input class="btn btn-primary" type="button" value="- Remove Selected Action(s)"/>
</div>
</div>
This table shows me data from an arrayList in memory, nothing with a database, I need to remove those selected objects from the array. At the moment I have my controller like this
Entity
private int configid;
private String debtagerule;
private String remindebttype;
private int every;
private String unit;
private boolean selected;
//getters and setters
In addition to the above, this is the controller with which I am currently working
Controller
#GetMapping("/deleteConfigureCampaign")
public String deleteConfig(#ModelAttribute ConfigCampaign configCampaign, Model model) {
listConfigCampaigns.remove(configCampaign);
return "redirect:/configureCampaign";
}
In Spring Boot, You have to use JpaRepository<> for delete data from database and need to understand structure of Spring Boot project.
Here is sturcture of Spring Boot project:
Entity -> Repository -> Service -> Controller -> View.
Here down is code:
Entity
#Table(name = "config_master")
public class ConfigCampaign {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer configid;
private String debtagerule;
private String remindebttype;
private Integer every;
private String unit;
private boolean selected;
// Constructor, Getter and Setter
}
Repository
Use of #Modifying annotation: It is used to enhance the #Query annotation so that we can execute not only SELECT queries, but also INSERT, UPDATE, DELETE, and even DDL queries
#Repository
public interface ConfigRepo extends JpaRepository<ConfigCampaign, Integer>{
#Modifying
#Transactional
#Query(nativeQuery = true, value = "DELETE FROM config_master WHERE configid IN(?1)")
void delConfig(List<Integer> configId);
}
Service
#Service
public class PojoServiceImpl{
#Autowired
private ConfigRepo configRepo;
#Override
public void delConfig(Integer[] configId) {
configRepo.delConfig(Arrays.asList(configId));
}
}
Controller
// Show table of Config Campaign
#RequestMapping(value = "/showconfig", method = RequestMethod.GET)
public String getConfig(Model mdl)
{
List<ConfigCampaign> getConfig = pojoService.getAllConfig();
mdl.addAttribute("config", getConfig);
return "showConfigCampaign";
}
// Delete item from Config Campaign
#RequestMapping(value = "/delcampaign", method = RequestMethod.GET)
public String deleteConfig(#RequestParam("cid") Integer[] configId)
{
pojoService.delConfig(configId);
return "redirect:/showconfig";
}
showConfigCampaign
You have to add configData.configid in checkbox.
<form th:action="#{/delcampaign}" th:object="${sconfig}">
<div class="container">
<div class="row">
<div class="col-sm-12">
<table class="table" style="text-align: center">
<thead>
<tr>
<th scope="col">Remove</th>
<th scope="col">Debt Age Rule</th>
<th scope="col">Reminder</th>
<th scope="col">Frequency</th>
</tr>
</thead>
<tbody>
<tr th:each="configData: ${config}">
<td><input type="checkbox" name="cid" th:value="${configData.configid}"/></td>
<td th:text="${configData.debtagerule}"></td>
<td th:text="${configData.remindebttype}"></td>
<td th:text="${configData.every}"></td>
</tr>
</tbody>
</table>
<input type="submit" value="Delete Users" />
</div>
</div>
</div>
</form>

Spring MVC new row in database is created while want to update

I write my first form using Spring MVC pattern and Hibernate.
I have a problem when I want to update existing row in table.
After click "Edit" Buttno in a table, correct row is found in db. Then I can update "name" field and click SAVE button. Than in database i created new row with new ID.
I have wrote two System.out to check current values of object.
My Controller class:
#Controller
//#RequestMapping("/")
public class InterventionController {
#Autowired
private InterventionService interventionService;
#GetMapping("/")
public String viewHomePage(Model model){
List<InterventionModel> interventionList = interventionService.listAll();
model.addAttribute("interventionList", interventionList);
return "index";
}
#GetMapping("/new")
public String addInterventionForm(Model model){
InterventionModel interventionModel = new InterventionModel();
model.addAttribute("interventionModel", interventionModel);
System.out.println(model.toString());
return "new_intervention";
}
#RequestMapping(value="/save", method = RequestMethod.POST)
public String saveIntervention(#ModelAttribute("interventionModel")InterventionModel interventionModel){
System.out.println("Object retreived from editing view "+interventionModel); // <- just to check in console object attributes
interventionService.save(interventionModel);
return "redirect:/";
}
#RequestMapping("/edit/{id}")
public ModelAndView showEditInterventionForm(#PathVariable(name="id") Long id){
ModelAndView mav = new ModelAndView("edit_intervention");
InterventionModel interventionModel = interventionService.get(id).get(); // <-- Optional received from service layer
mav.addObject("interventionModel", interventionModel);
System.out.println("Object retrieved from database : "+interventionModel); // <- just to check in console object attributes
return mav;
}
#GetMapping("/delete/{id}")
public String deleteIntervention(#PathVariable(name="id") Long id){
interventionService.delete(id);
return "redirect:/";
}
My InterventionModel class doesn't contain any annotation. I don't know if that is a mistake, but that object is DTO between controller and service layer. In the service layer, it is mapped to the entity which is annotated #Entity.
public class InterventionModel {
private Long id;
private String name;
public InterventionModel() {
}
public InterventionModel(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "InterventionModel{" +
"id=" + id +
", name='" + name + '\'' +
'}';
} }
index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Interventions</title>
</head>
<body>
<div align="center">
<h1>Interventions</h1>
Create new Intervention
<br><br>
<table border="2" cellpadding="10">
<thead>
<tr>
<th>Intervention Id</th>
<th>Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr th:each="intervention :${interventionList}">
<td th:text="${intervention.id}">Intervention Id</td>
<td th:text="${intervention.name}">Name</td>
<td>
<a th:href="#{'/edit/' + ${intervention.id}}">Edit</a>
<a th:href="#{'/delete/' + ${intervention.id}}">Delete</a>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
and edit_intervention.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Edit Intervention</title>
</head>
<body>
<div align="center">
<h1>Edit Intervention</h1>
<br/>
<form action="#" th:action="#{/save}" th:object="${interventionModel}" method="post">
<table border="0" cellpadding="10">
<tr>
<td>Intervention ID</td>
<!-- <td><input type="text" th:field="*{id}" readonly="readonly"/></td>-->
<td><input type="text" th:field="*{id}" readonly="readonly"/></td>
</tr>
<tr>
<td>Intervention name</td>
<td><input type="text" th:field="*{name}"/></td>
</tr>
<tr>
<td colspan="2"><button type="submit">Save</button> </td>
</tr>
</table>
</form>
</div>
</body>
</html>
What is curious for me. Object when is retrieved from DB has proper attributes (id, name) than Model is created and sent to edit_intervention.html form. After changing name, it goes back to save method but there ID number is "null", instead of name which contains changed new value.
For me (as a beginner) it looks like no all attributes are transferred from the view to the save method in controller. When we have ID set to "null" it's a sign for hibernate to create new row.
I guess there is a minor failure which I cannot find.
Logs from terminal when I call update form:
and view how table after modification looks like:
Thank you in advance for help.
As you see your id field is null. Because probably the Long value wasn't set.
In entity class you should mark id property as #Id, also you can always add the #GeneratedValue annotation above.

How to save selected for loop data in mysql database?

I'm new to spring boot and struck in a prob for some time now. In my thymeleaf page i have used a for loops and i need to save currently iterating item in the database.(ex:im using days of the week in a for loop and a user can select a subject for each item in my for loo, then 5 sql rows should be saved with day and subject) but currently it doesn't save the date and save 2 selected subjects in 1 sql row
Add time Table thymeleaf view
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org">
<head>
<link rel="stylesheet" type="text/css" href="static/css/timeTableMapping.css" th:href="#{/css/timeTableMapping.css}">
<meta charset="UTF-8">
<title>Time Table</title>
</head>
<body>
</form>
<div class="container2">
<form action="#" th:action="#{/timeTableMapping/save}" th:object="${timeTableMapping}" method="post">
<table border="0" cell[adding="10">
<tr>
<td><h1>Time Table:</h1></td>
<td>
<select th:field="*{time_table_code}">
<option value="">Choose..</option>
<option th:each="timeTable: ${timeTables}" th:value="${timeTable.name}" th:text="${timeTable.name}"/>
</select>
</td>
</tr>
</table>
<table border="1" >
<thead>
<tr>
</tr>
<br>
<th:block th:each="day : ${days}">
<th th:value="${day.name}" th:text="${day.name}"></th>
</th:block>
</thead>
<tbody>
<th:block th:each="day : ${days}">
<td>
<select th:field="*{subject_code}">
<option value=""></option>
<option th:each="subject: ${subjects}" th:value="${subject.subject_code}" th:text="${subject.name}"/>
</select>
</td>
</th:block>
<tr>
<td colspan="2">
<button type="submit">Save</button>
</td>
</tr>
</tbody>
</table>
</form>
</div>
</body>
</html>
Time Table Mapping Controller
#Controller
public class TimeTableMappingController {
#Autowired
private TimeTableMappingDAO timeTableMappingDAO;
#Autowired
private TimeTableDAO timeTableDAO;
#Autowired
private SubjectDAO subjectDAO;
#Autowired
private StudentGroupDAO studentGroupDAO;
#Autowired
private DayDAO dayDAO;
#RequestMapping("/timeTableMapping")
public String viewHomePage(Model model){
List<TimeTableMapping> timeTableMappingDetails= timeTableMappingDAO.findAll();
model.addAttribute("timeTableMappingDetails",timeTableMappingDetails);
return "timeTableMapping";
}
#RequestMapping("/timeTableMapping/new")
public String addTimeTableMapping(Model model){
System.out.println("hey");
System.out.println("hey");
TimeTableMapping timeTableMapping =new TimeTableMapping();
model.addAttribute("timeTableMapping",timeTableMapping);
List<TimeTable> timeTableDetail = timeTableDAO.findAll();
model.addAttribute("timeTables", timeTableDetail);
List<Subject> subjectDetail = subjectDAO.findAll();
model.addAttribute("subjects", subjectDetail);
List<Day> dayDetails = dayDAO.findAll();
model.addAttribute("days",dayDetails);
List<Time> timeDetails = timeDAO.findAll();
model.addAttribute("times",timeDetails);
return "addTimeTableMapping";
}
#RequestMapping(value="/timeTableMapping/save",method= RequestMethod.POST)
public String saveTimeTable(#ModelAttribute("timeTableMapping") TimeTableMapping timeTableMapping){
timeTableMappingDAO.save(timeTableMapping);
return "redirect:/timeTableMapping";
}
/*
#RequestMapping(value="/timeTableMapping/saveAll",method= RequestMethod.POST)
public String saveAll(#ModelAttribute("timeTableMapping") TimeTableMapping timeTableMapping){
timeTableDAO.saveAll(timeTableMapping);
return "redirect:/timeTableMapping";
}*/
#RequestMapping("/timeTableMapping/edit/{id}")
public ModelAndView updateTimeTable(#PathVariable(name="id")Long id){
ModelAndView mav=new ModelAndView(("updateTimeTable"));
TimeTable timeTable = timeTableDAO.findById(id);
mav.addObject("timeTable",timeTable);
List<Subject> subjectDetails = subjectDAO.findAll();
mav.addObject("subjects", subjectDetails);
List<StudentGroup> studentGroupDetails = studentGroupDAO.findAll();
mav.addObject("studentGroups",studentGroupDetails);
List<Day> dayDetails = dayDAO.findAll();
mav.addObject("days",dayDetails);
List<Time> timeDetails = timeDAO.findAll();
mav.addObject("times",timeDetails);
return mav;
}
#RequestMapping("/timeTableMapping/delete/{id}")
public String deleteProduct(#PathVariable(name="id") Long id){
timeTableDAO.delete(id);
return "redirect:/timeTable";
}
}
Add Time Table DAO
#Service
public class TimeTableMappingDAO {
#Autowired
TimeTableRepository timeTableRepository;
#Autowired
TimeTableMappingRepository timeTableMappingRepository;
//to save a time table
public TimeTableMapping save(TimeTableMapping timeTableMapping){
return timeTableMappingRepository.save(timeTableMapping);
}
//#Override
public void saveAll(List<TimeTableMapping> timeTableMapping) {
List<TimeTableMapping> timetable=new ArrayList<>();
timeTableMappingRepository.saveAll(timetable).forEach(timeTableMapping::add); // TimeTable repository
}
/*
public TimeTableMapping saveAll(TimeTableMapping timeTableMapping){
return timeTableMappingRepository.saveAll(timeTableMapping);
}
*/
//to search all
public List<TimeTableMapping> findAll(){
return timeTableMappingRepository.findAll();
}
//get by id
public TimeTableMapping findById(Long id){
return timeTableMappingRepository.findById(id).orElse(null);
}
//delete
public void delete(Long id){
timeTableMappingRepository.deleteById(id);
}
}
Time Table Mapping Repository
#Repository
public interface TimeTableMappingRepository extends JpaRepository<TimeTableMapping, Long> {
}
Before auto wiring TimeTableMappingRepository in your DAO, you should add #Repository on interface TimeTableMappingRepository.
Just like this
#Repository
public interface TimeTableMappingRepository extends JpaRepository {}
By Adding #Repository on the interface, spring-data-jpa will create a proxy object of this interface on runtime and you will be able to autowired it.
You are getting more than one data. So you should use List<TimeTableMapping> timeTableMapping
In your service Implementation, you can pass the list that you got adn save all
#Override
public void saveAll(List<TimeTableMapping> timeTableMapping) {
List<TimeTableMapping> timetable=new ArrayList<>();
repository.saveAll(timetable).forEach(timeTableMapping::add); // TimeTable repository
}

populating thymeleaf dropdown with data of another table

i'm new to spring-boot. In my system there are two models named subject,course(two databases with the same names and connected by the foreign key course_id).I need to make it possible to select course name in a dropdown list in the addSubject thymeleaf form. Can someone please tell me how to do this
Subject.DAO file
#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 file
#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);
}
}
Subject Controller
#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";
}
}
Subject html file
<!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>
So you want to load Course combo inside subject html
You need to modify subject controller
#RequestMapping("/subject")
public String viewHomePage(Model model){
List<Subject> subjectDetails= subjectDAO.findAll();
List<Course> courseDetail= courseDAO.findAll();
model.addAttribute("subjectDetails",subjectDetails);
model.addAttribute("courses",courseDetail);
return "subject";
}
In HTML
<tr>
<td>Course:</td>
<td>
<select th:field="*{course_code}">
<option value="">Choose..</option>
<option th:each="course: ${courses}" th:value="${course.id}" th:text="${course.name}" />
</select>
</td>
</tr>
<tr>
Edit 1:
I think you are loading addSubject.html
In that case you need to modify addSubject controller
#RequestMapping("/subject/new")
public String addSubject(Model model){
Subject subject =new Subject();
model.addAttribute("subject",subject);
List<Course> courseDetail= courseDAO.findAll();
model.addAttribute("courses",courseDetail);
return "addSubject";
}
Edit 2:
As per your code in Git I can see
#Autowired
private SubjectDAO subjectDAO;
private CourseDAO courseDAO;
It should be
#Autowired
private SubjectDAO subjectDAO;
#Autowired
private CourseDAO courseDAO;
First add all courses to the ModelMap
model.addAttribute("cources",courseDao.findAll());
Then use th:each attribute to populate select options
<select th:field="*{course}">
<option value="">Choose..</option>
<option th:each="c: ${cources}" th:value="${c.id}" th:text="${c.name}" />
</select>

How to insert the multiple value from select form into database?

My submission form:
<form method="post" action="${pageContext.request.contextPath }/">
<div>
<label>User:</label>
<select name="customer">
<option value="">Select Customer</option>
<c:forEach var="c" items="${ cList }">
<option value="${ c.id }">${ c.name }</option>
</c:forEach>
</select>
</div><br>
<div>
<label>Hobby:</label>
<select name="product" multiple size="8">
<!-- <option value="">Select Items</option> -->
<c:forEach var="p" items="${ pList }">
<option value = "${ p.id }">${ p.productName }</option>
</c:forEach>
</select>
</div>
<br><br>
<input type="submit" value="Send">
</form>
My Controller:
#RequestMapping(value = "/", method = RequestMethod.POST)
public String postHome(Model model, HttpServletRequest request, #ModelAttribute Transcation t){
transactionDao.addTransaction(t);
return "home";
}
In TransactionDaoImpl:
#Override
#Transactional
public void addTranscation(Transcation t) {
session = sessionFactory.openSession();
session.save(t);
session.close();
}
Based on your idea, what type of modifications do i have to make to perform insert operation.

Categories