org.springframework.beans.factory.UnsatisfiedDependencyException: error after adding new repository - spring

Hello im trying to work on a project first of all it was all smooth when i worked on a single model as you see below "Student"
StudentController
package net.springboot.javaguides.controller;
import javax.validation.Valid;
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 net.springboot.javaguides.entity.Student;
import net.springboot.javaguides.repository.StudentRepository;
#Controller
#RequestMapping("/students/")
public class StudentController {
#Autowired
private StudentRepository studentRepository;
#GetMapping("showForm")
public String showStudentForm(Student student) {
return "student/add-student";
}
#GetMapping("list")
public String students(Model model) {
model.addAttribute("students", this.studentRepository.findAll());
return "student/index";
}
#PostMapping("add")
public String addStudent(#Valid Student student, BindingResult result, Model model) {
if(result.hasErrors()) {
return "student/add-student";
}
this.studentRepository.save(student);
return "redirect:list";
}
#GetMapping("edit/{id}")
public String showUpdateForm(#PathVariable ("id") long id, Model model) {
Student student = this.studentRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Invalid student id : " + id));
model.addAttribute("student", student);
return "student/update-student";
}
#PostMapping("update/{id}")
public String updateStudent(#PathVariable("id") long id, #Valid Student student, BindingResult result, Model model) {
if(result.hasErrors()) {
student.setId(id);
return "student/update-student";
}
// update student
studentRepository.save(student);
// get all students ( with update)
model.addAttribute("students", this.studentRepository.findAll());
return "student/index";
}
#GetMapping("delete/{id}")
public String deleteStudent(#PathVariable ("id") long id, Model model) {
Student student = this.studentRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Invalid student id : " + id));
this.studentRepository.delete(student);
model.addAttribute("students", this.studentRepository.findAll());
return "student/index";
}
}
StudentEntity
package net.springboot.javaguides.entity;
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 = "students")
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "name")
private String name;
#Column(name = "email")
private String email;
#Column(name = "phone_no")
private long phoneNo;
public Student() {
super();
}
public Student(String name, String email) {
super();
this.name = name;
this.email = email;
}
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;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(long phoneNo) {
this.phoneNo = phoneNo;
}
}
StudentRepository
package net.springboot.javaguides.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import net.springboot.javaguides.entity.Student;
#Repository
public interface StudentRepository extends JpaRepository<Student, Long>{
List<Student> findByName(String name);
}
and now im trying to add some new model as you see below but im having error from it :
CourseController
package net.springboot.javaguides.controller;
import javax.validation.Valid;
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 net.springboot.javaguides.entity.Course;
import net.springboot.javaguides.repository.CourseRepository;
#Controller
#RequestMapping("/courses/")
public class CourseController {
#Autowired
private CourseRepository courseRepository;
#GetMapping("showForm")
public String showCourseForm(Course course) {
return "add-course";
}
#GetMapping("list")
public String courses(Model model) {
model.addAttribute("courses", this.courseRepository.findAll());
return "index";
}
#PostMapping("add")
public String addCourse(#Valid Course course, BindingResult result, Model model) {
if(result.hasErrors()) {
return "add-course";
}
this.courseRepository.save(course);
return "redirect:list";
}
#GetMapping("edit/{id}")
public String showUpdateForm(#PathVariable ("id") long id, Model model) {
Course course = this.courseRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Invalid course id : " + id));
model.addAttribute("course", course);
return "update-course";
}
#PostMapping("update/{id}")
public String updateCourse(#PathVariable("id") long id, #Valid Course course, BindingResult result, Model model) {
if(result.hasErrors()) {
course.setId(id);
return "update-course";
}
// update course
courseRepository.save(course);
// get all courses ( with update)
model.addAttribute("courses", this.courseRepository.findAll());
return "index";
}
#GetMapping("delete/{id}")
public String deleteCourse(#PathVariable ("id") long id, Model model) {
Course course = this.courseRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Invalid course id : " + id));
this.courseRepository.delete(course);
model.addAttribute("courses", this.courseRepository.findAll());
return "index";
}
}
CourseEntity
package net.springboot.javaguides.entity;
import java.sql.Date;
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 = "Courses")
public class Course {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "cours_name")
private String cours_name;
#Column(name = "date_debut")
private Date date_debut;
#Column(name = "date_fin")
private Date date_fin;
#Column(name = "enseignant")
private String enseignant;
#Column(name = "type_cours")
private String type_cours;
#Column(name = "filliere")
private String filliere;
public Course() {
super();
}
public Course(String cours_name, Date date_debut, Date date_fin, String enseignant, String type_cours,
String filliere) {
super();
this.cours_name = cours_name;
this.date_debut = date_debut;
this.date_fin = date_fin;
this.enseignant = enseignant;
this.type_cours = type_cours;
this.filliere = filliere;
}
public Long getId() {
return id;
}
public String getCours_name() {
return cours_name;
}
public void setCours_name(String cours_name) {
this.cours_name = cours_name;
}
public Date getDate_debut() {
return date_debut;
}
public void setDate_debut(Date date_debut) {
this.date_debut = date_debut;
}
public Date getDate_fin() {
return date_fin;
}
public void setDate_fin(Date date_fin) {
this.date_fin = date_fin;
}
public String getEnseignant() {
return enseignant;
}
public void setEnseignant(String enseignant) {
this.enseignant = enseignant;
}
public String getType_cours() {
return type_cours;
}
public void setType_cours(String type_cours) {
this.type_cours = type_cours;
}
public String getfilliere() {
return filliere;
}
public void setfilliere(String filliere) {
this.filliere = filliere;
}
public void setId(Long id) {
this.id = id;
}
}
**
CourseRepository
**
package net.springboot.javaguides.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import net.springboot.javaguides.entity.Course;
#Repository
public interface CourseRepository extends JpaRepository<Course, Long>{
List<Course> findByName(String cours_name);
}
but im having this error
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.0.RELEASE)
2020-08-27 13:44:03.876 INFO 9188 --- [ restartedMain] s.j.SpringbootThymeleafWebAppApplication : Starting SpringbootThymeleafWebAppApplication on DESKTOP-5D7IMCJ with PID 9188 (C:\Users\yassi\Desktop\workspacenew\springboot-thymeleaf-web-app-master\target\classes started by yassi in C:\Users\yassi\Desktop\workspacenew\springboot-thymeleaf-web-app-master)
2020-08-27 13:44:03.880 INFO 9188 --- [ restartedMain] s.j.SpringbootThymeleafWebAppApplication : No active profile set, falling back to default profiles: default
2020-08-27 13:44:03.941 INFO 9188 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2020-08-27 13:44:03.941 INFO 9188 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2020-08-27 13:44:04.881 INFO 9188 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2020-08-27 13:44:04.957 INFO 9188 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 68ms. Found 2 repository interfaces.
2020-08-27 13:44:05.415 INFO 9188 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$97fbb782] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-08-27 13:44:05.849 INFO 9188 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-08-27 13:44:05.868 INFO 9188 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-08-27 13:44:05.868 INFO 9188 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/9.0.12
2020-08-27 13:44:05.876 INFO 9188 --- [ restartedMain] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jre1.8.0_221\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_221/bin/server;C:/Program Files/Java/jre1.8.0_221/bin;C:/Program Files/Java/jre1.8.0_221/lib/amd64;C:\oraclexe\app\oracle\product\11.2.0\server\bin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\110\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\120\Tools\Binn\ManagementStudio\;C:\Program Files (x86)\Microsoft SQL Server\120\Tools\Binn\;C:\Program Files\Microsoft SQL Server\120\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\120\DTS\Binn\;C:\Program Files\Microsoft SQL Server\120\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\ManagementStudio\;C:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\;C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\PrivateAssemblies\;C:\Program Files (x86)\Microsoft SQL Server\110\DTS\Binn\;C:\Program Files\Git\cmd;C:\Program Files\nodejs\;C:\Program Files\MySQL\MySQL Server 5.1\bin;C:\Users\yassi\AppData\Local\Microsoft\WindowsApps;;C:\Users\yassi\AppData\Local\Programs\Microsoft VS Code\bin;D:\eclipse;;.]
2020-08-27 13:44:05.990 INFO 9188 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-08-27 13:44:05.990 INFO 9188 --- [ restartedMain] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2049 ms
2020-08-27 13:44:06.025 INFO 9188 --- [ restartedMain] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2020-08-27 13:44:06.031 INFO 9188 --- [ restartedMain] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2020-08-27 13:44:06.031 INFO 9188 --- [ restartedMain] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2020-08-27 13:44:06.031 INFO 9188 --- [ restartedMain] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'formContentFilter' to: [/*]
2020-08-27 13:44:06.031 INFO 9188 --- [ restartedMain] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2020-08-27 13:44:06.203 INFO 9188 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-08-27 13:44:06.332 INFO 9188 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-08-27 13:44:06.388 INFO 9188 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2020-08-27 13:44:06.630 INFO 9188 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate Core {5.3.7.Final}
2020-08-27 13:44:06.632 INFO 9188 --- [ restartedMain] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2020-08-27 13:44:06.776 INFO 9188 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2020-08-27 13:44:06.917 INFO 9188 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
2020-08-27 13:44:07.829 INFO 9188 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-08-27 13:44:07.871 INFO 9188 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2020-08-27 13:44:08.146 WARN 9188 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'courseController': Unsatisfied dependency expressed through field 'courseRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'courseRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List net.springboot.javaguides.repository.CourseRepository.findByName(java.lang.String)! No property name found for type Course!

The log says the problem already! .repository.CourseRepository.findByName(java.lang.String)! No property name found for type Course! Your Course entity doesn't have a property called name, it's called cours_name. Change the cours_name in your Course entity to name or change the name of the method in CourseRepository!

Try adding #EnableJpaRepositories(packages) on top of your main class.
i had an same issue, i handled with adding #EntityScan or #EnableJpaRepositories(packages)

Related

Post Request object data is passing as null in the controller class method parameter in Spring Boot

i am currently developing a backend API with help of Spring Boot Project.
The POST request which i am sending from postman to one of the resource method in Controller class. But all the data is showing as null
Entity class
public class SIM_Entity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String Sim_card_no;
private String Mobile_no;
private boolean status;
#Temporal(TemporalType.DATE)
private Date Expiry_date;
private boolean State_of_registration;
private String KYC;
private String Telecom_Provider;
private String Full_Name;
/**
* #param sim_card_no
* #param mobile_no
* #param status
* #param expiry_date
* #param state_of_registration
* #param kYC
* #param telecom_Provider
* #param full_Name
*/
public SIM_Entity(String sim_card_no, String mobile_no, boolean status, Date expiry_date,
boolean state_of_registration, String kYC, String telecom_Provider, String full_Name) {
super();
Sim_card_no = sim_card_no;
Mobile_no = mobile_no;
this.status = status;
Expiry_date = expiry_date;
State_of_registration = state_of_registration;
KYC = kYC;
Telecom_Provider = telecom_Provider;
Full_Name = full_Name;
}
/**
*
*/
public SIM_Entity() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getSim_card_no() {
return Sim_card_no;
}
public void setSim_card_no(String sim_card_no) {
Sim_card_no = sim_card_no;
}
public String getMobile_no() {
return Mobile_no;
}
public void setMobile_no(String mobile_no) {
Mobile_no = mobile_no;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public Date getExpiry_date() {
return Expiry_date;
}
public void setExpiry_date(Date expiry_date) {
Expiry_date = expiry_date;
}
public boolean isState_of_registration() {
return State_of_registration;
}
public void setState_of_registration(boolean state_of_registration) {
State_of_registration = state_of_registration;
}
public String getKYC() {
return KYC;
}
public void setKYC(String kYC) {
KYC = kYC;
}
public String getTelecom_Provider() {
return Telecom_Provider;
}
public void setTelecom_Provider(String telecom_Provider) {
Telecom_Provider = telecom_Provider;
}
public String getFull_Name() {
return Full_Name;
}
public void setFull_Name(String full_Name) {
Full_Name = full_Name;
}
#Override
public String toString() {
return "SIM_Entity [id=" + id + ", Sim_card_no=" + Sim_card_no + ", Mobile_no=" + Mobile_no + ", status="
+ status + ", Expiry_date=" + Expiry_date + ", State_of_registration=" + State_of_registration
+ ", KYC=" + KYC + ", Telecom_Provider=" + Telecom_Provider + ", Full_Name=" + Full_Name + "]";
}
}
Controller class
#RestController
#RequestMapping(value = "/")
public class SIMCardController {
#Autowired
private SIMCardService simCardService;
#GetMapping
public String SIMCardManagement_Message() {
return "Welcome to SIM Card Management Application Development";
}
#PostMapping(value = "/add", consumes = "application/json", produces = "application/json")
public ResponseEntity<SIM_Entity> saveSIM_Entity(#RequestBody SIM_Entity entity) {
System.out.println("The value of Entity coming from Client request :"+" "+entity.toString());
try {
SIM_Entity createSIMCardEntry = simCardService.createSIMCardEntry(entity);
return new ResponseEntity<>(createSIMCardEntry, HttpStatus.CREATED);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
#GetMapping(value = "/listall", consumes = "application/json", produces = "application/json")
public ResponseEntity<List<SIM_Entity>> getAllEntity() {
try {
List<SIM_Entity> allSimCardEntry = simCardService.getAllSimCardEntry();
return new ResponseEntity<List<SIM_Entity>>(allSimCardEntry, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.NO_CONTENT);
}
}
#PutMapping(value = "/{id}")
public ResponseEntity<SIM_Entity> updateSimCardInfo(#PathVariable("id") Long id, #RequestBody SIM_Entity entry) {
SIM_Entity updateSimEntryRecord = simCardService.updateSimEntryRecord(id, entry);
return new ResponseEntity<SIM_Entity>(updateSimEntryRecord, HttpStatus.OK);
}
#DeleteMapping("/{id}")
public ResponseEntity<HttpStatus> deleteSIMById(#PathVariable("id") Long id) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
Error Stack Trace
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.7.2)
2022-08-16 05:55:51.394 INFO 61555 --- [ restartedMain] c.t.SimCardReStBackEndApiApplication : Starting SimCardReStBackEndApiApplication using Java 11.0.12 on Bikashs-MacBook-Air.local with PID 61555 (/Users/bikashmohapatra/SpringRest_Workspace/SIM_Card_ReST_BackEnd_API/target/classes started by bikashmohapatra in /Users/bikashmohapatra/SpringRest_Workspace/SIM_Card_ReST_BackEnd_API)
2022-08-16 05:55:51.396 INFO 61555 --- [ restartedMain] c.t.SimCardReStBackEndApiApplication : No active profile set, falling back to 1 default profile: "default"
2022-08-16 05:55:51.444 INFO 61555 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2022-08-16 05:55:51.444 INFO 61555 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2022-08-16 05:55:52.360 INFO 61555 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-08-16 05:55:52.468 INFO 61555 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 86 ms. Found 1 JPA repository interfaces.
2022-08-16 05:55:53.181 INFO 61555 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-08-16 05:55:53.190 INFO 61555 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-08-16 05:55:53.191 INFO 61555 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.65]
2022-08-16 05:55:53.264 INFO 61555 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-08-16 05:55:53.264 INFO 61555 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1819 ms
2022-08-16 05:55:53.465 INFO 61555 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-08-16 05:55:53.495 INFO 61555 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.10.Final
2022-08-16 05:55:53.606 INFO 61555 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-08-16 05:55:53.673 INFO 61555 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-08-16 05:55:54.053 INFO 61555 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2022-08-16 05:55:54.064 INFO 61555 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
2022-08-16 05:55:54.562 INFO 61555 --- [ restartedMain] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-08-16 05:55:54.568 INFO 61555 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-08-16 05:55:54.931 WARN 61555 --- [ restartedMain] 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-08-16 05:55:55.240 INFO 61555 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2022-08-16 05:55:55.275 INFO 61555 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-08-16 05:55:55.287 INFO 61555 --- [ restartedMain] c.t.SimCardReStBackEndApiApplication : Started SimCardReStBackEndApiApplication in 4.384 seconds (JVM running for 5.5)
2022-08-16 05:57:24.474 INFO 61555 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-08-16 05:57:24.476 INFO 61555 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-08-16 05:57:24.493 INFO 61555 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 17 ms
The value of Entity coming from Client request : SIM_Entity [id=null, Sim_card_no=null, Mobile_no=null, status=true, Expiry_date=null, State_of_registration=false, KYC=null, Telecom_Provider=null, Full_Name=null]
2022-08-16 05:57:24.813 WARN 61555 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1048, SQLState: 23000
2022-08-16 05:57:24.813 ERROR 61555 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : Column 'mobile_no' cannot be null
2022-08-16 05:57:24.814 INFO 61555 --- [nio-8080-exec-1] o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements
how to resolve this issue?
I reproduced the bug and got the same problem. I was able to solve it.
Firstly as Andrew Thomas said you should follow the java naming convention (camelCase). Secondly, if you want to continue with the property names that you have declared take a look at your parameterized constructor . Whatever name you are accepting in that constructor and whatever name you are passing from the front-end should always match.
In your case, they don't match that's why those fields are not getting populated with the required data.
I would suggest you use a DTO class along with a library called Lombok which will take care of everything
For getters, setters and constructors you can use like this
#Entity
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
#ToString
public class SIM_Entity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String Sim_card_no;
private String Mobile_no;
private boolean status;
#Temporal(TemporalType.DATE)
private Date Expiry_date;
private boolean State_of_registration;
private String KYC;
private String Telecom_Provider;
private String Full_Name;
/**
* #param sim_card_no
* #param mobile_no
* #param status
* #param expiry_date
* #param state_of_registration
* #param kYC
* #param telecom_Provider
* #param full_Name
*/
public SIM_Entity(String sim_card_no, String mobile_no, boolean status, Date expiry_date,
boolean state_of_registration, String kYC, String telecom_Provider, String full_Name) {
super();
Sim_card_no = sim_card_no;
Mobile_no = mobile_no;
this.status = status;
Expiry_date = expiry_date;
State_of_registration = state_of_registration;
KYC = kYC;
Telecom_Provider = telecom_Provider;
Full_Name = full_Name;
}

Hibernate Envers - Field 'setordinal' doesn't have a default value from hibernate envers

When inserting the CheckList entity hibernate fails with the following error:
SQL Error: 1364, SQLState: HY000
Field 'setordinal' doesn't have a default value
My Entity structure is as follows:
I have a Embeddable class :
#Embeddable
public class RelateTo {
#Column(length = 100, nullable = false)
private String entityType;
#ElementCollection(fetch = FetchType.LAZY)
#MapKeyColumn(name="name", length = 100)
#Column(name="value", length = 500)
private Map<String, String> properties;
public String getEntityType() {
return entityType;
}
public void setEntityType(String entityType) {
this.entityType = entityType;
}
public Map<String, String> getProperties() {
if(properties == null) {
properties = new HashMap<>();
}
return properties;
}
public void setProperties(Map<String, String> properties) {
this.properties = properties;
}
}
And this class is used within CheckList class as follows:
#Entity
#Audited
public class CheckList {
#ElementCollection(fetch = FetchType.LAZY)
#Fetch(FetchMode.SELECT)
#BatchSize(size = 20)
#OrderColumn
private Set<CheckListItem> items;
#Embedded
private RelateTo relateTo;
public CheckList() {
}
public Set<CheckListItem> getItems() {
if (this.items == null) {
this.items = new HashSet<>();
}
return items;
}
public void setItems(Set<CheckListItem> items) {
this.items = items;
}
public RelateTo getRelateTo() {
return relateTo;
}
public void setRelateTo(RelateTo relateTo) {
this.relateTo = relateTo;
}
}
Hibernate generates audit table for CheckList with reference to RelateTo entity (which contains Map<String,String> called properties) as follows :
CREATE TABLE `check_list_properties_audit` (
`revision_id` int NOT NULL,
`revision_type` tinyint NOT NULL,
`check_list_id` varchar(36) NOT NULL,
`setordinal` int NOT NULL,
`name` varchar(64) NOT NULL,
`value` varchar(128) NOT NULL,
PRIMARY KEY (`revision_id`,`check_list_id`,`value`,`name`),
CONSTRAINT `FKmny3johxwt0i5sfkblq6unicx` FOREIGN KEY (`revision_id`) REFERENCES `revinfo` (`rev`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
Note that the table has a field called 'setordinal' but the field value is not populated during the insert. Here is the trace I got from insert call:
insert into check_list_properties_audit (revision_type, revision_id, check_list_id, value, name) values (?, ?, ?, ?, ?)
--- [ restartedMain] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [INTEGER] - [0]
--- [ restartedMain] o.h.type.descriptor.sql.BasicBinder : binding parameter [2] as [INTEGER] - [3]
--- [ restartedMain] o.h.type.descriptor.sql.BasicBinder : binding parameter [3] as [VARCHAR] - [f5fae3ff-c4f4-4466-8355-b52597b973fd]
--- [ restartedMain] o.h.type.descriptor.sql.BasicBinder : binding parameter [4] as [VARCHAR] - [Some name here]
--- [ restartedMain] o.h.type.descriptor.sql.BasicBinder : binding parameter [5] as [VARCHAR] - [taskName]
There are 6 fields to be inserted but the binding shows only 5 fields are populated. Thus the insert fails.
How can I get rid of this problem. The only option I've right now is to makr it #NotAudited, which I don't want to do.

I can't to see my web page in spring [spring]

I'm new using this framework, I'm tryng to deploy a web with a hibernate connection, I created a .xml config file to connect to PostgreSQL.
But the logs shows this error:
2020-11-14T22:32:28.610246+00:00 heroku[router]: at=info method=GET path="/"
host=gstlabs.herokuapp.com request_id=978ecfdc-917f-41a0-8867-8cc55b73def1 fwd="190.84.149.124" dyno=web.1 connect=2ms service=211ms status=500 bytes=610 protocol=https
2020-11-14T23:04:34.213061+00:00 heroku[web.1]: Idling
2020-11-14T23:04:34.215664+00:00 heroku[web.1]: State changed from up to down
2020-11-14T23:04:35.167671+00:00 heroku[web.1]: Stopping all processes with SIGTERM
2020-11-14T23:04:35.279279+00:00 app[web.1]: 2020-11-14 23:04:35.278 INFO 4 --- [extShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-11-14T23:04:35.279712+00:00 app[web.1]: 2020-11-14 23:04:35.279 WARN 4 --- [extShutdownHook] o.s.b.f.support.DisposableBeanAdapter : Invocation of destroy method failed on bean with name 'entityManagerFactory': org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.example.core.models.Projects.technologies in com.example.core.models.Technologies.projects
2020-11-14T23:04:35.280073+00:00 app[web.1]: 2020-11-14 23:04:35.279 INFO 4 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2020-11-14T23:04:35.282600+00:00 app[web.1]: 2020-11-14 23:04:35.282 INFO 4 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2020-11-14T23:04:35.325392+00:00 app[web.1]: 2020-11-14 23:04:35.325 INFO 4 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
2020-11-14T23:04:35.426750+00:00 heroku[web.1]: Process exited with status 143
There are my Classes:
[Technologies]
package com.example.core.models;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
#Entity
#Table(name="technologies")
public class Technologies {
#Id
#Column(name="id")
private int id;
#Column(name="name")
private String name;
public Technologies() {
}
public Technologies(String name) {
this.name = 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;
}
#Override
public String toString() {
return "Technologies [id=" + id + ", name=" + name + "]";
}
#ManyToMany(mappedBy="technologies")
private Set<Projects> projects = new HashSet<>();
public Set<Projects> getProjects() {
return projects;
}
public void setProjects(Set<Projects> projects) {
this.projects = projects;
}
}
[Projects]
package com.example.core.models;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
#Entity
#Table(name="projects")
public class Projects {
#Id
#Column(name="id")
private int id;
#Column(name="photo")
private String photo;
#Column(name="link")
private String link;
public Projects() {
}
public Projects(String photo, String link) {
this.photo = photo;
this.link = link;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
#Override
public String toString() {
return "Projects [id=" + id + ", photo=" + photo + ", link=" + link + "]";
}
#ManyToMany(cascade= {CascadeType.ALL})
#JoinTable(
name="projects_has_technologies",
joinColumns=#JoinColumn(name="project_id"),
inverseJoinColumns=#JoinColumn(name="technology_id")
)
Set<Technologies> tecnologies = new HashSet<>();
#ManyToMany(mappedBy="projects")
private Set<Profiles> profiles = new HashSet<>();
public Set<Technologies> getTecnologies() {
return tecnologies;
}
public void setTecnologies(Set<Technologies> tecnologies) {
this.tecnologies = tecnologies;
}
public Set<Profiles> getProfiles() {
return profiles;
}
public void setProfiles(Set<Profiles> profiles) {
this.profiles = profiles;
}
}
There are some code that are some at my clases in this proyect the other intermedial clases are similar, I'm trynt in this moment insert some objects to the database.
Thanks to your help in advance.
Have you tried to add a Configuration Class in your project for example
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories( basePackages = "your repository package" )
#EntityScan( basePackages = {"your entity package1","your entity package2"}
public class TransactionConfiguration {}
This will help you to find your entity classes in the project.

WebFlux functional endpoint, how to return a ServerResponse with retrieved data and no unnecessary block/wait?

I am totally new to reactive code and after a number of tutorials and youtube videos I am trying to setup a tiny test application using functional endpoints; a simple RouterFunction, RouterHandler and Repository. The problem is how to return an object in the ServerResponse from the respository to the caller, without causing any unnecessary blocking?
I am using Postman for testing. Here's the interesting parts of my test application:
#Configuration
public class BookRouter {
#Autowired
BookRepositoryImpl bookRepository;
#Bean
public RouterFunction<ServerResponse> bookRoutes() {
BookHandler bookHandler = new BookHandler(bookRepository);
return RouterFunctions
.nest(path("/api/books"),
route(GET("/{group}/{name}").and(accept(ALL)), bookHandler::getBook)
);
}
}
#Repository
public class BookRepositoryImpl implements BookRepository {
private final ReactiveMongoTemplate mongoTemplate;
#Autowired
public BookRepositoryImpl(ReactiveMongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}
#Override
public Mono<Book> findByName(String group, String name) {
Query query = new Query(Criteria.where("group").is(group).and("name").is(name));
return mongoTemplate.findOne(query, Book.class);
}
}
public class BookHandler {
public Mono<ServerResponse> getBook(ServerRequest request) {
String group = request.pathVariable("group");
String name = request.pathVariable("name");
bookRepository
.findByName(group, name)
.subscribe(
ok -> System.out.println("findByName " + ok),
error -> System.err.println("Error: " + error));
return ServerResponse
.accepted()
.contentType(MediaType.TEXT_PLAIN)
.bodyValue("Request queued");
}
}
When I have the code as shown above, the expected data is printed out in subscribe(ok -> ...), but I haven't figured out how to return this data in the ServerResponse.
If I change the code in getBook() to
return setting
.flatMap(s -> ServerResponse
.ok()
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(s))
.switchIfEmpty(NOT_FOUND);
the returned bodyValue is empty, although I can see that it was retrieved from the database.
Any advice on what I am missing is most appreciated.
Update
I am using MongoDB Compass to view and verify the content of the database.
Debug logging is enabled in application.properties with logging.level.root=DEBUGso the Spring classes write some info in the terminal window. Parts of the somewhat anonymized log is as follows:
2020-09-05 21:37:02.688 DEBUG 32720 --- [ctor-http-nio-3] o.s.w.r.f.s.s.RouterFunctionMapping : [96ef6152-1] Mapped to com.sample.book.BookRouter$$Lambda$586/0x0000000800540040#3b0bf8e0
2020-09-05 21:37:02.717 DEBUG 32720 --- [ctor-http-nio-3] o.s.d.m.core.ReactiveMongoTemplate : findOne using query: { "group" : "Thriller", "name" : "The Shining"} fields: Document{{}} for class: class com.sample.book.Book in collection: book
2020-09-05 21:37:02.734 DEBUG 32720 --- [ctor-http-nio-3] o.s.d.m.core.ReactiveMongoTemplate : findOne using query: { "group" : "Thriller", "name" : "The Shining"} fields: {} in db.collection: book.book
2020-09-05 21:37:02.751 DEBUG 32720 --- [ctor-http-nio-3] org.mongodb.driver.protocol.command : Sending command '{"find": "book", "filter": {"group": "Thriller", "name": "The Shining"}, "limit": 1, "singleBatch": true, "$db": "book"}' with request id 7 to database book on connection [connectionId{localValue:2, serverValue:217}] to server localhost:27017
2020-09-05 21:37:02.766 DEBUG 32720 --- [ntLoopGroup-3-2] org.mongodb.driver.protocol.command : Execution of command with request id 7 completed successfully in 16.24 ms on connection [connectionId{localValue:2, serverValue:217}] to server localhost:27017
2020-09-05 21:37:02.837 DEBUG 32720 --- [ntLoopGroup-3-2] o.s.http.codec.json.Jackson2JsonEncoder : [96ef6152-1] Encoding [_id=5f53692af0a02d3af8a7fed9, group=Thriller, name=The Shining, value=in]]
2020-09-05 21:37:02.853 DEBUG 32720 --- [ctor-http-nio-3] r.n.http.server.HttpServerOperations : [id: 0x96ef6152, L:/0:0:0:0:0:0:0:1:8088 - R:/0:0:0:0:0:0:0:1:50248] Decreasing pending responses, now 0
2020-09-05 21:37:02.879 DEBUG 32720 --- [ctor-http-nio-3] o.s.w.s.adapter.HttpWebHandlerAdapter : [96ef6152-1] Completed 200 OK
2020-09-05 21:37:02.905 DEBUG 32720 --- [ctor-http-nio-3] r.n.http.server.HttpServerOperations : [id: 0x96ef6152, L:/0:0:0:0:0:0:0:1:8088 - R:/0:0:0:0:0:0:0:1:50248] Last HTTP response frame
2020-09-05 21:37:02.931 DEBUG 32720 --- [ctor-http-nio-3] r.n.http.server.HttpServerOperations : [id: 0x96ef6152, L:/0:0:0:0:0:0:0:1:8088 - R:/0:0:0:0:0:0:0:1:50248] Last HTTP packet was sent, terminating the channel
I found the problem. I had forgot to implement getters in the Book class holding the #Document. I am surprised that there were no error message or warning when they were missing.
As soon as I inserted them, the result was returned as expected from this code:
return setting
.flatMap(s -> ServerResponse
.ok()
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(s))
.switchIfEmpty(NOT_FOUND);
Here is the data as returned to Postman after the fix:
{
"_id": "5f53692af0a02d3af8a7fed9",
"group": "Thrillers",
"name": "The Shining",
"value": "in"
}
Thank you to #caco3 for helping me find the problem!
Here is my updated Book.java.
#Document
#CompoundIndex(name = "group-name", def = "{'group':1, 'name':1}", unique = true) // Requires auto-index-creation in application.properties
public class Book {
#Id
private String _id;
private String group;
private String name;
private String value;
public Book() {
}
public Book(String group, String name, String value) {
this.group = group;
this.name = name;
this.value = value;
}
#Override
public String toString() {
StringBuilder s = new StringBuilder('[');
s.append("_id=").append(_id);
s.append(", group=").append(group);
s.append(", name=").append(name);
s.append(", value=").append(value);
s.append(']');
return s.toString();
}
public String get_id() {
return _id;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}

Spring back end localhost requires login

I'm trying to develop a cross-platform application, with Cordova in the front-end and using Spring in the back_end.
Basically, I started by the link between the database and generating the classes (models). Here's my application properties:
# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = updateUnable to find column with logical name: program_id
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
# Server
server.port=8080
endpoints.cors.allowed-origins=*
I wanted to try if I'm getting the list in JSON form before I go to the backend. So I made an example to get the list of operators, the class Operator is declared like that:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.rest.model;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
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.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* #author gate11
*/
#Entity
#Table(catalog = "db_suivi", schema = "")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Operator.findAll", query = "SELECT o FROM Operator o")
, #NamedQuery(name = "Operator.findById", query = "SELECT o FROM Operator o WHERE o.id = :id")
, #NamedQuery(name = "Operator.findByOperatorFName", query = "SELECT o FROM Operator o WHERE o.operatorFName = :operatorFName")
, #NamedQuery(name = "Operator.findByOperatorLName", query = "SELECT o FROM Operator o WHERE o.operatorLName = :operatorLName")})
public class Operator implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
private Long id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
private String operatorFName;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
private String operatorLName;
#JoinTable(name = "BadgeOperator", joinColumns = {
#JoinColumn(name = "idOp", referencedColumnName = "id")}, inverseJoinColumns = {
#JoinColumn(name = "idBad", referencedColumnName = "id")})
#ManyToMany(fetch = FetchType.LAZY)
private List<BadgePoint> badgePointList;
#ManyToMany(mappedBy = "operatorList", fetch = FetchType.LAZY)
private List<Zone> zoneList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "operator", fetch = FetchType.LAZY)
private List<TimePass> timePassList;
public Operator() {
}
public Operator(Long id) {
this.id = id;
}
public Operator(Long id, String operatorFName, String operatorLName) {
this.id = id;
this.operatorFName = operatorFName;
this.operatorLName = operatorLName;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getOperatorFName() {
return operatorFName;
}
public void setOperatorFName(String operatorFName) {
this.operatorFName = operatorFName;
}
public String getOperatorLName() {
return operatorLName;
}
public void setOperatorLName(String operatorLName) {
this.operatorLName = operatorLName;
}
#XmlTransient
public List<BadgePoint> getBadgePointList() {
return badgePointList;
}
public void setBadgePointList(List<BadgePoint> badgePointList) {
this.badgePointList = badgePointList;
}
#XmlTransient
public List<Zone> getZoneList() {
return zoneList;
}
public void setZoneList(List<Zone> zoneList) {
this.zoneList = zoneList;
}
#XmlTransient
public List<TimePass> getTimePassList() {
return timePassList;
}
public void setTimePassList(List<TimePass> timePassList) {
this.timePassList = timePassList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Operator)) {
return false;
}
Operator other = (Operator) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.rest.Operator[ id=" + id + " ]";
}
}
I added an interface (repository) implementing JpaRepository:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.rest.repository;
import com.rest.model.Operator;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
/**
*
* #author gate11
*/
public interface OperatorRepository extends JpaRepository<Operator, Long>{
#Override
List<Operator> findAll();
}
And as needed, also a controller for the class Operator:
package com.rest.rest;
import com.rest.model.Operator;
import com.rest.service.OperatorService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping(value = "/api", produces = MediaType.APPLICATION_JSON_VALUE)
public class OperatorController {
#Autowired
private OperatorService operatorService;
#CrossOrigin
#RequestMapping(method = GET, value = "/operator/all")
public List<Operator> loadAll() {
return this.operatorService.findAll();
}
}
The interface service:
package com.rest.service;
import com.rest.model.Operator;
import java.util.List;
/**
*
* #author gate11
*/
public interface OperatorService {
List<Operator> findAll();
}
The service Implement also:
package com.rest.serviceImp;
import com.rest.model.Operator;
import com.rest.repository.OperatorRepository;
import com.rest.service.OperatorService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
*
* #author gate11
*/
#Service
public class OperatorServiceImp implements OperatorService{
#Autowired
private OperatorRepository operatorRepository;
#Override
public List<Operator> findAll() {
List<Operator> operator = operatorRepository.findAll();
return operator;
}
}
When I launch the application, the log:
2018-03-05 14:34:47.427 INFO 10768 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/css/**'], Ant [pattern='/js/**'], Ant [pattern='/images/**'], Ant [pattern='/webjars/**'], Ant [pattern='/**/favicon.ico'], Ant [pattern='/error']]], []
2018-03-05 14:34:47.565 INFO 10768 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: Ant [pattern='/h2-console/**'], [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#183bb809, org.springframework.security.web.context.SecurityContextPersistenceFilter#593fdbbe, org.springframework.security.web.header.HeaderWriterFilter#2d784ff4, org.springframework.security.web.authentication.logout.LogoutFilter#55ef8d65, org.springframework.security.web.authentication.www.BasicAuthenticationFilter#3ba7a547, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#12e1efcb, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#57449117, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#5cba96fc, org.springframework.security.web.session.SessionManagementFilter#5403d62a, org.springframework.security.web.access.ExceptionTranslationFilter#4817a878, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#36126980]
2018-03-05 14:34:47.573 INFO 10768 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/**']]], [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#70c855ab, org.springframework.security.web.context.SecurityContextPersistenceFilter#1eef0aa6, org.springframework.security.web.header.HeaderWriterFilter#537d0675, org.springframework.security.web.authentication.logout.LogoutFilter#7d1011c1, org.springframework.security.web.authentication.www.BasicAuthenticationFilter#1b4c8eff, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#73c2d36e, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#48372dcd, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#3cfcbfa3, org.springframework.security.web.session.SessionManagementFilter#4befcfad, org.springframework.security.web.access.ExceptionTranslationFilter#4ed4729f, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#dffb1e0]
2018-03-05 14:34:47.807 INFO 10768 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2018-03-05 14:34:47.900 INFO 10768 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-03-05 14:34:48.000 INFO 10768 --- [ restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2018-03-05 14:34:48.008 INFO 10768 --- [ restartedMain] com.rest.Application : Started Application in 10.365 seconds (JVM running for 11.067)
2018-03-05 14:42:28.257 INFO 10768 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-03-05 14:42:28.257 INFO 10768 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2018-03-05 14:42:28.279 INFO 10768 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 21 ms
Then, I should go to localhost:8080/api/operator/all to get the list of operator as I used to do, but it's asking me to use a username password, I tried everything from db user (root, root) but doesn't work.
I don't even have a connexion page in the application.
enter image description here
If you have any idea, please feel free to suggest, I'm using a Mac as you see.
Thanks.

Resources