Attribute name cannot be null or empty - java

I have to show the data form my database to an HTML view like a dropdown menu for that I have created an enitiy, controller and a repository packages.
moreover, I have a dedicated MySql database ready for that I have used the application properties.
CONTROLLER CLASS
import package com.data.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import com.data.Entity.Location;
import com.data.repository.LocationRepository;
#Controller
public class LocationController {
#Autowired
private LocationRepository locRepo;
#GetMapping("/")
public String home( Model m) {
List<Location> list = locRepo.findAll();
m.addAttribute("all_places", list);
return "index";
}
}
HTML PAGE
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<select th: each="p: ${all_places}">
<option th:text="${p.name}"></option>
</select>
</body>
</html>
ENTITY CLASS
package com.data.Entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
#Entity
#Table(name = "location_dtls")
public class Location {
#Id
#GeneratedValue(strategy = jakarta.persistence.GenerationType.IDENTITY)
private long id;
#Column(name = "place_name")
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Location [id=" + id + ", name=" + name + "]";
}
}
REPOSITORY CLASS
package com.data.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.data.Entity.Location;
public interface LocationRepository extends JpaRepository<Location, Long> {
}
ERROR
Caused by: java.lang.IllegalArgumentException: Attribute name cannot be null or empty

There is a problem in your index.html
<select>
<option th:each="p:${all_places}" th:value="${p.name}" th:text="${p.name}"></option>
</select>
this will resolve the issue

In your template, you have a space between th: and each, which I guess Thymeleaf chokes on.

Related

How can I get the information that I already put in H2 Database to thymeleaf page?

Client.java
package com.example.demo.entities;
import java.io.Serializable;
import java.util.Collection;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
#Entity
#Table(name = "clients")
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
public class Client implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "name")
private java.lang.String nom;
#Column(name = "adress")
private java.lang.String adresse;
private String mail;
private String telephone;
public Client(String nom, String adresse) {
super();
this.nom = nom;
this.adresse = adresse;
}
public Client(String nom, String adresse, String mail, String telephone) {
super();
this.nom = nom;
this.adresse = adresse;
this.mail = mail;
this.telephone = telephone;
}
public Client() {};
}
ClientController.java
package com.example.demo.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import com.example.demo.entities.Client;
import com.example.demo.repository.ClientRepository;
#Controller
public class ClientController{
#Autowired
public ClientRepository cr;
#GetMapping("/")
public String viewHomePage(Model model) {
List <Client> list= cr.findAll();
model.addAttribute("list",list);
return "home";
}
}
ClientRepository.java
package com.example.demo.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.demo.entities.Client;
#Repository
public interface ClientRepository extends JpaRepository<Client,Long>{
}
main.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import com.example.demo.entities.Client;
import com.example.demo.repository.ClientRepository;
#SpringBootApplication
public class Shop1Application {
public static void main(String[] args) {
ApplicationContext crt=SpringApplication.run(Shop1Application.class, args);
ClientRepository cr=crt.getBean(ClientRepository.class);
Client c1=new Client("Bilel","Hammamet","myemailis","123456");
Client c2=new Client("Wissal","Tunis","herrmail","1151");
Client c3=new Client("Mohamed","nabeul","hisemail","444");
Client c4=new Client("anas","Hammamet","his","55222");
Client c5=new Client("mourad","tunis","fffff","44");
cr.save(c1);
cr.save(c2);
cr.save(c3);
cr.save(c4);
cr.save(c5);
}
}
home.html
<!DOCTYPE html>
<html xmlns:th="http//www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1 > Liste des clients de la base </h1>
<div>
<table>
<tr>
<th>ID</th><th>Nom</th><th>Adresse</th><th>Mail</th><th>telephone</th>
</tr>
<tr th:each="c:${list}">
<td th:text="${c.id}"></td>
<td th:text="${c.nom}"></td>
<td th:text="${c.adresse}"></td>
<td th:text="${c.mail}"></td>
<td th:text="${c.telephone}"></td>
</tr>
</table>
</div>
</body>
</html>
This is an ss of my packages
This is an ss of error in localhost:8080
This is h2 database
I tried to change in the home.html file but nothing happened I think the problem is in the home.html (Thymeleaf section). I think I have a problem calling the id, adresse, telephone from the repository which found in the h2 database to make them appear in a table in the thymeleaf page.
One thing this cloud happen is some html tags aren't enclosed well. Like your tag should be closed too.

Angular HttpErrorResponse GET Request

I have a simple Quarkus project and want to show the data in an Angular table with HttpClient. I also have a CORS Filter. Anyway, I get the following error:
Angular table with no date, HttpErrorResponse Status 0
service.ts
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { School } from './model/school';
#Injectable({
providedIn: 'root'
})
export class SchoolService {
url = "localhost:8080/school"
constructor(public http: HttpClient) { }
getAll(): Observable<School[]> {
return this.http.get<School[]>(this.url);
}
getById(id: number): Observable<School> {
const url = "locahlost:8080/school/{id}";
return this.http.get<School>(url);
}
}
ts of component
import { Component, OnInit } from '#angular/core';
import { School } from '../model/school';
import { SchoolService } from '../school.service';
#Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
schools: School[] = [];
constructor(public schoolService: SchoolService) { }
ngOnInit(): void {
this.schoolService.getAll().subscribe(e => {
this.schools = e;
});
}
}
html
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Street</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let school of schools">
<td>{{school.id}}</td>
<td>{{school.name}}</td>
<td>{{school.street}}</td>
</tr>
</tbody>
</table>
server model
package model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class School {
#Id
#GeneratedValue
private int id;
private String name;
private String street;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
}
resource
package rest;
import model.School;
import javax.inject.Inject;
import javax.transaction.Transactional;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.List;
#Path("school")
#Produces(MediaType.APPLICATION_JSON)
#Transactional
public class SchoolResource {
#Inject
SchoolDao dao;
#GET
public List<School> getAll() {
return dao.getAll();
}
#Path("id")
#GET
public School getById(#PathParam("id") int id) {
return dao.getById(id);
}
}
dao
package rest;
import model.School;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import java.util.List;
#Dependent
public class SchoolDao {
#Inject
EntityManager em;
public List<School> getAll() {
return em.createQuery("select s from School s", School.class).getResultList();
}
public School getById(int id) {
return em.find(School.class, id);
}
}
Thank you in advance, I think the problem must be on the server, because I tried showing data with a JSON file instead of Quarkus data already, and it does work.
As #R.Richards mentioned in a comment, putting "http://" in front of the url in the service file solved the problem.

OneToOne Spring Hibernate Thymeleaf

I am trying to add 2 values ​​"name" and "city" to my 2 tables using #OneToOne. I think I write incomplete code at #Controller and wrong at Thymeleaf code. Help me . Thanks very much
Student.java
package com.example.demo.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name = "student")
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "student_id")
private long studentId;
#Column(name = "name")
private String name;
#OneToOne
#JoinColumn(name = "home_address_id")
private Address address;
public long getStudentId() {
return studentId;
}
public void setStudentId(long studentId) {
this.studentId = studentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
Address.java
package com.example.demo.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "address")
public class Address {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "address_id")
private long addressId;
#Column(name = "city")
private String city;
public long getAddressId() {
return addressId;
}
public void setAddressId(long addressId) {
this.addressId = addressId;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
StudentRepository.java
package com.example.demo.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.demo.models.Student;
public interface StudentRepository extends JpaRepository<Student, Long> {
Student findByName (String name);
}
StudentService.java
package com.example.demo.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.models.Student;
import com.example.demo.repository.StudentRepository;
#Service
public class StudentService {
#Autowired
private StudentRepository studentRepository;
public List<Student> findAll (){
return studentRepository.findAll();
}
public Student findByName (String name) {
return studentRepository.findByName(name);
}
public Student save (Student student) {
return studentRepository.save(student);
}
}
StudentController.Java
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;
import com.example.demo.models.Student;
import com.example.demo.service.StudentService;
#Controller
public class StudentController {
#Autowired
private StudentService studentService;
#GetMapping("/all")
public ModelAndView getAll (ModelAndView modelAndView, Student student) {
modelAndView.addObject("student", studentService.findAll());
modelAndView.setViewName("all");
return modelAndView;
}
#GetMapping("/add")
public ModelAndView add (ModelAndView modelAndView, Student student) {
modelAndView.addObject("add", student);
modelAndView.setViewName("add");
return modelAndView;
}
#PostMapping("/add")
public ModelAndView postAdd (ModelAndView modelAndView, Student student) {
Student existStudent= studentService.findByName(student.getName());
if (existStudent!=null) {
modelAndView.setViewName("add");
}
else {
studentService.save(student);
modelAndView.setViewName("success");
}
return modelAndView;
}
}
add.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Add</title>
</head>
<body>
<center>
<form action="#" th:action="#{/add}" th:object="${add}" method="post">
<table>
<tr>
<td><label for="name">Name</label></td>
<td><input th:field="*{name}" type="text" name="name"></input></td>
</tr>
<tr>
<td><label for="city">City</label></td>
<td><input th:field="*{address.city}" type="text" name="address.city"></input>
</td>
</tr>
<tr>
<td><input type="submit" value="Submit"></input></td>
</tr>
</table>
</form>
</center>
</body>
</html>
student.sql
create table student (
student_id BIGINT NOT NULL AUTO_INCREMENT,
home_address_id BIGINT NOT NULL,
name VARCHAR(30) NOT NULL,
PRIMARY KEY (student_id),
CONSTRAINT student_address FOREIGN KEY (home_address_id) REFERENCES ADDRESS ( address_id)
);
Address.sql
create table ADDRESS (
address_id BIGINT NOT NULL AUTO_INCREMENT,
city VARCHAR(30) NOT NULL,
PRIMARY KEY (address_id)
);
I think I am wrong and may write incomplete. If possible, rewrite code snippets I need to fix or add. Thanks very much

SpringBoot+Thymeleaf: Property or field 'name' cannot be found on object of type

I would like to show the Objects in the HTML File with Thymeleaf but it says
"Property or field 'name' cannot be found on object of type 'com.example.demo.Entities.PeopleInformation' - maybe not public or not valid?"
That's my Controller for the Page
package com.example.demo.Controller;
import java.util.ArrayList;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.Entities.PeopleInformation;
#Controller
public class HelloWorld {
#GetMapping(value= "/list_contacts")
public String showContacts(Model m){
ArrayList<PeopleInformation> kontakte = new ArrayList<PeopleInformation>();
PeopleInformation a = new PeopleInformation("Lutz","Walter","0152 222556","Aktuell");
PeopleInformation b = new PeopleInformation("Bosch","Holger","0152 567345","Aktuell");
PeopleInformation c = new PeopleInformation("Schindler","Nicole","0152 220022","Aktuell");
kontakte.add(a);
kontakte.add(b);
kontakte.add(c);
m.addAttribute("kontakte",kontakte);
return "list_contacts";
}
}
That's the Entity using Lombok
package com.example.demo.Entities;
import org.springframework.data.annotation.Id;
import com.microsoft.spring.data.gremlin.annotation.Vertex;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
#NoArgsConstructor #Setter #Getter
public class PeopleInformation {
#Id
private Long id;
private String name;
private String vorname;
private String telefon;
private String status;
public PeopleInformation(String name,String vorname,String telefon,String status) {
this.name = name;
this.vorname = vorname;
this.telefon = telefon;
this.status = status;
}
}
And that's my HTML File with Thymeleaf
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Kontakt-Liste</title>
</head>
<body>
<div>
<table border="1">
<tr>
<th>Name</th>
<th>Vorname</th>
<th>Telefon</th>
<th>Status</th>
</tr>
<tr th:each ="kontakte : ${kontakte}">
<td th:utext="${kontakte.name}">...</td>
<td th:utext="${kontakte.vorname}">...</td>
<td th:utext="${kontakte.telefon}">...</td>
<td th:utext="${kontakte.status}">...</td>
</tr>
</table>
</div>
</body>
</html>
Can someone spot the Problem, Thanks :)
if you want to see data you should declare the getters in the PeopleInformation entity
Like this:
public Long getId() {
return id;
}
public String getName() {
return name;
}
public String getVorname() {
return vorname;
}
public String getTelefon() {
return telefon;
}
public String getStatus() {
return status;
}

How to connect/bind two tables using Spring MVC and hibernate

My English is not very well, so sorry for mistakes.
I'am using a Spring, Spring MVC, Hibernate, Spring Data.
I have two entities Customer and CustomerDetails I would like to connect/bind them.
I'am using #OneToOne annotation, but I have no idea how to set a customer for CusomerDetails and vice versa. I found that I should create Customer and CustomerDetails in controller, and there connect them, but it is not working and I think that it is a bad approach. Anyone knows How should it looks?
Thanks for help.
Customer class:
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="customer")
public class Customer {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="customer_id")
private int id;
#Column(name="name")
private String name;
#Column(name="email")
private String email;
#Column(name="address")
private String address;
#OneToOne(cascade=CascadeType.ALL)
private CustomerDetails customerDetails;
public Customer() {
}
public Customer(CustomerDetails customerDetails)
{
this.customerDetails=customerDetails;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public CustomerDetails getCustomerDetails() {
return customerDetails;
}
public void setCustomerDetails(CustomerDetails customerDetails) {
this.customerDetails = customerDetails;
}
#Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + ", email=" + email + ", address=" + address
+ ", customerDetails=" + customerDetails + "]";
}
}
CustomerDetails:
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="customer_details")
public class CustomerDetails {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#Column(name="surname")
private String lastName;
#Column(name="number")
private int number;
#OneToOne(cascade= {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH})
private Customer customer;
public CustomerDetails() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
#Override
public String toString() {
return "CustomerDetails [id=" + id + ", lastName=" + lastName + ", number=" + number + ", customer=" + customer
+ "]";
}
}
Services:
import java.util.List;
import com.firstapp.entity.Customer;
public interface CustomerService {
public List<Customer>getCustomers();
public Customer getCustomer(int id);
public void saveCustomer(Customer customer);
public void deleteCustomer(int id);
public List<Customer>search(String keyword);
}
public interface CustomerDetailsService {
public List<CustomerDetails> getCustomers();
public CustomerDetails getCustomer(int id);
public void saveCustomer(CustomerDetails customer);
public void deleteCustomer(int id);
}
#Service
public class CustomerServiceImpl implements CustomerService {
#Autowired
private CustomerRepository repo;
public List<Customer> getCustomers() {
return repo.findAll();
}
public Customer getCustomer(int id) {
Optional<Customer>result= repo.findById(id);
return result.get();
}
public void saveCustomer(Customer customer) {
repo.save(customer);
}
public void deleteCustomer(int id) {
repo.deleteById(id);
}
public List<Customer>search(String keyword)
{
return repo.search(keyword);
}
}
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.firstapp.entity.CustomerDetails;
import com.firstapp.repository.CustomerDetailsRepository;
#Service
public class CustomerDetailsServiceImpl implements CustomerDetailsService{
#Autowired
private CustomerDetailsRepository repo;
public List<CustomerDetails> getCustomers() {
return repo.findAll();
}
public CustomerDetails getCustomer(int id) {
return repo.findById(id).get();
}
public void saveCustomer(CustomerDetails customer) {
repo.save(customer);
}
public void deleteCustomer(int id) {
repo.deleteById(id);
}
}
Repositories:
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.firstapp.entity.Customer;
#Repository
public interface CustomerRepository extends JpaRepository<Customer, Integer> {
#Query(value="SELECT c from Customer c where c.name LIKE '%'|| :keyword || '%'"
+ "OR c.email LIKE '%'|| :keyword || '%'"
+ "OR c.address LIKE '%'|| :keyword || '%'")
public List<Customer>search(#Param("keyword")String keyword);
}
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.firstapp.entity.CustomerDetails;
#Repository
public interface CustomerDetailsRepository extends JpaRepository<CustomerDetails, Integer> {
}
My controller:
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.firstapp.entity.Customer;
import com.firstapp.entity.CustomerDetails;
import com.firstapp.service.CustomerDetailsService;
import com.firstapp.service.CustomerDetailsServiceImpl;
import com.firstapp.service.CustomerService;
import com.firstapp.service.CustomerServiceImpl;
#Controller
#RequestMapping("/customer")public class CustomerController {
#Autowired
private CustomerService service;
#Autowired
private CustomerDetailsService serviceCD;
#GetMapping("/home")public String home(Model model)
{
List<Customer>customers=service.getCustomers();
model.addAttribute("message","Hello from Spring MVC"); model.addAttribute("customers",customers);
return "home-page";
}
#GetMapping("/showForm")
public String showForm(Map<String,Object>model)
{
Customer customer=new Customer();
CustomerDetails cd=new CustomerDetails();
customer.setCustomerDetails(cd);
model.put("customer",new Customer());
model.put("customerDetails", cd);
return "new-customer";
}
#PostMapping("/add")
public String addCustomer(#ModelAttribute("customer") Customer customer)
{
service.saveCustomer(customer);
return "redirect:/customer/addDetails";
}
#RequestMapping("/addDetails")
public String addCustomerDetails(#ModelAttribute("customerDetails") CustomerDetails customerDt)
{
serviceCD.saveCustomer(customerDt);
return "redirect:/customer/home";
}
#GetMapping("/edit")
public String editCustomer(#RequestParam int id, Model model)
{
Customer customer=service.getCustomer(id);
model.addAttribute("customer",customer);
return "edit-customer";
}
#GetMapping("/delete")
public String deleteCustomer(#RequestParam int id)
{
service.deleteCustomer(id);
return "redirect:/customer/home";
}
#GetMapping("/search")
public String search(#RequestParam String keyword,Model model)
{
List<Customer>customers=service.search(keyword);
model.addAttribute("customers",customers);
return "search-page";
}
}
my jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Customer registration</title>
</head>
<body>
<div align="center">
<h2>New Customer</h2>
<form:form action="add" method="post" modelAttribute="customer">
<table>
<tr>
<td>Name:</td>
<td><form:input path="name"/></td>
</tr>
<tr>
<td>E-mail:</td>
<td><form:input path="email"/></td>
</tr>
<tr>
<td>Address:</td>
<td><form:input path="address"/></td>
</tr>
<tr>
<td></td><td><input type="submit" value="Submit"/></td>
</tr>
</table>
</form:form>
</div>
</body>
</html>
Set the CustomerDetails for Customer:
customer.setCustomerDetail(customerDetail);
customerDetail.setCustomer(customer);
It's enough. Spring JPA automatically sets references and id's between table entities.
In additional try to change model layer:
1) First what you should to change - add the mappedBy parameter with table name into '#OneToOne'
2) Use #JoinColumn for one of entity:
for Customer:
#OneToOne(mappedBy = "customer")
#JoinColumn(name = "customer_details_id", referencedColumnName = "id")
for CustomerDetails:
#OneToOne(mappedBy = "customer_detail")
in additional: try to save CustomerDetail entity into table after creating, but before saving a Customer.
PS
Does no matter technically where are you create entities - it is just patterns and SOLID principals.
All parameters in #OneToOne and #JoinColumn should be named as fields in entity and as tables. Once I had a very difficult and long resolving with this issue. So be precise.

Categories

Resources