i have two tables first one is Filiere and the second is Cycle, related by a one to many relationship,which a Filiere can have a Cycle and Cycle can have multiple Filiere,and i want to display infos about all the filieres including Cycle name in a table using thymeleaf
package org.pfe.entities;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
#Entity
public class Cycle implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(unique=true,nullable = false)
private String nom;
#OneToMany(mappedBy="cyc")
private Set<Filiere> filList=new HashSet<>();
public Cycle() {
super();
}
public Cycle(String nom, Set<Filiere> filList) {
super();
this.nom = nom;
this.filList = filList;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public Set<Filiere> getFilList() {
return filList;
}
public void setFilList(Set<Filiere> filList) {
this.filList = filList;
}
public Long getId() {
return id;
}
}
package org.pfe.entities;
import java.util.Date;
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.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import org.springframework.format.annotation.DateTimeFormat;
#Entity
public class Filiere {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotBlank(message = "ne doit pas etre null" )
#NotNull
private String nom;
#Temporal(TemporalType.DATE)
#DateTimeFormat(pattern = "yyyy-MM-dd")
#NotNull(message = "la date ne doit pas etre null")
private Date dateCreation;
#ManyToOne
#JoinColumn(name="dept_id")
private Departement dept;
#ManyToOne
#JoinColumn(name="cycle_id")
private Cycle cyc;
}
Can you plz help me as soon as possible
you put the cycle object to the model.
For Example:
model.addAttribute("cycleList", listOfCycle);
In thymeleaf
<tr th:each="cycle:${cycleList}">
<td th:text="${cycle.id}"></td>
<td th:text="${cycle.nom}"></td>
<td>
<div th:each="filList:${cycle.filList}">
<p th:text="${filList.id}"></p>
<p th:text="${filList.nom}"></p>
<p th:text="${filList.dateCreation}"></p>
</div>
</td>
</tr>
This is how you can get the data in thymeleaf.
I am trying to implement ONE-TO-MANY Mapping in REST but getting null reference of USERDETAILS table in Companies table.
Also added the commented part, when I was using the commented part I was getting expected output while fetching the data through getAllUsers(). But it was creating one extra column don't know how to deal with the same.
Below are the Model classes :
USERDETAILS : :
package com.restapi.user.entity;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
#Entity
#Table(name = "USER_DETAIL_INFORMATION")
#Data
#AllArgsConstructor
#NoArgsConstructor
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = {"createdDate","modifyDate"},allowGetters = true)
public class UserDetails {
#Id
#Column(name = "user_id")
#GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "user_id_sequence")
#SequenceGenerator(name = "user_id_sequence",sequenceName = "user_Detail_information_Seq")
#JsonProperty(value ="id" )
private Long userId;
#JsonProperty("name")
#Column(name = "user_name")
private String userName;
#JsonProperty("email")
#Column(name = "user_email")
private String userEmail;
#JsonProperty("address")
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "user_address_id")
#JsonManagedReference
private Address userAddress;
#Column(name ="user_creation_date")
#Temporal(TemporalType.DATE)
#CreatedDate
#JsonProperty("createdDate")
private Date userCreationDate;
#LastModifiedDate
#Temporal(TemporalType.DATE)
#JsonProperty("modifyDate")
#Column(name = "user_modification_date")
private Date modifyDate;
#JsonProperty("companies")
#OneToMany(mappedBy = "userDetailsid",cascade = CascadeType.ALL,fetch = FetchType.EAGER)
private List<Companies> companies;
/*#JsonProperty("companies")
#OneToMany(cascade = CascadeType.ALL)
//, mappedBy = "userDetailsid"
#JoinColumn
private List<Companies> companies;
*/
}
Address : :
package com.restapi.user.entity;
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.SequenceGenerator;
import javax.persistence.Table;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
#Data
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name = "Address_Details")
public class Address {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "address_seq")
#SequenceGenerator(name = "address_seq",sequenceName = "Address_detail_seq")
#Column(name = "ad_id")
private Long addressId;
#JsonProperty(value = "city")
#Column(name = "ad_city")
private String city;
#JsonProperty(value = "state")
#Column(name = "ad_state")
private String state;
#OneToOne(mappedBy ="userAddress")
#JsonBackReference
private UserDetails userDetails;
}
COMPANIES : :
package com.restapi.user.entity;
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.SequenceGenerator;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonProperty;
#Entity
#Table(name = "COMPANY_INFO_DETAILS")
public class Companies {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "company_seq")
#SequenceGenerator(name = "company_seq",sequenceName = "Compamy_seq_generator")
private Long companyId;
#JsonProperty("c_code")
#Column(name = "c_code")
private String companyCode;
#JsonProperty("c_name")
#Column(name = "c_name")
private String companyName;
#ManyToOne
#JoinColumn(name = "COMAPNY_user_id")
private UserDetails userDetailsid;
/* #ManyToOne(cascade = CascadeType.ALL)
private UserDetails userDetailsid; */
public Companies() {
super();
// TODO Auto-generated constructor stub
}
public Companies(Long companyId, String companyCode, String companyName, UserDetails userDetails) {
super();
this.companyId = companyId;
this.companyCode = companyCode;
this.companyName = companyName;
this.userDetailsid = userDetails;
}
public Long getCompanyId() {
return companyId;
}
public void setCompanyId(Long companyId) {
this.companyId = companyId;
}
public String getCompanyCode() {
return companyCode;
}
public void setCompanyCode(String companyCode) {
this.companyCode = companyCode;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public UserDetails getUserDetails() {
return userDetailsid;
}
public void setUserDetails(UserDetails userDetails) {
System.out.println("user DETAILD"+userDetails.toString());
this.userDetailsid = userDetails;
}
}
Controller
package com.restapi.user.controller;
import java.util.List;
import java.util.Optional;
import javax.management.loading.PrivateClassLoader;
import javax.websocket.server.PathParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.restapi.user.entity.UserDetails;
import com.restapi.user.exceptionHandling.DataInsertionException;
import com.restapi.user.exceptionHandling.DataNotFoundException;
import com.restapi.user.helper.HelperMethods;
import com.restapi.user.service.UserService;
#RestController
#RequestMapping("/api/user")
public class UserController {
#Autowired
private UserService userService;
#Autowired
private HelperMethods helper;
/***
* This API will save the user Details in the database table.
*
* #return
*/
#PostMapping("/addnewUser")
public ResponseEntity<UserDetails> addNewUser(#RequestBody UserDetails userDetails) {
try {
if (helper.isNullEmpty(userDetails.getUserName())) {
throw new DataInsertionException("UserName is missing from the request- it is a mandatory parameter!!");
} else if (userDetails.getUserAddress()==null) {
throw new DataInsertionException(
"UserAddress is missing from the request- it is a mandatory parameter!!");
} else if (helper.isNullEmpty(userDetails.getUserEmail())) {
throw new DataInsertionException(
"User's Email address is missing from the request- it is a mandatory parameter!!");
} else {
UserDetails details = userService.saveUserDetails(userDetails);
return ResponseEntity.status(HttpStatus.CREATED).body(details);
}
} catch (Exception e) {
throw new DataInsertionException(e.getMessage());
}
}
/***
* This API will fetch the list of users available
*
* #return
* #throws Exception
*/
#GetMapping("/getAllUserDetails")
public ResponseEntity<List<UserDetails>> getListOfUsers() throws Exception {
try {
List<UserDetails> userDetails = userService.getAllUsers();
System.out.println(userDetails.size());
if (userDetails.size() < 1) {
throw new DataNotFoundException("No Data FOUND!!");
} else {
return new ResponseEntity<List<UserDetails>>(userDetails, HttpStatus.OK);
}
} catch (Exception e) {
throw new DataNotFoundException(e.getMessage());
}
}
/***
* This API will fetch the user Details by using the ID
*
* #return
* #throws Exception
*/
#GetMapping("/id/{id}")
public ResponseEntity<UserDetails> getUserById(#PathParam("id") Long id) throws Exception {
try {
Optional<UserDetails> userDetails = userService.getUserById(id);
if (!userDetails.isPresent()) {
throw new DataNotFoundException("No Data FOUND!!");
} else {
return new ResponseEntity<UserDetails>(userDetails.get(), HttpStatus.OK);
}
} catch (Exception e) {
throw new DataNotFoundException(e.getMessage());
}
}
}
REQUEST STRUCTURE ::
{
"name": "test_NAME",
"email": "abc#gmail",
"address": {
"city": "abc",
"state": "JK"
},
"companies": [
{
"c_code": "TCS",
"c_name": "TATA"
},
{
"c_code": "CTS",
"c_name": "COGNI"
}
]
}
RESPONSE_BODY ::
{
"id": 3,
"name": "test_NAME",
"email": "abc#gmail",
"address": {
"addressId": 3,
"city": "abc",
"state": "JK"
},
"createdDate": "2021-05-14T20:13:32.154+00:00",
"modifyDate": "2021-05-14T20:13:32.154+00:00",
"companies": [
{
"companyId": 5,
"userDetails": **null**,
"c_code": "TCS",
"c_name": "TATA"
},
{
"companyId": 6,
"userDetails": **null**,
"c_code": "CTS",
"c_name": "COGNI"
}
]
}
SERVICE CLASS :
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.restapi.user.entity.UserDetails;
import com.restapi.user.repository.UserRepository;
#Service
public class UserService {
#Autowired
private UserRepository repository;
public UserDetails saveUserDetails(UserDetails userDetails) {
return repository.save(userDetails);
}
public List<UserDetails> getAllUsers() {
return repository.findAll();
}
public Optional<UserDetails> getUserById(Long id) {
Optional<UserDetails> user = repository.findById(id);
return user;
}
}
Repository
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.restapi.user.entity.UserDetails;
#Repository
public interface UserRepository extends JpaRepository<UserDetails, Long>{
}
GetRequest result After Commented part
{
"id": 1,
"name": "test_NAME",
"email": "abc#gmail",
"address": {
"addressId": 1,
"city": "abc",
"state": "JK"
},
"createdDate": "2021-05-15",
"modifyDate": "2021-05-15",
"companies": [
{
"companyId": 2,
"userDetails": null,
"c_code": "CTS",
"c_name": "COGNI"
},
{
"companyId": 1,
"userDetails": null,
"c_code": "TCS",
"c_name": "TATA"
}
]
}
]
If not using Commented part
{
"id": 1,
"name": "test_NAME",
"email": "abc#gmail",
"address": {
"addressId": 1,
"city": "abc",
"state": "JK"
},
"createdDate": "2021-05-15",
"modifyDate": "2021-05-15",
"companies": []
}
]
When using Commented part :
When not using commented part :
Expected output should be :
Someone please highlight what I am missing or doing wrong ? Thanks in advance
Thanks for sharing the UserService. Based from your code in saving user details:
public UserDetails saveUserDetails(UserDetails userDetails) {
return repository.save(userDetails);
}
You are not defining any reference between a user and his/her companies. Again, the cascade you did on the UserDetails object will only means that (since you use CascadeType.ALL) once you save the UserDetails object the save operation will also be cascaded to the Company object however, JPA still needs to know the references between these objects, thus you have to set the userDetailsid for each Company object (during construction). Update your service to something like this:
public UserDetails saveUserDetails(UserDetails userDetails) {
userDetails.getCompanies().stream().forEach(company -> company.setUserDetailsid(userDetails));
return repository.save(userDetails);
}
Note: Just remove your commented codes. They would not work anyways without the update of your service as above.
Lastly, I am seeing you are using Lombok here, so why not use it all through out of your classes to remove boilerplates and update the company something like below. I have put #JsonBackReference to avoid infinite recursion of jackson on your response during add new user and create a getter method getUserReferenceId just for you to see the response of company with a reference userId.
#Entity
#Table(name = "COMPANY_INFO_DETAILS")
#Data
#AllArgsConstructor
#NoArgsConstructor
public class Companies {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "company_seq")
#SequenceGenerator(name = "company_seq", sequenceName = "Compamy_seq_generator")
private Long companyId;
#JsonProperty("c_code")
#Column(name = "c_code")
private String companyCode;
#JsonProperty("c_name")
#Column(name = "c_name")
private String companyName;
#ManyToOne
#JsonBackReference
#JoinColumn(name = "COMAPNY_user_id")
private UserDetails userDetailsid;
public Long getUserReferenceId() {
return userDetailsid != null ? userDetailsid.getUserId() : null;
}
}
I create tour and travel app using xspringboot and Hibernate jpa.in
that application i have two entity class one is turist and other is
vechileTtype.I want to map vechiletype entity with turist entity. I
use xaamp server for my sql database. but when i mapped these two
entity and run the application i get this type of error
Repeated column in mapping for entity: com.main.ToursTravels.model.VechileType column: name (should be mapped with insert="false" update="false")
Turist.java
package com.main.ToursTravels.model;
import java.math.BigDecimal;
import java.util.Date;
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.OneToOne;
import javax.persistence.Table;
import lombok.Data;
#Entity
#Table(name="turist")
#Data
public class Turist {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="truist_id")
private Long truistid;
#Column(name="turistname")
private String turistname;
#Column(name="travel_km")
private int travelkm;
#Column(name="travel_date")
private Date traveldate;
#Column(name="drivername")
private String drivername;
#OneToOne(fetch=FetchType.LAZY,cascade=CascadeType.ALL)
#JoinColumn(name="booking_id")
private VechileType vechiletype;
#Column(name="vechileno")
private String vechileno;
#Column(name="total_amount")
private BigDecimal totalamount;
#Column(name="BOOKING_status")
private boolean bookingstatus;
}
VechileType.java
package com.main.ToursTravels.model;
import java.math.BigDecimal;
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.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import lombok.Data;
#Entity
#Table(name="vechiletype")
#Data
public class VechileType {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="booking_id")
private Long bookingid;
#OneToOne(fetch=FetchType.LAZY,cascade=CascadeType.ALL,mappedBy="vechiletype")
private Turist turist;
#Column(name="name")
private boolean mini;
#Column(name="name")
private boolean sedan;
#Column(name="name")
private boolean suv;
#Column(name="name_per_km")
private int rateperkm;
private BigDecimal minprice;
}
application.properties
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/groserystore?useSSL=false & serveTimezone= UTC & useLegacyDateTimeCode=false
spring.datasource.username=root
spring.datasource.password=
#use of jpa
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.JPA.hibernate.ddl.auto=update
You are mapping 3 different properties to the same column name:
#Column(name="name")
private boolean mini;
#Column(name="name")
private boolean sedan;
#Column(name="name")
private boolean suv;
Use different names instead:
#Column(name="mini")
private boolean mini;
#Column(name="sedan")
private boolean sedan;
#Column(name="suv")
private boolean suv;
A better, more extensible alternative could be to use an enum:
public enum VehicleKind {
MINI, SEDAN, SUV
}
And in VechileType
#Entity
#Table(name="vechiletype")
#Data
public class VechileType {
#Enumerated(EnumType.STRING)
private VehicleKind kind;
I have a model class which is used in post(create) and put(update) rest API
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.Setter;
#Getter
#Setter
#NoArgsConstructor
#Entity(name= "employee")
public class employeeDetail {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long employeeId;
#NonNull
private String employeeName;
}
So since employee id to be nullable on add, while it has to be passed when update operation. What is the best to implement?
Note: In this case employee id is a primary key, the same situation is possible for non-primary key fields as well. I use Spring boot, Spring data JPA and hibernate. Database is mariadb.
Something like this:
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.transaction.Transactional;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Optional;
#Getter
#Setter
#NoArgsConstructor
#Entity(name = "employee")
class EmployeeDetail {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long employeeId; //Long is better!
#NotNull
private String employeeName;
// Needed just for conversion -> use some mapper, and remove this constructor
public EmployeeDetail(EmployeeDetailDTO employeeDetailDTO) {
this.employeeId = employeeDetailDTO.getEmployeeId();
this.employeeName = employeeDetailDTO.getEmployeeName();
}
}
interface EmployeeDetailRepo extends JpaRepository<EmployeeDetail, Long> {
}
#Data
#JsonInclude(JsonInclude.Include.NON_NULL)
class EmployeeDetailDTO {
private Long employeeId;
#NotNull
private String employeeName;
// Other fields
// Needed just for conversion -> use some mapper, and remove this constructor
public EmployeeDetailDTO(EmployeeDetail employeeDetail) {
this.employeeId = employeeDetail.getEmployeeId();
this.employeeName = employeeDetail.getEmployeeName();
}
}
#Service
class EmpDetailService {
private EmployeeDetailRepo employeeDetailRepo;
#Autowired
public EmpDetailService(EmployeeDetailRepo employeeDetailRepo) {
this.employeeDetailRepo = employeeDetailRepo;
}
public EmployeeDetailDTO add(EmployeeDetailDTO employeeDetailDTO) {
// map EmployeeDetailDTO to EmployeeDetail
EmployeeDetail employeeDetail = new EmployeeDetail(employeeDetailDTO);
EmployeeDetail employeeDetail1FromDB = employeeDetailRepo.save(employeeDetail);
// map back to dto
return new EmployeeDetailDTO(employeeDetail1FromDB);
}
#Transactional
public EmployeeDetailDTO edit(Long id, EmployeeDetailDTO employeeDetailDTO) {
// map EmployeeDetailDTO to EmployeeDetail
Optional<EmployeeDetail> byId = employeeDetailRepo.findById(id);
EmployeeDetail employeeDetailFromDB = byId.orElseThrow(() -> new RuntimeException("No such user with id: " + id));
employeeDetailFromDB.setEmployeeName(employeeDetailDTO.getEmployeeName());
return new EmployeeDetailDTO(employeeDetailFromDB);
}
}
#RequestMapping
class Controller {
private EmpDetailService empDetailService;
#Autowired
Controller(EmpDetailService empDetailService) {
this.empDetailService = empDetailService;
}
#PostMapping("/add")
public ResponseEntity<EmployeeDetailDTO> add(#Valid #RequestBody EmployeeDetailDTO employeeDetailDTO) {
EmployeeDetailDTO added = empDetailService.add(employeeDetailDTO);
return new ResponseEntity<>(added, HttpStatus.OK);
}
#PostMapping("/edit/{id}")
public ResponseEntity<EmployeeDetailDTO> edit(#PathVariable Long id,
#Valid #RequestBody EmployeeDetailDTO employeeDetailDTO) {
EmployeeDetailDTO edited= empDetailService.edit(id, employeeDetailDTO);
return new ResponseEntity<>(edited, HttpStatus.OK);
}
}
Since you expect Hibernate to generate yuor id on insert it should be nullable, so its type.
Just change employeeId to Integer.
From a design point of view, consider to create 2 different business domain classes, one for insert with no id and one for update/select with non nullable id.
public class EmployeeRegistration {
#NonNull
private String name;
}
public class EmployeeDetail {
#NonNull
private Integer employeeId;
#NonNull
private String name;
}
Then provade methods to transform them to database entities.
I've an entity class User_Details
package vl.cybersecurityapplication.model;
import java.io.Serializable;
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 = "User_Details")
public class User_Details implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "UserId")
private int userId;
#Column(name = "FirstName")
private String firstName;
#Column(name = "LastName")
private String lastName;
#Column(name = "Password")
private String password;
#Column(name = "E_Mail")
private String eMail;
#Column(name = "Mobile_Num")
private int mobileNumber;
//getters and setters
}
Here is my repo interface
package vl.cybersecurityapplication.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import vl.cybersecurityapplication.model.User_Details;
public interface IUserRepository extends JpaRepository<User_Details, Long> {
public Integer findMobileNumberByName(String userName);
}
This is my repo class
package vl.cybersecurityapplication.repository;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import vl.cybersecurityapplication.model.User_Roles;
#Transactional
#Repository
public class UserRepository{
#Autowired
IUserRepository userRepository;
public Integer findMobileNumberByName(#PathVariable String lastName) {
int mobileNumber = userRepository.findMobileNumberByName("shaik");
System.out.println("Mobile Number : "+mobileNumber);
return mobileNumber;
}
}
I'm new to Spring Boot and JPA.
Here I need to query mobile number in User_Details table by using lastname.
i.e., Select Mobile_Num from User_Details where LastName= "xyz";
Can Some one help me how to wo write this query in my repo class.
You can write like this. But you cannot fetch only MobileNumber. You will get a complete object.
List<User> findByLastName(String lastname).
If you want to get only some fields then you should check out Projections
No need to use a native query. JPA supports object based query.
You can use List findByLastName(String lastname) which will generate that query in the backend and return the result.