Implementing one to one relation ship spring hibernate - java

I have a table cards which is related to some other master tables (divisions and units) with one to one relation.
On UI I am showing drop downs to select the division and unit values for card, this is the function to create form in CardController.java
#RequestMapping(value = "/addCardForm", method = RequestMethod.GET)
public String addCardForm(ModelMap map)
{
map.addAttribute("divisions", divisionService.getAllDivisions());
map.addAttribute("units", unitService.getAllUnits());
return "admin/addCard";
}
addCard.jsp :
<form:form method="post" action="addCard">
<table cellspacing="10" id="card-table">
<tr>
<td><label for="division" class="control-label">Division : </label></td>
<td><select name="division" class="selectpicker">
<option>Select</option>
<c:forEach items="${divisions}" var="division">
<option value="${division.id}">${division.name}</option>
</c:forEach>
</select></td>
</tr>
<tr>
<td><label for="unit" class="control-label">Unit : </label></td>
<td><select name="unit" class="selectpicker">
<option>Select</option>
<c:forEach items="${units}" var="unit">
<option value="${unit.id}">${unit.name}</option>
</c:forEach>
</select></td>
</tr>
<tr>
<td><button type="submit" class="btn btn-primary">Submit</button></td>
<td></td>
</tr>
</table>
</form>
Drop downs are populated with the data but on submitting form its not setting division or unit to the cardEntity object they are set to null, this is the addCard function in controller :
#RequestMapping(value = "/addCard", method = RequestMethod.POST)
public String addCard(#ModelAttribute(value="card") CardEntity card, BindingResult result)
{
cardService.addCard(card);
//card.getDivision(); -- this is null
return "redirect:/card";
}
There are other fields which are added in the card except drop downs.
CardEntity.java
#Entity
#Table(name="cards")
#Proxy(lazy=false)
public class CardEntity {
#Id
#Column(name="id")
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#OneToOne
#JoinColumn(name="division_id", referencedColumnName="id")
private DivisionEntity division;
#OneToOne
#JoinColumn(name="unit_of_qty_id", referencedColumnName="id")
private UnitEntity units;
public DivisionEntity getDivision() {
return division;
}
public void setDivision(DivisionEntity division) {
this.division = division;
}
public UnitEntity getUnits() {
return units;
}
public void setUnits(UnitEntity units) {
this.units = units;
}
}
Edit :
I have to set divisionEntity and unitEntity manually :
#RequestMapping(value = "/addCard", method = RequestMethod.POST)
public String addCard(HttpServletRequest request, #ModelAttribute(value="card") CardEntity card, BindingResult result)
{
card.setDivision(divisionService.findOne(Integer.parseInt(request.getParameter("division"))));
card.setUnit(unitService.findOne(Integer.parseInt(request.getParameter("unit"))));
cardService.addCard(card);
return "redirect:/card";
}
So I guess the problem is divisionEntity and unitEntity objects are not set in card after submitting the form.

You can do this too:
<tr>
<td><label for="division.id" class="control-label">Division : </label></td>
<td><select name="division.id" class="selectpicker">
<option>Select</option>
<c:forEach items="${divisions}" var="division">
<option value="${division.id}">${division.name}</option>
</c:forEach>
</select></td>
</tr>
<tr>
<td><label for="unit.id" class="control-label">Unit : </label></td>
<td><select name="unit.id" class="selectpicker">
<option>Select</option>
<c:forEach items="${units}" var="unit">
<option value="${unit.id}">${unit.name}</option>
</c:forEach>
</select></td>
</tr>
The rest is same as your original. But:
Make sure you have a default constrcutor in Division class;
The CardEntity should have getUnit() and setUnit(), not getUnits() and setUnits().
Hope it help.

Related

how to populate a response from java spring boot with thymleaf

I am trying to return the data as a response body in java spring boot when a button is click in an html page.I have a list of countries displayed in my page with an edit button assigned to each. I want to find the data that was clicked by id so I have defined the method in my controller class. That's when the edit button is click, it should take the id of the country in the clicked row and display the information based on that id. When I test the api in Postman, it returns the data correctly but when I called the same api in my html page, it's giving me this error.
org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "/findById/{id=${country.id}}" (template: "country" - line 555, col 26)
at org.thymeleaf.spring5.expression.SPELVariableExpressionEvaluator.evaluate(SPELVariableExpressionEvaluator.java:292) ~[thymeleaf-spring5-3.0.14.RELEASE.jar:3.0.14.RELEASE]
Caused by: org.springframework.expression.spel.SpelParseException: Expression [/findById/{id=${country.id}}] #0: EL1070E: Problem parsing left operand
This is my data class
Entity
#Data
#NoArgsConstructor
#AllArgsConstructor
public class Country {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String code;
private String capital;
private String description;
private String nationality;
private String continent;
}
My Controller class
#Controller
public class CountryController {
#Autowired
private CountryService countryService;
#GetMapping("/countries")
public String getCountry(Model model){
List<Country> countryList = countryService.getAllCountry();
model.addAttribute("countries",countryList);
return "country";
}
#PostMapping("/countries/addNew")
public String saveInfo(Country country){
countryService.saveCountryInfo(country);
return "redirect:/countries";
}
#GetMapping("/findById/{id}")
#ResponseBody
public ResponseEntity<Country> getCountryById(#PathVariable("id") Long countryId){ //Bind PathVariable id to id
return ResponseEntity.ok(countryService.getCountryById(countryId)) ;
}
#GetMapping("/country/code/{code}")
public Country getCountryCode(#PathVariable("code") String code){
return countryService.getCountryByCode(code);
}
}
My Service class
#Service
public class CountryService {
#Autowired
private CountryRepository countryRepository;
public List<Country> getAllCountry() {
return countryRepository.findAll();
}
public void saveCountryInfo(Country country){
countryRepository.save(country);
}
public Country getCountryById(Long id){
return countryRepository.findById(id).get();
}
public Country getCountryByCode(String code){
return countryRepository.findByCode(code);
}
}
My Repository class
#Repository
public interface CountryRepository extends JpaRepository<Country,Long> {
public Country findByCode(String code);
}
Here is the html code
<section class="section dashboard">
<div class="row">
<!-- Left side columns -->
<div class="row">
<div class="col-lg-9 col-md-12">
<div class="panel panel-default">
<div class="panel-heading">
<!-- Image background -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addModal" data-whatever="#mdo">Add A Country</button>
<h1>List of Country</h1>
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Code</th>
<th>Capital</th>
<th>Description</th>
<th>Nationality</th>
<th>Continent</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr th:each="country:${countries}">
<td th:text="${country.id}"></td>
<td th:text="${country.code}">Code</td>
<td th:text="${country.capital}">Capital</td>
<td th:text="${country.description}">Description</td>
<td th:text="${country.nationality}">Nationality</td>
<td th:text="${country.continent}">Continent</td>
<td>
<div class="btn-group">
<a th:href="${/findById/{id=${country.id}}}" class="btn btn-primary" id="editButton" data-bs-toggle="modal" data-bs-target="#editModal">Edit</a>
</div>
</td>
</tr>
</tbody>
</table>
</div><!-- End of Image background -->
</div><!-- End Left side columns -->
</div>
</div>
</div>
</section>

Trying to create a composite jpa object in Spring + Thymeleaf

I've tried to create an object with another object inside, with a form but the Object picked from a dropdown list gets converted into a String when returned from the Thymeleaf form.
Those are the entities in my project, with an 1:n relatioship between them:
Entity User
//imports
#Entity
#Table(name = "USERS")
public class User {
#Id
#GeneratedValue
#Column( name ="USER_ID")
private int id;
#Column( name ="username")
private String username;
#Column( name ="password")
private String password;
#Column( name ="email")
private String email;
#OneToMany(fetch= FetchType.LAZY, mappedBy="user", cascade = CascadeType.ALL)
private List<Post> posts;
//setter & getters & toString
}
Entity Post
//imports
#Entity
#Table(name="POSTS")
public class Post {
#Id
#GeneratedValue
#Column(name="POST_ID")
private int id;
#Column(name="tittle")
private String tittle;
#Column(name="text")
private String text;
#ManyToOne
#JoinColumn(name="USER_ID",referencedColumnName="USER_ID")
private User user;
//getters & setters & toString
To create a new Post:
//In Controller
#RequestMapping(value = "/posts/new")
public String newPost(Model model) {
model.addAttribute("post", new Post());
model.addAttribute("users", userService.list());
return "addPost";
}
Which returns the template that has this form:
<form th:action="#{/savePost}" th:object="${post}" method="post">
<tr>
<td><input type="hidden" th:field="${post.id}" /></td>
</tr>
<tr>
<td>Titulo</td>
<td>Texto</td>
<td>Usuario</td>
</tr>
<tr>
<td><input type="text" th:field="${post.tittle}"
th:value="${post.tittle}" /></td>
<td><input type="text" th:field="${post.text}"
th:value="${post.text}" /></td>
<td><select th:field="${post.user}">
<option th:each="user : ${users}" th:text="${user.username}"
th:value="${user.id}"></option>
</select></td>
</tr>
<tr>
<td colspan="3"><input class="btn btn-primary" type="submit"
value="GUARDAR"></td>
</tr>
</form>
The action attribute in the form calls:
#PostMapping("/savePost")
//#RequestMapping(value = "users/save",method = RequestMethod.POST)
public String savePost(#ModelAttribute Post post) {
postService.add(post);
return "redirect:/posts";
}
At this point, I try to create a Post and select a User from the dropdown but when attempting to save it gives me this error:
Field error in object 'post' on field 'user': rejected value [16]; codes [typeMismatch.post.user,typeMismatch.user,typeMismatch.com.julian.bootmvchibernate.model.User,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [post.user,user]; arguments []; default message [user]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'com.julian.bootmvchibernate.model.User' for property 'user'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [#javax.persistence.ManyToOne #javax.persistence.JoinColumn com.julian.bootmvchibernate.model.User] for value '16'; nested exception is java.lang.NullPointerException]
So I tried to implement a Formatter like so:
public class UserFormatter implements Formatter<User> {
#Autowired
#Qualifier("userService")
public GeneralService<User> userService;
#Override
public String print(User object, Locale locale) {
return (object != null ? object.getUsername() : "");
}
#Override
public User parse(String text, Locale locale) throws ParseException {
final Integer userId = Integer.parseInt(text);
return userService.get(userId);
}
}
Registering it:
#SpringBootApplication
public class BootmvchibernateApplication implements WebMvcConfigurer{
#SuppressWarnings("unchecked")
#Override
public void addFormatters(FormatterRegistry registry) {
registry.addFormatter(new UserFormatter());
}
public static void main(String[] args) {
SpringApplication.run(BootmvchibernateApplication.class, args);
}
}
But when this approach is tried the next error is found, this just uppon accessing the /post/new direcction (the template addPost doesn't work):
An error happened during template parsing (template: "class path resource [templates/addPost2.html]")
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/addPost2.html]")
.....
Caused by: org.attoparser.ParseException: Error during execution of processor 'org.thymeleaf.spring5.processor.SpringOptionFieldTagProcessor' (template: "addPost2" - line 43, col 8)
.....
Caused by: org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [#javax.persistence.ManyToOne #javax.persistence.JoinColumn com.julian.bootmvchibernate.model.User] for value '2'; nested exception is java.lang.NullPointerException
at org.springframework.core.convert.support.ConversionUtils.invokeConverter(ConversionUtils.java:47)
If any more information is needed, tell me and I post it.
EDIT: this is the repository if someone is interested.
github.com/JulianBautistaVelez/JPA_Spring_Excercise
The problem is in your addPost.html except that everything is ok now.
<table>
<form th:action="#{/posts/new/mod}" th:object="${post}"
method="POST">
<tr>
<td><input type="hidden" th:field="${post.id}" /></td>
</tr>
<tr>
<td>Titulo</td>
<td>Texto</td>
<td>Usuario</td>
</tr>
<tr>
<td><input type="text" th:field="${post.tittle}"
th:value="${post.tittle}" /></td>
<td><input type="text" th:field="${post.text}"
th:value="${newPost.text}" /></td>
<!-- <td><select th:field="${newPost.user}">
<option th:each="user : ${users}" th:text="${user.username}"
th:value="${user.id}"></option>
</select></td> -->
<td><select th:field="*{user}" class="form-control">
<option th:each="user: ${users}"
th:value="${user.id}" th:text="${user.username}"></option>
</select></td>
</tr>
<tr>
<td colspan="3"><input class="btn btn-primary" type="submit"
value="GUARDAR"></td>
</tr>
</form>
</table>
I changed newPost as post , because you are adding in here as post model.
#RequestMapping(value = "/posts/new")
public String newPost(Model model) {
logger.info("-- en NEW Usuario");
model.addAttribute("post", new Post());
model.addAttribute("users", userService.list());
logger.info("-- -- -- LISTA DE USUARIOS -- -- --");
System.out.println(userService.list());
return "addPost";
}

Naming variables/fields?? Not accepting names - Thymeleaf and Spring Boot MVC

I am new to Spring Boot and I am am working on creating connecting the front of an application to the back at the moment.
I used this site https://spring.io/guides/gs/validating-form-input/
to work on a simple example and it worked fine. It uses the names 'name' and 'age' for the two fields, and getAge, and getName etc for getters and setters.
This code works:
HTML form:
<html>
<body>
<form action="#" th:action="#{/}" th:object="${personForm}" method="post">
<table>
<tr>
<td>Name:</td>
<td><input type="text" th:field="*{name}" /></td>
<td th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</td>
</tr>
<tr>
<td>Age:</td>
<td><input type="text" th:field="*{age}" /></td>
<td th:if="${#fields.hasErrors('age')}" th:errors="*{age}">Age Error</td>
</tr>
<tr>
<td><button type="submit">Submit</button></td>
</tr>
</table>
</form>
</body>
</html>
Person java class
public class PersonForm {
#NotNull
#Size(min=2, max=30)
private String name;
#NotNull
#Min(18)
private Integer age;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String toString() {
return "Person(Name: " + this.name + ", Age: " + this.age + ")";
}
}
Controller
#Controller
public class WebController extends WebMvcConfigurerAdapter {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/results").setViewName("results");
}
#GetMapping("/")
public String showForm(PersonForm personForm) {
return "form";
}
#PostMapping("/")
public String checkPersonInfo(#Valid PersonForm personForm, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "form";
}
return "redirect:/results";
}
}
I have simply changed the names of the variables to the below: (2 strings instead of an int and a string). The following error is displayed when I try to view the page: Error during execution of processor 'org.thymeleaf.spring4.processor.attr.SpringInputGeneralFieldAttrProcessor' (form:33)
Line 33 has " th:field="*{testcolumn}" " on it.
Is there certain naming conventions you must follow with thymeleaf perhaps? I cannot find information about it. Thanks
Person class:
#NotNull
#Size(min=2, max=30)
private String testcolumn;
#NotNull
private String testcolumntwo;
public String getTestcolumn() {
return this.testcolumn;
}
public void setTestcolumn(String testcolumn) {
this.testcolumn = testcolumn;
}
public String getTestcolumntwo() {
return testcolumntwo;
}
public void setTestcolumntwo(String testcolumntwo) {
this.testcolumntwo = testcolumntwo;
}
public String toString() {
return "Person(Name: " + this.testcolumntwo + ", Age: " + this.testcolumntwo + ")";
}
HTML Form:
<form action="#" th:action="#{/}" th:object="${personForm}" method="post">
<table>
<tr>
<td>Name:</td>
<td><input type="text" th:field="*{testcolumn}" /></td>
<td th:if="${#fields.hasErrors('testcolumn')}" th:errors="*{testcolumn}">Name Error</td>
</tr>
<tr>
<td>Age:</td>
<td><input type="text" th:field="*{testcolumntwo}" /></td>
<td th:if="${#fields.hasErrors('testcolumntwo')}" th:errors="*{testcolumntwo}">Age Error</td>
</tr>
<tr>
<td><button type="submit">Submit</button></td>
</tr>
</table>
</form>

Spring 3 RadioButtonsTag Attribute 'items' must be an array, a Collection or a Map Exception

I am populate a List of String as radio button in the JSP. I add the List to the ModelMap but still the below Exception occurred. What am i missing please?
Attribute 'items' must be an array, a Collection or a Map:
java.lang.IllegalArgumentException: Attribute 'items' must be an
array, a Collection or a Map
#Controller
public class EmployeeController {
#Autowired
private EmployeeManager employeeManager;
#RequestMapping(value = {"/"}, method = RequestMethod.GET)
public String homePage(ModelMap map) {
map.addAttribute("employee", new Employee());
populateDepartments(map);
return "addEmployee";
}
private void populateDepartments(ModelMap map){
List<String> departments = new ArrayList<String>();
departments.add("Dept 1");
departments.add("Dept 2");
map.addAttribute("departments",departments);
}
}
addEmployee.jsp:
<form:form method="post" action="add" commandName="employee">
<table>
<tr>
<td><form:label path="name">Name</td>
<td><form:input path="name" /></td>
<td>Address</td>
<td><form:input path="address" /></td>
<td>Departments</td>
<td><form:radiobuttons path="empDepartment" items="${departments}"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Add"/>
</td>
</tr>
</table>
</form:form>
The entity
#Entity
public class Employee {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String name;
private String address;
#Transient
private String empDepartment;
}

Spring MVC - populate enum to dropdownlist

I have a form like this :
<form:form method="POST" action="searchProjects" commandName="projectcriteria">
<table>
<tr>
<td class="label"><spring:message code="number" /></td>
<td><form:input path="number" /></td>
<td class="label"><spring:message code="customer" /></td>
<td><form:input path="customer" /></td>
</tr>
<tr>
<td class="label"><spring:message code="name" /></td>
<td><form:input path="name" /></td>
<td class="label"><spring:message code="status" /></td>
<td>
<form:select path="status">
<option value=""><spring:message code="please_select" /></option>
<c:forEach var="enum" items="${allStatus}">
<option value="${enum}"><spring:message code="${enum.statusEnum}" /></option>
</c:forEach>
</form:select>
</td>
</tr>
<tr>
<td colspan="4" style="text-align: center;">
<input type="submit" value="<spring:message code="search"/>" />
<input type="button" value="<spring:message code="reset_criteria"/>" />
</td>
</tr>
</table>
</form:form>
The Projectcriteria and the StatusEnum are like this:
public enum StatusEnum {
INV("Invalidate"),
TOV("Validate"),
VAL("Validated"),
FIN("Finished");
private String name;
private StatusEnum(String name) {
this.name = name;
}
public String getStatusEnum() {
return this.name;
}
}
public class ProjectCriteria {
private long number;
private String name;
private String customer;
private StatusEnum status;
/**
* #return the number
*/
public long getNumber() {
return number;
}
/**
* #param number the number to set
*/
public void setNumber(long number) {
this.number = number;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the customer
*/
public String getCustomer() {
return customer;
}
/**
* #param customer the customer to set
*/
public void setCustomer(String customer) {
this.customer = customer;
}
/**
* #return the status
*/
public StatusEnum getStatus() {
return status;
}
/**
* #param status the status to set
*/
public void setStatus(StatusEnum status) {
this.status = status;
}
}
How do I populate the StatusEnum attribute in the ProjectCriteria class to the jsp page. What do i have to put into the Controller?
Thanks a lot for any help.
Add your enum values in Controller method which giving request to respective page i.e.
model.addAttribute("enumValues",StatusEnum.value());
Then iterate enumValues in dropdown menu using foreach.
You could try this (sorry code not tested):
<c:forEach var="enum" items="${StatusEnum.values()}">
<option value="${enum}"><spring:message code="${enum.name}" /></option>
</c:forEach>
Note: if your enum class has a package name, you might have to include the fully qualified class name in the items attribute. You might be able to pass the enum as a model attribute from your controller as well (?).

Categories

Resources