I have s simple Java Spring Project with simple DataBase. My Tables "Park_lot" and "Cars" have relation @OneToOne. How Can I add all information from one column "location" to , that used to add info to table Cars?
My models: ParkLot.java
package com.valderosh.carrent.models;
import javax.persistence.*;
import java.util.List;
@Entity
public class ParkLot {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String phoneNumber;
private String location;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public ParkLot() {
}
public ParkLot(String phoneNumber, String location) {
this.phoneNumber = phoneNumber;
this.location = location;
}
}
Cars.java
package com.valderosh.carrent.models;
import javax.persistence.*;
@Entity
public class Cars {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
//Fields
private String brand;
private String mark;
private String segment;
private String colour;
private String power;
private String drive_opt;
private String status;
private String fuel;
private String transmission;
private String image;
private String number;
//Relations
@OneToOne(mappedBy = "cars", fetch = FetchType.EAGER)
private Prices prices;
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name="park_id")
private ParkLot location;
//Constructor
public Cars() {
}
public Cars(String brand, String mark, String segment, String colour, String power, String drive_opt, String status, String fuel, String transmission, String image, String number, Prices prices, ParkLot location) {
this.brand = brand;
this.mark = mark;
this.segment = segment;
this.colour = colour;
this.power = power;
this.drive_opt = drive_opt;
this.status = status;
this.fuel = fuel;
this.transmission = transmission;
this.image = image;
this.number = number;
this.prices = prices;
this.location = location;
}
//GetSetters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getMark() {
return mark;
}
public void setMark(String mark) {
this.mark = mark;
}
public String getSegment() {
return segment;
}
public void setSegment(String segment) {
this.segment = segment;
}
public String getColour() {
return colour;
}
public void setColour(String colour) {
this.colour = colour;
}
public String getPower() {
return power;
}
public void setPower(String power) {
this.power = power;
}
public String getDrive_opt() {
return drive_opt;
}
public void setDrive_opt(String drive_opt) {
this.drive_opt = drive_opt;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getFuel() {
return fuel;
}
public void setFuel(String fuel) {
this.fuel = fuel;
}
public String getTransmission() {
return transmission;
}
public void setTransmission(String transmission) {
this.transmission = transmission;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public Prices getPrices() {
return prices;
}
public void setPrices(Prices prices) {
this.prices = prices;
}
public ParkLot getLocation() {
return location;
}
public void setLocation(ParkLot location) {
this.location = location;
}
}
My Controllers:
CarsController
package com.valderosh.carrent.controllers;
import com.valderosh.carrent.models.*;
import com.valderosh.carrent.repository.CarsRepository;
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 org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.ArrayList;
import java.util.Optional;
@Controller
public class CarsController {
@Autowired
private CarsRepository carsRepository;
@GetMapping("/cars-manage/add")
public String carsAddpage(@RequestParam ParkLot location, Model model) {
model.addAttribute("parking", location);
return "cars/carsAdd";
}
@PostMapping("/cars-manage/add")
public String newCarAdd( @RequestParam String brand, @RequestParam String mark, @RequestParam String segment, @RequestParam String colour, @RequestParam String power, @RequestParam String drive_opt, @RequestParam String transmission, @RequestParam String fuel, @RequestParam String status,@RequestParam String image, @RequestParam String number, @RequestParam(required = false) Prices prices, @RequestParam ParkLot location, Model model) {
Cars newCar = new Cars(brand, mark, segment, colour, power, drive_opt, status, fuel, transmission, image, number, prices, location);
carsRepository.save(newCar);
return "redirect:/car-park";
}
}
HTML Template (with using ThymeLeaf)
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>New Car</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
<body>
<div >
<header th:insert = "components/header :: header"></header>
<h2>New Car</h2>
<div >
<div >
<div >
<form action="/cars-manage/add" method="post" >
<div >
<div >
<h5 >Other///</h5>
<p >Segment</p>
<select name="segment" >
<option value="Econom">Econom</option>
<option value="Standart">Standart</option>
<option value="Luxury">Luxury</option>
</select>
<p >Status</p>
<select name="status" >
<option value="Free">Free</option>
<option value="Used">Used</option>
<option value="In Repair">In Repair</option>
</select>
<p >Number Plates</p>
<input name="number" placeholder="Number" >
<p >LOCATION</p>
<!--Here i want to place all values from column "Location", table ParkLot to this option list named "location" -->
<select name="location" >
<option th:each="park : ${parking}" th:value="${park.location}" th:text="${park.location}"></option>
</select>
</div>
</div>
<button type="submit" >Create</button>
</form>
</div>
</div>
<img src="https://lh3.googleusercontent.com/Vo-uOewd9MJF9S5RMCcECaIV5r8d4iaIFZCIdWTfygwRFNB5Uf5NTOInEzzkNAK-Dd3bds5MMzFXgCONuv4tpBm86cnMGeGQ35Q5KgnquRGiaOikkXNV_7nlf2kRUfF9492r9gjVpyFntFiTCTnbXSe8gXmQE5TFY0ukvBesQ-ttPQprsg6oeCErPgjAsppky4Cw28xX7N1Tbk5yUMYEYFvGKjd8PioXyjJo1n5q5YURRLfM_kD7T4JOfEbABxFxfSP0o5vqpln8KY2piwn7JKy7yoqocVCv9EACixyH-utDYe0BFRgcEqRmmujtmPbrnBTMwXX9V0D1dw7gbXlJoS9GBTX_MIprkuZ8RAkGxdc1rLMuMQZwJ3GR415uPCOSKRtkv9qS5pe41ADi5MaWFM7CRNtkevdq9IXQ7iachfISV5dt0fvov_uw1TFHIfGkn7v7wRHFsXOx_dIh4n04mxut2MfZXHNV7LPJOSScAKsZpwRUeCXWK6zXmBoa1kxZmsOw3P2NVwHriBnxjicfgIe5Yo7AbXMKX1ly0X1K3vlKV4CN2YOQ8sq2RhPnxEknXO3HNbz8nw2nj1KRliYcCiHSfPVYReI_7N3hz4gKCr8S-8ZsqZrIyizpXvpXmu3mzMtASLw-BeYHfcXqr4qF6AFREIgMJQMdVY-ZyWL8Wqpqr2x1lpQ3kl1Z56tbXHGVh5tbHBc370yTIf0LdDa65OfQdTH9ItDgTf4yh7ZAX_xRcv8eg5SYYKLkqodrvUIlxanVXDzY4aIh3YAvUP4M0JwgNilxiwBGmSLJGM_3P2E3RN08YrSb4brpb_PXt7rnkUFMoru6ig4kMjKCZsjw5Dv49LUiqxjrZLDEGIIuspiDuh_LmhsXV2FnmBygcP9GsMgxlJf7UA=s800-no?authuser=4" height="600" width="400">
</div>
<footer th:insert = "components/footer :: footer"></footer>
</div>
</body>
</html>
When i started app and foint to "carAdd" Page i have this exception:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.6.3)
2022-05-29 01:49:33.565 INFO 16404 --- [ main] c.valderosh.carrent.CarrentApplication : Starting CarrentApplication using Java 15.0.2 on LynxPad with PID 16404 (C:\Users\HP\Desktop\Java\Spring\Projects\carrent\target\classes started by Lynx in C:\Users\HP\Desktop\Java\Spring\Projects\carrent)
2022-05-29 01:49:33.567 INFO 16404 --- [ main] c.valderosh.carrent.CarrentApplication : No active profile set, falling back to default profiles: default
2022-05-29 01:49:34.810 INFO 16404 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-05-29 01:49:34.944 INFO 16404 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 120 ms. Found 8 JPA repository interfaces.
2022-05-29 01:49:35.886 INFO 16404 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-05-29 01:49:35.902 INFO 16404 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-05-29 01:49:35.902 INFO 16404 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.56]
2022-05-29 01:49:36.055 INFO 16404 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-05-29 01:49:36.055 INFO 16404 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2387 ms
2022-05-29 01:49:36.364 INFO 16404 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-05-29 01:49:36.440 INFO 16404 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.4.Final
2022-05-29 01:49:36.488 INFO 16404 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-05-29 01:49:36.606 INFO 16404 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-05-29 01:49:36.779 INFO 16404 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2022-05-29 01:49:36.808 INFO 16404 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL57Dialect
2022-05-29 01:49:37.696 INFO 16404 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-05-29 01:49:37.705 INFO 16404 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-05-29 01:49:37.772 WARN 16404 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2022-05-29 01:49:38.740 INFO 16404 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Will secure any request with [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@63d66761, org.springframework.security.web.context.SecurityContextPersistenceFilter@e645600, org.springframework.security.web.header.HeaderWriterFilter@37753b69, org.springframework.security.web.authentication.logout.LogoutFilter@39004e4f, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@4ec37a42, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@78d61f17, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@47d4e28a, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@434a8938, org.springframework.security.web.session.SessionManagementFilter@74c04377, org.springframework.security.web.access.ExceptionTranslationFilter@1ab1d93d, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@6e78177b]
2022-05-29 01:49:39.463 INFO 16404 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-05-29 01:49:39.483 INFO 16404 --- [ main] c.valderosh.carrent.CarrentApplication : Started CarrentApplication in 6.485 seconds (JVM running for 7.21)
2022-05-29 01:50:10.206 INFO 16404 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-05-29 01:50:10.206 INFO 16404 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-05-29 01:50:10.209 INFO 16404 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 3 ms
2022-05-29 01:50:14.304 WARN 16404 --- [nio-8080-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required request parameter 'location' for method parameter type ParkLot is not present]
CodePudding user response:
In your GET request you should specify the location parameter which will match your method parameter @RequestParam String location
:
Example:
"/cars-manage/add?location=<your location>"
and in your method signature should be String like :
@GetMapping("/cars-manage/add")
public String carsAddpage(@RequestParam String location, Model model)
It's also possible binding parameters as Map and Lists.
Example here: https://www.baeldung.com/spring-request-param