OneToOne Spring Hibernate Thymeleaf - java

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

Related

Attribute name cannot be null or empty

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.

Save List items from html table to Mysql

I am trying to save a list of items from an html table in mysql, but it gives me an error:
Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long[]'; nested exception is java.lang.NumberFormatException: For input string: "{ID}".
My Code is:
Entity Class is
package com.gadpo.cga.app.models.entity;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import org.springframework.format.annotation.DateTimeFormat;
#Entity
#Table(name = "paquetes")
public class Paquete implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotEmpty
private String detalle;
#DateTimeFormat(pattern = "yyyy-MM-dd")
#Temporal(TemporalType.DATE)
#NotNull
#Column(name="fecha")
private Date fecha;
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval=true)
#JoinColumn(name="paquete_id")
private List<Actividad> actividades;
#NotNull
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval=true)
#JoinColumn(name="paquete_id")
private List<ItemPaquete> items;
//#OneToMany(mappedBy = "paquete", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
//private List<Usuario> usuarios;
public List<ItemPaquete> getItems() {
return items;
}
public void setItems(List<ItemPaquete> items) {
this.items = items;
}
#ManyToOne(fetch = FetchType.LAZY)
private Usuario usuario;
#ManyToOne(fetch = FetchType.LAZY)
private Planificacion planificacion;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDetalle() {
return detalle;
}
public void setDetalle(String detalle) {
this.detalle = detalle;
}
public List<Actividad> getActividades() {
return actividades;
}
public void setActividades(List<Actividad> actividades) {
this.actividades = actividades;
}
public Planificacion getPlanificacion() {
return planificacion;
}
public void setPlanificacion(Planificacion planificacion) {
this.planificacion = planificacion;
}
public Usuario getUsuario() {
return usuario;
}
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
public Date getFecha() {
return fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
public void addItemPaquete(ItemPaquete item) {
items.add(item);
}
/**
*
*/
private static final long serialVersionUID = 1L;
}
Controller is:
package com.gadpo.cga.app.controller;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.gadpo.cga.app.models.entity.ItemPaquete;
import com.gadpo.cga.app.models.entity.Paquete;
import com.gadpo.cga.app.models.entity.Planificacion;
import com.gadpo.cga.app.models.entity.Usuario;
import com.gadpo.cga.app.models.service.IUsuarioService;
#Controller
#RequestMapping("/paquete")
#SessionAttributes("paquete")
public class PaqueteController {
#Autowired
private IUsuarioService usuarioService;
private final Logger log = LoggerFactory.getLogger(getClass());
#GetMapping("/form/{planificacionId}")
public String crear(#PathVariable(value="planificacionId") Long planificacionId, Map<String, Object> model, RedirectAttributes flash) {
Planificacion planificacion=usuarioService.findPlanificacionById(planificacionId);
if(planificacion==null) {
flash.addFlashAttribute("error","La planificación no existe en la bd");
return "redirect:/listar";
}
Paquete paquete = new Paquete();
paquete.setPlanificacion(planificacion);
model.put("paquete", paquete);
model.put("titulo", "Registro de paquete");
return "paquete/form";
}
#GetMapping(value="/cargar-usuarios/{term}", produces= {"application/json"})
public #ResponseBody List<Usuario>cargarUsuarios(#PathVariable String term){
return usuarioService.findByApellido(term);
}
#PostMapping("/form")
public String guardar(#Valid Paquete paquete,BindingResult result,Model model,
#RequestParam(name="item_id[]",required = false) Long [] itemId,RedirectAttributes flash, SessionStatus status) {
if (result.hasErrors()) {
model.addAttribute("titulo", "Registrar nuevo paquete");
return "paquete/form";
}
for(int i=0; i<itemId.length;i++) {
//System.out.println("ID del usuario: "+itemId[i]);
Usuario usuario = usuarioService.findUsuarioById(itemId[i]);
ItemPaquete linea = new ItemPaquete();
linea.setUsuario(usuario);
paquete.addItemPaquete(linea);
log.info("ID: "+itemId[i].toString());
}
/* if (result.hasErrors()) {
model.addAttribute("titulo", "Formulario de paquete");
return "paquete/form";
}*/
usuarioService.savePaquete(paquete);
status.setComplete();
flash.addFlashAttribute("success","Paquete creado con éxito!");
return "redirect:listar";
}
}
and my form is
form_paquete
The error is happening in your PaqueteController class in the public String guardar method. Your controller is expecting a java.util.Long array (itemId) but is receiving a String instead.
First, you have to remove the [] in your #RequestParam(name="item_id[]").
Then, make sure that the Post requesting you are sending is like:
{
"item_id": [1,2,3],
...
}
in my form plantilla-items.html the name of td is item_id[]
The code in plantilla-items is:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<table th:fragment="itemsPaquete" class="d-none">
<tbody id="plantillaItemsPaquete">
<tr id="row_{ID}">
<td class="d-none"><input type="hidden" value="{ID}"
name="item_id[]" /></td>
<td>{ID}</td>
<td>{NOMBRE}</td>
<td><a href="#" class="btn btn-danger btn-xs"
onclick="itemsHelper.eliminarLineaFactura({ID});">x</a></td>
</tr>
</tbody>
</table>
</body>
</html>
request
When check the request in the brownser, the first element is a string "{ID}" and no understand

Unable to save one to many relationship entities at the same time on same JSP page using hibernate

I'm new to Spring and trying to build a sample application. In this I have a Company(OwnerCompany) which can have multiple locations(OwnerCompanyOffices). I am trying to save the company and it multiple locations at the same time using same JSP page.I'm not able to get proper data from my JSP page to the spring controller. My Hibernate logs are like this
OwnerCompanyOffices [id=0, name=null, location=null, ownerCompany=null]
Hibernate: insert into owner_company_offices (location, name, owner_company_id) values (?, ?, ?)
Here is my code
My OwnerCompany Entity OwnerCompany.java
package com.sachinmukherjee.spring_hibernate.entity;
import java.util.Set;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "owner_company")
public class OwnerCompany {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name="name")
private String name;
#Column(name = "short_name")
private String short_name;
#OneToMany(mappedBy = "owner_company",cascade = CascadeType.REMOVE,fetch = FetchType.LAZY)
private Set<Users> users;
#OneToMany(mappedBy = "ownerCompany", cascade = CascadeType.REMOVE, fetch = FetchType.EAGER)
private List<OwnerCompanyOffices> ownerCompanyOffices;
public OwnerCompany() {
super();
// TODO Auto-generated constructor stub
}
public OwnerCompany(String name, String short_name) {
this.name = name;
this.short_name = short_name;
}
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 getShort_name() {
return short_name;
}
public void setShort_name(String short_name) {
this.short_name = short_name;
}
public Set<Users> getUsers() {
return users;
}
public void setUsers(Set<Users> users) {
this.users = users;
}
public List<OwnerCompanyOffices> getOwnerCompanyOffices() {
return ownerCompanyOffices;
}
public void setOwnerCompanyOffices(List<OwnerCompanyOffices> ownerCompanyOffices) {
this.ownerCompanyOffices = ownerCompanyOffices;
}
#Override
public String toString() {
return "OwnerCompany [id=" + id + ", name=" + name + ", short_name=" + short_name + ", users=" + users
+ ", ownerCompanyOffices=" + ownerCompanyOffices + "]";
}
public void addOwnerCompanyOffices(OwnerCompanyOffices ownerCompanyOffice) {
if(ownerCompanyOffices == null) {
ownerCompanyOffices = new ArrayList<OwnerCompanyOffices>();
}
ownerCompanyOffices.add(ownerCompanyOffice);
ownerCompanyOffice.setOwnerCompany(this);
}
}
My OwnerCompanyOffices Entity OwnerCompanyOffices.java
package com.sachinmukherjee.spring_hibernate.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name="owner_company_offices")
public class OwnerCompanyOffices {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "name")
private String name;
#Column(name="location")
private String location;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "owner_company_id")
private OwnerCompany ownerCompany;
public OwnerCompanyOffices() {
super();
// TODO Auto-generated constructor stub
}
public OwnerCompanyOffices(String name, String location) {
this.name = name;
this.location = location;
}
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 getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public OwnerCompany getOwnerCompany() {
return ownerCompany;
}
public void setOwnerCompany(OwnerCompany ownerCompany) {
this.ownerCompany = ownerCompany;
}
#Override
public String toString() {
return "OwnerCompanyOffices [id=" + id + ", name=" + name + ", location=" + location + ", ownerCompany="
+ ownerCompany + "]";
}
}
My OwnerCompanyOfficesDAO class OwnerCompanyOfficesDAOImp
package com.sachinmukherjee.spring_hibernate.dao;
import java.util.List;
import javax.transaction.Transactional;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.sachinmukherjee.spring_hibernate.entity.OwnerCompanyOffices;
#Repository
public class OwnerCompanyOfficesDAOImp implements OwnerCompanyOfficesDAO {
#Autowired
SessionFactory sessionFactory;
public List<OwnerCompanyOffices> getAllOffices() {
// TODO Auto-generated method stub
return null;
}
#Transactional
public void saveOffice(OwnerCompanyOffices ownerCompanyOffice) {
Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(ownerCompanyOffice);
}
}
My OwnerCompanyController Class OwnerCompanyController
package com.sachinmukherjee.spring_hibernate.controller;
import java.util.List;
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.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.ui.Model;
import com.sachinmukherjee.spring_hibernate.dao.OwnerCompanyDAO;
import com.sachinmukherjee.spring_hibernate.dao.OwnerCompanyOfficesDAO;
import com.sachinmukherjee.spring_hibernate.entity.OwnerCompany;
import com.sachinmukherjee.spring_hibernate.entity.OwnerCompanyOffices;
#Controller
#RequestMapping("/owner_company/")
public class OwnerCompanyController {
#Autowired
private OwnerCompanyDAO ownerCompanyDAO;
#Autowired
private OwnerCompanyOfficesDAO ownerCompanyOfficesDAO;
#GetMapping("/add/")
public String add(Model model) {
OwnerCompanyOffices ownerCompanyOffices = new OwnerCompanyOffices();
model.addAttribute("ownerCompanyOffices", ownerCompanyOffices);
return "owner_company/add";
}
#PostMapping("/submit")
public String submit(#ModelAttribute("ownerCompanyOffices") OwnerCompanyOffices ownerCompanyOffices) {
System.out.println(ownerCompanyOffices);
ownerCompanyOfficesDAO.saveOffice(ownerCompanyOffices);
return "redirect:/owner_company/";
}
}
My add.jsp page where I'm entering the ownercompany and ownercompanyoffices data
<div class="row">
<div class="col-md-12">
<form action="${pageContext.request.contextPath}/owner_company/submit/" method="POST" modelAttribute="ownerCompanyOffices" class="form-control">
<label>Name</label>
<input name="ownerCompanyOffices.ownerCompany.name" required="required"/>
</br></br>
<label>Short Name</label>
<input name="ownerCompanyOffices.ownerCompany.short_name" type="text" />
</br></br>
<table class="table table-responsive">
<thead>
<tr>
<th>Name</th>
<th>Location</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr class="toClone">
<td><input type="text" name="ownerCompanyOffices.name" required="required"/></td>
<td><input type="text" name="ownerCompanyOffices.location" required="required"/></td>
<td class="remove"></td>
</tr>
<tr id="addRow">
<td></td>
<td></td>
<td>Add More
</tr>
</tbody>
</table>
<button type="submit" class="btn btn-success">Save</button>
</form>
</div>
</div>
</body>
</html>
<script type="text/javascript">
$(document).on("click",".addMore", function(){
var clonedRow = $(".toClone:first").clone();
$(clonedRow).find("input").each(function(){
$(this).val("");
});
$(clonedRow).addClass("toRemove");
$(clonedRow).find(".remove").addClass("removeRow");
$(clonedRow).find(".remove").html("<a href='#'>Remove</a>");
$(clonedRow).insertBefore($("#addRow"));
});
$(document).on("click",".removeRow", function(){
$(this).closest("tr").remove();
});
</script>
Here By clicking on add more link user can add multiple offices against a single company.

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.

Hibernate #ManyToOne mapping issue

i have two tables category and products. where category id is foreign key in products table.when i am trying to insert data in products table using hql my category table is also updated and suppose category is mobile and its id is 1 than after update it will be 1 and null. here are the codes.
Products.java
package com.main.model;
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.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="Products")
public class Products {
#Id#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column
private String productname;
#Column
private String productstore;
#Column
private String productdesc;
#Column
private double price;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="categoryid")
private Category category;
private String imagePath;
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProductname() {
return productname;
}
public void setProductname(String productname) {
this.productname = productname;
}
public String getProductstore() {
return productstore;
}
public void setProductstore(String productstore) {
this.productstore = productstore;
}
public String getProductdesc() {
return productdesc;
}
public void setProductdesc(String productdesc) {
this.productdesc = productdesc;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
}
Category.java
package com.main.model;
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="Category")
public class Category {
#Id#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="category_id")
private int id;
#Column
private String categoryName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
}
admin.jsp
<form id="asd" action="/shopping_cart/addProduct" method="post">
<center>
<h3>Please Enter Product Details</h3>
Category<select name="category.id">
<option name="mobiles" value="1">Mobiles</option>
<option name="" value="2">Books</option>
<option name="" value="3">EarPhones</option>
</select><br /> <br />
Product Name <input type="text" value="" name="productname" width="100%" /><span
id="errorname" required></span> <br /> <br /> Product Store
<input type="text" value="" name="productstore" required /> <span
id="error_address" required></span><br /> <br />
Product Desc<input
type="text" value="" name="productdesc" required> <span
id="error_city"></span><br /> <br /> Image Path
<input
type="text" value="" name="imagePath" /><span id="error_state"></span>
<br /> <br /> Price
<input
type="number" value="" name="price" /><span id="error_zipcode"></span>
<br /> <br />
<input
type="submit" value="Add Product" name="addProduct" />
</center>
</form>
Controller
#RequestMapping(value = "/addProduct", method = RequestMethod.POST)
public ModelAndView processForm11(#ModelAttribute("products1") Products products) {
System.out.println("adding product to db");
adminService.addProduct(products);
System.out.println("Product inserted successfully");
ModelAndView model=new ModelAndView("nextpage");
return model;
}
DAOImpl class
package com.main.dao;
import javax.annotation.Resource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;
import com.main.model.Products;
#Repository
public class AdminDAOImpl implements AdminDAO {#Resource(name="sessionFactory")
protected SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public void addProduct(Products product) {
Session session=sessionFactory.openSession();
Transaction tx=session.beginTransaction();
session.save(product);
tx.commit();
session.close();
}
}
Thanks in advance.

Categories

Resources