Calling a one to many list in a saved entity returns null - spring-boot

When I check an entities contents right after saving it, everything appears normal, but any other time and the mapped entities in it are all null. Both checks are done by getting it through its repository.
Ad
package com.stevan.madsapp.entities;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.jws.soap.SOAPBinding;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
#Entity(name = "ad")
#NamedStoredProcedureQuery(
name = "ad.getAds",
procedureName = "get_ads",
parameters = { #StoredProcedureParameter(mode = ParameterMode.IN, name = "param1", type = String.class) }
)
public class Ad {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "name", nullable = false)
private String name;
#OneToMany(mappedBy = "ad")
private List<Question> questions = new ArrayList<>();
#ManyToOne
#JoinColumn(name = "author")
private UserDetails author;
#ManyToMany
#JoinTable(
name = "user_details_ad",
joinColumns = #JoinColumn(name = "user_details_id"),
inverseJoinColumns = #JoinColumn(name = "ad_id")
)
private Set<UserDetails> usersFinished = new HashSet<>();
#ManyToOne
#JoinColumn(name = "country")
private Country country;
#ManyToOne
#JoinColumn(name = "job")
private Job job;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Question> getQuestions() {
return questions;
}
public void setQuestions(List<Question> questions) {
this.questions = questions;
}
public UserDetails getAuthor() {
return author;
}
public void setAuthor(UserDetails author) {
this.author = author;
}
public Set<UserDetails> getUsersFinished() {
return usersFinished;
}
public void setUsersFinished(Set<UserDetails> usersFinished) {
this.usersFinished = usersFinished;
}
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
public Job getJob() {
return job;
}
public void setJob(Job job) {
this.job = job;
}
}
Question
package com.stevan.madsapp.entities;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
#Entity(name = "question")
public class Question {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(nullable = false)
private String type;
#Column(nullable = false)
private String question;
#OneToMany(mappedBy = "question")
private List<McOption> radioOptions = new ArrayList<>();
#OneToMany(mappedBy = "question")
private List<McOption> checkboxOptions = new ArrayList<>();
#ManyToOne
#JoinColumn(name = "ad_id")
private Ad ad;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public List<McOption> getRadioOptions() {
return radioOptions;
}
public void setRadioOptions(List<McOption> radioOptions) {
this.radioOptions = radioOptions;
}
public List<McOption> getCheckboxOptions() {
return checkboxOptions;
}
public void setCheckboxOptions(List<McOption> checkboxOptions) {
this.checkboxOptions = checkboxOptions;
}
}
AdService
package com.stevan.madsapp.services;
import com.stevan.madsapp.entities.*;
import com.stevan.madsapp.repositories.AdRepository;
import com.stevan.madsapp.security.components.TokenIdCheck;
import com.stevan.madsapp.web.dto.AdDTO;
import com.stevan.madsapp.web.dto.QuestionDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.persistence.criteria.CriteriaBuilder;
import java.util.*;
#Service
public class AdService {
#Autowired
private AdRepository adRepository;
#Autowired
private QuestionService questionService;
#Autowired
private JobService jobService;
#Autowired
private CountryService countryService;
#Autowired
private UserDetailsService userDetailsService;
public List<AdDTO> getAds(Integer id)
{
UserDetails user = userDetailsService.getUserDetails(id);
Job job = user.getJob();
Country country = user.getCountry();
List<Ad> jobAds = job.getAds();
List<Ad> countryAds = country.getAds();
List<Ad> commonAds = new ArrayList<Ad>(jobAds);
commonAds.retainAll(countryAds);
return convertListToDTO(commonAds);
}
public Ad store(AdDTO ad, Integer id) {
Ad newAd = new Ad();
newAd.setName(ad.getName());
List<Question> newQuestions = new ArrayList<>();
for(Question question : ad.getQuestions())
{
Question newQuestion = questionService.store(question);
newQuestions.add(newQuestion);
}
newAd.setQuestions(newQuestions);
newAd.setAuthor(userDetailsService.getUserDetails(id));
newAd.setJob(jobService.getJob(ad.getJobId()));
newAd.setCountry(countryService.getCountry(ad.getCountryId()));
adRepository.save(newAd);
System.out.println(adRepository.getById(newAd.getId()).getQuestions());
return newAd;
}
public Ad getAd(Integer id)
{
return adRepository.getById(id);
}
public AdDTO requestAd(Integer adId, Integer userId)
{
Ad ad = getAd(adId);
UserDetails user = userDetailsService.getUserDetails(userId);
if(ad.getJob() != user.getJob() || ad.getCountry() != user.getCountry())
{
return null;
}
return convertToDTO(ad);
}
public List<AdDTO> convertListToDTO(List<Ad> ads)
{
List<AdDTO> adDTOS = new ArrayList<>();
for(Ad ad: ads)
{
AdDTO newAdDTO = convertToDTO(ad);
adDTOS.add(newAdDTO);
}
return adDTOS;
}
public AdDTO convertToDTO(Ad ad)
{
AdDTO newAdDTO = new AdDTO();
newAdDTO.setId(ad.getId());
newAdDTO.setName(ad.getName());
newAdDTO.setQuestions(ad.getQuestions());
newAdDTO.setJobId(ad.getJob().getId());
newAdDTO.setCountryId(ad.getCountry().getId());
return newAdDTO;
}
}
QuestionService
package com.stevan.madsapp.services;
import com.stevan.madsapp.entities.Ad;
import com.stevan.madsapp.entities.McOption;
import com.stevan.madsapp.entities.Question;
import com.stevan.madsapp.repositories.QuestionRepository;
import com.stevan.madsapp.web.dto.McOptionDTO;
import com.stevan.madsapp.web.dto.QuestionDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
#Service
public class QuestionService {
#Autowired
private QuestionRepository questionRepository;
#Autowired
private McOptionService mcOptionService;
public Question store(Question question)
{
Question newQuestion = new Question();
newQuestion.setQuestion(question.getQuestion());
newQuestion.setType(question.getType());
if (newQuestion.getType().equals("radio"))
{
List<McOption> newMcOptions = new ArrayList<>();
for (McOption mcOption : question.getRadioOptions())
{
McOption newMcOption = mcOptionService.store(mcOption);
newMcOptions.add(newMcOption);
}
newQuestion.setRadioOptions(newMcOptions);
}
else if(newQuestion.getType().equals("checkbox"))
{
List<McOption> newMcOptions = new ArrayList<McOption>();
for (McOption mcOption : question.getCheckboxOptions())
{
McOption newMcOption = mcOptionService.store(mcOption);
newMcOptions.add(newMcOption);
}
newQuestion.setCheckboxOptions(newMcOptions);
}
questionRepository.save(newQuestion);
return newQuestion;
}
}
(This one just in case I missed something)
AdController
package com.stevan.madsapp.web.controllers;
import com.stevan.madsapp.entities.Ad;
import com.stevan.madsapp.exceptions.ValidationException;
import com.stevan.madsapp.security.components.TokenIdCheck;
import com.stevan.madsapp.services.AdService;
import com.stevan.madsapp.validators.AdValidator;
import com.stevan.madsapp.web.dto.AdDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
#RequestMapping(value = "/api/forms", produces = MediaType.APPLICATION_JSON_VALUE)
#CrossOrigin(origins = "http://localhost:4200")
public class AdController {
#Autowired
private AdService adService;
#Autowired
private AdValidator adValidator;
#Autowired
private TokenIdCheck tokenIdCheck;
#GetMapping(value = "/statuscheck")
private ResponseEntity<Object> check()
{
return new ResponseEntity<>(HttpStatus.OK);
}
#GetMapping
private ResponseEntity<List<AdDTO>> getAllAds(#RequestHeader("id") Integer id)
{
List<AdDTO> adList = adService.getAds(id);
return new ResponseEntity<>(adList, HttpStatus.OK);
}
#GetMapping(value = "/request")
private ResponseEntity<AdDTO> getAd(#RequestHeader("adId") Integer adId,
#RequestHeader("Authorization") String token,
#RequestHeader("id") Integer id)
{
if(tokenIdCheck.check(id, token))
{
AdDTO adDTO = adService.requestAd(adId, id);
if(adDTO != null)
{
return new ResponseEntity<>(adDTO, HttpStatus.OK);
}
}
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
#PostMapping
private ResponseEntity<AdDTO> uploadAd(#RequestBody AdDTO adDTO,
#RequestHeader("id") Integer id) throws ValidationException
{
Errors optionalErrors = new BeanPropertyBindingResult(adDTO, "adDTO");
ValidationUtils.invokeValidator(adValidator, adDTO, optionalErrors);
if(optionalErrors.hasErrors())
{
throw new ValidationException(optionalErrors);
}
Ad newAd = adService.store(adDTO, id);
return newAd != null
? new ResponseEntity<>(adService.convertToDTO(newAd), HttpStatus.OK)
: new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}
To clarify more thouroughly now, when I sysout an Ads questions, right after I store it, it shows that it has some questions, but when I do it when requesting an Ad later, it shows an empty list. In mysql they have their apropriate foreign keys.

I had to save the ad_id in the Question entity before I added that question to the questions_id list in the Ad entity. The only problem I had with that is that in order to set the parent Ad as the ad_id in every question, I needed to save the Ad itself first.
Here are the changes:
In AdService:
public Ad store(AdDTO ad, Integer id) {
Ad newAd = new Ad();
newAd.setName(ad.getName());
newAd.setAuthor(userDetailsService.getUserDetails(id));
newAd.setJob(jobService.getJob(ad.getJobId()));
newAd.setCountry(countryService.getCountry(ad.getCountryId()));
adRepository.save(newAd);
Set<Question> newQuestions = newAd.getQuestions();
for(Question question : ad.getQuestions())
{
Question newQuestion = questionService.store(question, newAd);
newQuestions.add(newQuestion);
}
adRepository.save(newAd);
System.out.println(adRepository.getById(newAd.getId()).getQuestions());
return newAd;
}
I just added another adRepository.save(newAd) before cycling through questions, and changed the store Question method to take in an Ad, which I used to set the ad_id in questions.
and in QuestionService:
public Question store(Question question, Ad newAd)
{
Question newQuestion = new Question();
newQuestion.setQuestion(question.getQuestion());
newQuestion.setType(question.getType());
newQuestion.setAd(newAd);
if (newQuestion.getType().equals("radio"))
{
List<McOption> newMcOptions = new ArrayList<>();
for (McOption mcOption : question.getRadioOptions())
{
McOption newMcOption = mcOptionService.store(mcOption);
newMcOptions.add(newMcOption);
}
newQuestion.setRadioOptions(newMcOptions);
}
else if(newQuestion.getType().equals("checkbox"))
{
List<McOption> newMcOptions = new ArrayList<McOption>();
for (McOption mcOption : question.getCheckboxOptions())
{
McOption newMcOption = mcOptionService.store(mcOption);
newMcOptions.add(newMcOption);
}
newQuestion.setCheckboxOptions(newMcOptions);
}
questionRepository.save(newQuestion);
return newQuestion;
}

Related

Get from VIEW in Spring boot

I am beginner with Spring Boot and trying to improve my skills to get new job, so I hope you help me even if the question maybe easy for you as I search a lot and gain nothing.
I need to get by id, but return data is duplicated with only one record, I will show you what I do and the result for more explanation.
In DB side:
I have VW_Prices view in DB and it's data as shown below:
In Spring Boot side:
VW_Prices class is :
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Immutable;
#Entity
#Table(name = "VW_PRICES")
public class VW_Prices implements Serializable {
private long dealId;
private Long quotationId;
private Long productPriceForEjada;
private Long productPriceForClient;
private Long productId;
private Long productQuantity;
private String productName;
#Id
#Column(name = "ID")
public long getDealId() {
return dealId;
}
public void setDealId(long dealId) {
this.dealId = dealId;
}
#Column(name = "PRODUCT_QUANTITY")
public Long getProductQuantity() {
return productQuantity;
}
public void setProductQuantity(Long productQuantity) {
this.productQuantity = productQuantity;
}
#Column(name = "PRODUCT_NAME")
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
#Column(name = "PRODUCT_PRICE_FOR_EJADA")
public Long getProductPriceForEjada() {
return productPriceForEjada;
}
public void setProductPriceForEjada(Long productPriceForEjada) {
this.productPriceForEjada = productPriceForEjada;
}
#Column(name = "PRODUCT_PRICE_FOR_CLIENT")
public Long getProductPriceForClient() {
return productPriceForClient;
}
public void setProductPriceForClient(Long productPriceForClient) {
this.productPriceForClient = productPriceForClient;
}
#Column(name = "PRODUCT_ID")
public Long getProductId() {
return productId;
}
public void setProductId(Long productId) {
this.productId = productId;
}
#Column(name = "QUOTATION_ID")
public Long getQuotationId() {
return quotationId;
}
public void setQuotationId(Long quotationId) {
this.quotationId = quotationId;
}
}
and I create VW_PricesRepository
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import springboot.deals_tracker_system.models.VW_Prices;
import springboot.deals_tracker_system.models.VW_Prices_interface;
public interface VW_PricesRepository extends JpaRepository<VW_Prices, Long> {
#Query( nativeQuery = true,value = "SELECT distinct * from VW_Prices v where v.id = :dealID " )
List<VW_Prices> findByDealId( #Param("dealID") Long id);
}
and my in my Service
public List<VW_Prices> findByDealId(Long dealId) {
System.out.println("we are in service");
List<VW_Prices> variableForDebug = VW_pricesRepository.findByDealId(dealId);
for (VW_Prices vw_Prices : variableForDebug) {
System.out.println(vw_Prices.getDealId() + " " + vw_Prices.getProductName());
}
return variableForDebug;
//return VW_pricesRepository.findByDealId(dealId);
}
When I pass dealId = 39 the result comes duplicated and not correct as in below:
how can I get correct data??
The view is made for Quotation Product Table to get product name.
i think the problem is the id annotation you must add GeneratedValue
fro the class:
#Entity
#Table(name = "VW_PRICES")
public class VW_Prices implements Serializable {
#Id
#GeneratedValue (strategy = GenerationType.IDENTITY)
private long dealId;
private Long quotationId;
private Long productPriceForEjada;
private Long productPriceForClient;
private Long productId;
private Long productQuantity;
private String productName;
//code..
}
You dont have to use JPQL for this type of queries it's already exist in jpa:
VW_PricesRepository:
public interface VW_PricesRepository extends JpaRepository<VW_Prices, Long> {
}
to get data by id use findById like that:
public VW_Prices findByDealId(Long dealId) {
System.out.println("we are in service");
VW_Prices vw_Prices = VW_pricesRepository.findById(dealId);
System.out.println(vw_Prices.getDealId() + " " +
vw_Prices.getProductName());
}
return vw_Prices;
}
All data should be deleted from VW_Prices table because ids are not unique, try to insert new data with unique id then try the above code
I detect the problem, The view has main table Quotation and I didn't select it's ID and I used ID of the secondary table as the main ID for the View
I just write it if any one Google for such problem

Spring Boot Jpa #ManyToOne : ForeignKey column in DB always populated to null

Employee.Java
`
import lombok.ToString;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
#ToString
#Entity
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int empid;
private String empname;
private String empcontact;
private String empemail;
private String empphoto;
#OneToMany(mappedBy = "employee", cascade = CascadeType.ALL)
private List<Skillset> skillset;
public int getEmpid() {
return empid;
}
public void setEmpid(int empid) {
this.empid = empid;
}
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
public String getEmpcontact() {
return empcontact;
}
public void setEmpcontact(String empcontact) {
this.empcontact = empcontact;
}
public String getEmpemail() {
return empemail;
}
public void setEmpemail(String empemail) {
this.empemail = empemail;
}
public String getEmpphoto() {
return empphoto;
}
public void setEmpphoto(String empphoto) {
this.empphoto = empphoto;
}
public List<Skillset> getSkillset() {
return skillset;
}
public void setSkillset(List<Skillset> skillset) {
this.skillset = skillset;
}`
SkillSet.Java
`
package aurozen.assign.aurozenassign.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.ToString;
import javax.persistence.*;
#Entity
public class Skillset {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int skillid;
private String skillname;
#JsonIgnore
#ManyToOne
#JoinColumn(name = "empId", nullable = false,updatable = false, insertable = true)
private Employee employee;
public int getSkillid() {
return skillid;
}
public void setSkillid(int skillid) {
this.skillid = skillid;
}
public String getSkillname() {
return skillname;
}
public void setSkillname(String skillname) {
this.skillname = skillname;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
#Override
public String toString() {
return "Skillset{" +
"skillid='" + skillid + '\'' +
", skillname='" + skillname + '\'' +
", employee=" + employee +
'}';
}
}
`
EmployeeRepositry.java
package aurozen.assign.aurozenassign.repositry;
import aurozen.assign.aurozenassign.entity.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
#Repository
public interface EmployeeRepositry extends JpaRepository<Employee, Integer> {
Optional<Employee> findByEmpcontact(String s);
}
SkillSetRepositry.java
package aurozen.assign.aurozenassign.repositry;
import aurozen.assign.aurozenassign.entity.Skillset;
import org.springframework.data.jpa.repository.JpaRepository;
public interface SkillsetRepositry extends JpaRepository<Skillset, Integer> {
}
Controller
#PostMapping(value = "/signup",produces = {"application/json"})
public Employee addEmployee(#RequestBody Employee employee) {
empRepo.save(employee);
return employee;
}
Json Data
{
"empname": "sandep",
"empcontact": "9650114890",
"empemail": "aidaih",
"empphoto": "paidpaid",
"skillset": [
{
"skillname": "jop"
}
]
}
I have attached Db Screenshot
Database Screenshot with empid as foreign key in skillset table
foreign key(empid) in the skillset table always populating to null when ever I try to post the data through postman.other fields getting populating without any problem in both the table
The relationship between Skillset and Employee is owned by Skillset. This means JPA will persist the state the Skillset objects have.
But via #RequestBody you are creating an Employee instance.
While that references a Skillset instances, that instance does not reference the Employee.
Therefor no relationship gets persisted.
To fix this add code to setSkillset to set the employee property of it.
Something like this should do:
public void setSkillset(List<Skillset> skillset) {
this.skillset = skillset;
skillset.foreach(s -> s.setEmployee(this));
}

SpringBoot+Neo4J OGM update record

I am getting very weird problem when trying to update the record in database .Main Node is updating properly but Relationship not creating after deleting it.
I have Node with relationship in database i am trying to update it via this code
Role roleRecord = findByUuid(uuid);//Get Role Record
Role roleData = new Role();//Create a new role object and update values
roleData.setDescription(role.getDescription());
roleData.setUuid(roleRecord.getUuid());
roleData.setRoleName(roleRecord.getRoleName());
roleData.setLabels(updatedLabelRecord);
deleteRole(roleRecord);// Delete existing role from database
for (Labels label : dbRecord) { //Delete relationship Node
deleteLabel(label);
}
createRole(roleData);// Then Create role and Label with new Data set
This code creating Role record but not the Label Node(Which is a relationship),Relationship something like this
Role->FILTERS_ON->Label
EDIT 1-
Role is a Neo4j Entity
deleteRole is method
public void deleteRole(Role roleEntity) {
roleRepository.delete(roleEntity);
}
deleteLabel is a method
public void deleteLabel(com.nokia.nsw.uiv.uam.entities.Labels label) {
labelRepository.delete(label);
}
createRole is a method
public Role createRole(Role role) {
return roleRepository.save(role);
}
EDIT 2 -
Role Entity Class
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.neo4j.ogm.annotation.GeneratedValue;
import org.neo4j.ogm.annotation.Id;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.Api;
#Api(
tags = "Role",
description = ""
)
#NodeEntity(label = "com.model.Role")
public class Role implements Serializable {
private static final long serialVersionUID = -8010543109475083169L;
private String roleName = null;
private String description = null;
// #Relationship(type = "HAS_ROLE", direction="INCOMING")
// private Tenant tenant;
#Relationship(type = "FILTERS_ON")
private List<Labels> labels = new ArrayList<>();
#JsonIgnore
private Long id;
#Id
#GeneratedValue(strategy = UivUuidStrategy.class)
#JsonProperty("id")
private String uuid;
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
// public Tenant getTenant() {
// return tenant;
// }
//
// public void setTenant(Tenant tenant) {
// this.tenant = tenant;
// }
public List<Labels> getLabels() {
return labels;
}
public void setLabels(List<Labels> labels) {
this.labels = labels;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
Label Entity class
import java.io.Serializable;
import java.util.Map;
import java.util.Objects;
import org.neo4j.ogm.annotation.GeneratedValue;
import org.neo4j.ogm.annotation.Id;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Properties;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
#NodeEntity(label = "com.model.role.Filter")
public class Labels implements Serializable {
private static final long serialVersionUID = 1L;
private String labelName;
#Properties
private Map<String, String> match;
private String access;
#JsonIgnore
private Long id;
#Id
#GeneratedValue(strategy = UivUuidStrategy.class)
#JsonProperty("id")
private String uuid;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public Map<String, String> getMatch() {
return match;
}
public void setMatch(Map<String, String> match) {
this.match = match;
}
public String getLabelName() {
return labelName;
}
public void setLabelName(String labelName) {
this.labelName = labelName;
}
public String getAccess() {
return access;
}
public void setAccess(String access) {
this.access = access;
}
#Override
public String toString() {
return "labelName : " + this.labelName;
}
#Override
public boolean equals(Object obj) {
return (obj instanceof Labels) && this.labelName.equals(((Labels) obj).getLabelName());
}
#Override
public int hashCode() {
return Objects.hash(labelName);
}
}

Unique index or primary key violation: "PRIMARY KEY ON PUBLIC.CAR(ID) : While calling the POST service

CarController.java
package com.mytaxi.controller;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.mytaxi.controller.mapper.CarMapper;
import com.mytaxi.datatransferobject.CarDTO;
import com.mytaxi.datatransferobject.CarDTO;
import com.mytaxi.domainobject.CarDO;
import com.mytaxi.domainvalue.Type;
import com.mytaxi.exception.ConstraintsViolationException;
import com.mytaxi.exception.EntityNotFoundException;
import com.mytaxi.service.car.CarService;
#RestController
#RequestMapping("v1/cars")
public class CarController
{
private final CarService carService;
#Autowired
public CarController(final CarService carService)
{
this.carService = carService;
}
#PostMapping
#ResponseStatus(HttpStatus.CREATED)
public CarDTO createCar(#Valid #RequestBody CarDTO carDTO) throws ConstraintsViolationException
{
CarDO carDO = CarMapper.makeCarDO(carDTO);
carDTO = CarMapper.makeCarDTO(carDO);
carService.create(carDO);
return carDTO;
}
}
CarDO.java
package com.mytaxi.domainobject;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.Max;
import com.mytaxi.domainvalue.Type;
#Entity
#Table(
name = "car",
uniqueConstraints = #UniqueConstraint(name = "uc_licensePlate", columnNames = {"licensePlate"})
)
public class CarDO
{
#Id
#Column(nullable = false)
#GeneratedValue
private Long id;
#Column(nullable = false)
#Enumerated(EnumType.STRING)
private Type manufacturer;
#Column(nullable = false)
private String licensePlate;
#Column(nullable = false)
private Integer seatCount;
#Column(nullable = false)
private String engineType;
#Column(nullable = false)
#org.hibernate.annotations.Type(type="yes_no")
private Boolean convertible;
#Column
#Max(5)
private Integer rating;
#Column(nullable = false)
#org.hibernate.annotations.Type(type="yes_no")
private Boolean isFunctioning = true;
#Column(nullable = false)
#org.hibernate.annotations.Type(type="yes_no")
private Boolean isBooked = false;
public Boolean getIsFunctioning()
{
return isFunctioning;
}
public void setIsFunctioning(Boolean isFunctioning)
{
this.isFunctioning = isFunctioning;
}
public CarDO(Type manufacturer, String licensePlate, Integer seatCount,
String engineType, Boolean convertible)
{
this.manufacturer = manufacturer;
this.licensePlate = licensePlate;
this.seatCount = seatCount;
this.engineType = engineType;
this.convertible = convertible;
}
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
public Type getManufacturer()
{
return manufacturer;
}
public void setManufacturer(Type manufacturer)
{
this.manufacturer = manufacturer;
}
public String getLicensePlate()
{
return licensePlate;
}
public void setLicensePlate(String licensePlate)
{
this.licensePlate = licensePlate;
}
public Integer getSeatCount()
{
return seatCount;
}
public void setSeatCount(Integer seatCount)
{
this.seatCount = seatCount;
}
public String getEngineType()
{
return engineType;
}
public void setEngineType(String engineType)
{
this.engineType = engineType;
}
public Boolean getConvertible()
{
return convertible;
}
public void setConvertible(Boolean convertible)
{
this.convertible = convertible;
}
public Integer getRating()
{
return rating;
}
public void setRating(Integer rating)
{
this.rating = rating;
}
}
CarDTO.java
package com.mytaxi.datatransferobject;
import javax.validation.constraints.NotNull;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.mytaxi.domainvalue.Type;
#JsonInclude(JsonInclude.Include.NON_NULL)
public class CarDTO
{
#JsonIgnore
private Long id;
#NotNull(message = "license plate can not be null!")
private String licensePlate;
#NotNull(message = "cartype can not be null!")
private Type carType;
#NotNull(message = "seatCount can not be null!")
private Integer seatCount;
#NotNull(message = "engineType can not be null!")
private String engineType;
private Boolean convertible;
private CarDTO()
{
}
public CarDTO(Long id, String licensePlate, Type carType, Integer seatCount, String engineType, Boolean convertible)
{
this.id = id;
this.licensePlate = licensePlate;
this.carType = carType;
this.seatCount = seatCount;
this.engineType = engineType;
this.convertible = convertible;
}
public static CarDTOBuilder newBuilder()
{
return new CarDTOBuilder();
}
#JsonProperty
public Long getId()
{
return id;
}
public String getLicensePlate()
{
return licensePlate;
}
public Type getCarType()
{
return carType;
}
public Integer getSeatCount()
{
return seatCount;
}
public String getEngineType()
{
return engineType;
}
public Boolean getConvertible()
{
return convertible;
}
public static class CarDTOBuilder
{
private Long id;
private String licensePlate;
private Type carType;
private Integer seatCount;
private String engineType;
private Boolean convertible;
public CarDTOBuilder setId(Long id)
{
this.id = id;
return this;
}
public CarDTOBuilder licensePlate(String licensePlate)
{
this.licensePlate = licensePlate;
return this;
}
public CarDTOBuilder setLicensePlate(String licensePlate)
{
this.licensePlate = licensePlate;
return this;
}
public CarDTOBuilder setCarType(Type carType)
{
this.carType = carType;
return this;
}
public CarDTOBuilder setSeatCount(Integer seatCount)
{
this.seatCount = seatCount;
return this;
}
public CarDTOBuilder setEngineType(String engineType)
{
this.engineType = engineType;
return this;
}
public CarDTOBuilder setConvertible(Boolean convertible)
{
this.convertible = convertible;
return this;
}
public CarDTO createCarDTO()
{
return new CarDTO(id, licensePlate, carType, seatCount, engineType, convertible);
}
}
}
CarMapper.java
package com.mytaxi.controller.mapper;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import com.mytaxi.datatransferobject.CarDTO;
import com.mytaxi.domainobject.CarDO;
public class CarMapper
{
public static CarDO makeCarDO(CarDTO carDTO)
{
return new CarDO(carDTO.getCarType(), carDTO.getLicensePlate(),
carDTO.getSeatCount(), carDTO.getEngineType(), carDTO.getConvertible());
}
public static CarDTO makeCarDTO(CarDO carDO)
{
CarDTO.CarDTOBuilder carDTOBuilder = CarDTO.newBuilder()
.setId(carDO.getId())
.setCarType(carDO.getManufacturer())
.licensePlate(carDO.getLicensePlate())
.setSeatCount(carDO.getSeatCount())
.setEngineType(carDO.getEngineType())
.setConvertible(carDO.getConvertible());
return carDTOBuilder.createCarDTO();
}
public static List<CarDTO> makeCarDTOList(Collection<CarDO> cars)
{
return cars.stream()
.map(CarMapper::makeCarDTO)
.collect(Collectors.toList());
}
}
CarService.java
package com.mytaxi.service.car;
import java.util.List;
import com.mytaxi.domainobject.CarDO;
import com.mytaxi.domainvalue.Type;
import com.mytaxi.exception.ConstraintsViolationException;
import com.mytaxi.exception.EntityNotFoundException;
public interface CarService
{
CarDO create(CarDO carDO) throws ConstraintsViolationException;
}
DefaultCarService.java
#Override
public CarDO create(CarDO carDO) throws ConstraintsViolationException
{
CarDO car;
try
{
car = carRepository.save(carDO);
}
catch (DataIntegrityViolationException e)
{
LOG.warn("ConstraintsViolationException while creating a driver: {}", carDO, e.getCause());
throw new ConstraintsViolationException(e.getMessage());
}
return car;
}
CarRepository.java
package com.mytaxi.dataaccessobject;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import com.mytaxi.domainobject.CarDO;
import com.mytaxi.domainvalue.Type;
public interface CarRepository extends CrudRepository<CarDO, Long>
{
List<CarDO> findByIsFunctioning(Boolean isFunctioning);
CarDO findByLicensePlate(String licensePlate);
List<CarDO> findByManufacturer(Type type);
}
When I hit the RESTAPI post service, I get the below exception.
Unique index or primary key violation:
aused by: org.h2.jdbc.JdbcSQLException: Unique index or primary key violation: "PRIMARY KEY ON PUBLIC.CAR(ID)"; SQL statement:
insert into car (convertible, engine_type, is_booked, is_functioning, license_plate, manufacturer, rating, seat_count, id) values (?, ?, ?, ?, ?, ?, ?, ?, ?) [23505-197]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:357) ~[h2-1.4.197.jar:1.4.197]
at org.h2.message.DbException.get(DbException.java:179) ~[h2-1.4.197.jar:1.4.197]
at org.h2.message.DbException.get(DbException.java:155) ~[h2-1.4.197.jar:1.4.197]
at org.h2.mvstore.db.MVPrimaryIndex.add(MVPrimaryIndex.java:123) ~[h2-1.4.197.jar:1.4.197]
at org.h2.mvstore.db.MVTable.addRow(MVTable.java:732) ~[h2-1.4.197.jar:1.4.197]
at org.h2.command.dml.Insert.insertRows(Insert.java:182) ~[h2-1.4.197.jar:1.4.197]
at org.h2.command.dml.Insert.update(Insert.java:134) ~[h2-1.4.197.jar:1.4.197]
at org.h2.command.CommandContainer.update(CommandContainer.java:102) ~[h2-1.4.197.jar:1.4.197]
at org.h2.command.Command.executeUpdate(Command.java:261) ~[h2-1.4.197.jar:1.4.197]
at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:199) ~[h2-1.4.197.jar:1.4.197]
at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:153) ~[h2-1.4.197.jar:1.4.197]
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61) ~[HikariCP-2.7.9.jar:na]
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java) ~[HikariCP-2.7.9.jar:na]
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:175) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
... 93 common frames omitted"PRIMARY KEY ON PUBLIC.CAR(ID) :
Any idea what is wrong in the code?
I was encountering the same problem for an #Entity class. My data.sql ids were conflicting with the auto-generated ids from H2.
My solution was to change:
#GeneratedValue(strategy = GenerationType.AUTO)
to
#GeneratedValue(strategy = GenerationType.IDENTITY)
This way I could keep my data.sql file.
The javadoc here indicates that GenerationType.IDENTITY "Indicates that the persistence provider must assign primary keys for the entity using a database identity column."
It was generating the sequence from 1, since there were already 3 values in the database which was inserted manually while initializing the application, modifying the auto generated sequences solved the issue.
#Eenvincible, if you created a data.sql to populate the data, you need to delete those.
The problem is probably given by the fact that you already are initializing data, either through a data.sql file, or CommandLineRunner.
Therefore, if you have
#GeneratedValue(strategy = GenerationType.AUTO)
Spring Data JPA automatically tries to set ID from 1 and then autoincrements of 1 for every new entry. If you already have some entries which start with ID 1 that is the problem (there is a conflict of ids).
You should either remove the data inserted if you want to keep things simple, or you should use other methods for generating the id, for example uuid see here https://thorben-janssen.com/generate-uuids-primary-keys-hibernate/

Updating null value for foreign key

I am working with JPA and I am trying to insert foreign key value its working fine but during modifying it is updating null values..
Please Refer following code
package com.bcits.bfm.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
#Entity
#Table(name="JOB_CALENDER")
public class JobCalender implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private int jobCalenderId;
private int scheduleType;
private String title;
private String description;
private String recurrenceRule;
private String recurrenceException;
private int recurrenceId;
private boolean isAllDay;
private Date start;
private Date end;
private String jobNumber;
private String jobGroup;
private int expectedDays;
private String jobPriority;
private String jobAssets;
private MaintainanceTypes maintainanceTypes;
private MaintainanceDepartment departmentName;
private JobTypes jobTypes;
#Id
#Column(name="JOB_CALENDER_ID")
#SequenceGenerator(name = "JOB_CALENDER_SEQUENCE", sequenceName = "JOB_CALENDER_SEQUENCE")
#GeneratedValue(generator = "JOB_CALENDER_SEQUENCE")
public int getJobCalenderId() {
return jobCalenderId;
}
public void setJobCalenderId(int jobCalenderId ) {
this.jobCalenderId = jobCalenderId ;
}
#Column(name="SCHEDULE_TYPE")
public int getScheduleType() {
return scheduleType;
}
public void setScheduleType(int scheduleType) {
this.scheduleType = scheduleType;
}
#Column(name="START_DATE")
public Date getStart() {
return start;
}
public void setStart(Date start) {
this.start = start;
}
#Column(name="END_DATE")
public Date getEnd() {
return end;
}
public void setEnd(Date end) {
this.end = end;
}
#Column(name="Title")
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Column(name="DESCRIPTION")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name="RECURRENCE_RULE")
public String getRecurrenceRule() {
return recurrenceRule;
}
public void setRecurrenceRule(String recurrenceRule) {
this.recurrenceRule = recurrenceRule;
}
#Column(name="IS_ALL_DAY")
public boolean getIsAllDay() {
return isAllDay;
}
public void setIsAllDay(boolean isAllDay) {
this.isAllDay = isAllDay;
}
#Column(name="RECURENCE_EXCEPTION")
public String getRecurrenceException() {
return recurrenceException;
}
public void setRecurrenceException(String recurrenceException) {
this.recurrenceException = recurrenceException;
}
#Column(name="RECURRENCE_ID")
public int getRecurrenceId() {
return recurrenceId;
}
public void setRecurrenceId(int recurrenceId) {
this.recurrenceId = recurrenceId;
}
/*Custom Columns*/
#Column(name = "JOB_NUMBER", nullable = false, length = 45)
public String getJobNumber() {
return this.jobNumber;
}
public void setJobNumber(String jobNumber) {
this.jobNumber = jobNumber;
}
#Column(name = "JOB_GROUP", nullable = false, length = 45)
public String getJobGroup() {
return this.jobGroup;
}
public void setJobGroup(String jobGroup) {
this.jobGroup = jobGroup;
}
#Column(name = "EXPECTED_DAYS", nullable = false, precision = 11, scale = 0)
public int getExpectedDays() {
return this.expectedDays;
}
public void setExpectedDays(int expectedDays) {
this.expectedDays = expectedDays;
}
#Column(name = "JOB_PRIORITY", nullable = false, length = 45)
public String getJobPriority() {
return this.jobPriority;
}
public void setJobPriority(String jobPriority) {
this.jobPriority = jobPriority;
}
#Column(name = "JOB_ASSETS", nullable = false, length = 4000)
public String getJobAssets() {
return this.jobAssets;
}
public void setJobAssets(String jobAssets) {
this.jobAssets = jobAssets;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "JOB_DEPT_ID",referencedColumnName="MT_DP_IT",nullable = false)
public MaintainanceDepartment getMaintainanceDepartment() {
return this.departmentName;
}
public void setMaintainanceDepartment(
MaintainanceDepartment departmentName) {
this.departmentName = departmentName;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "JOB_TYPE_ID",referencedColumnName="JT_ID",nullable = false)
public JobTypes getJobTypes() {
return this.jobTypes;
}
public void setJobTypes(JobTypes jobTypes) {
this.jobTypes = jobTypes;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "MAINTAINANCE_TYPE_ID",nullable = false)
public MaintainanceTypes getMaintainanceTypes() {
return this.maintainanceTypes;
}
public void setMaintainanceTypes(MaintainanceTypes maintainanceTypes) {
this.maintainanceTypes = maintainanceTypes;
}
}
And Parent Table Is
package com.bcits.bfm.model;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
/**
* MaintainanceTypes entity. #author MyEclipse Persistence Tools
*/
#Entity
#Table(name = "MAINTAINANCE_TYPES")
public class MaintainanceTypes implements java.io.Serializable {
private static final long serialVersionUID = 1L;
// Fields
private int mtId;
private String maintainanceType;
private String description;
private Timestamp mtDt;
private String createdBy;
private String lastUpdatedBy;
private Timestamp lastUpdatedDt;
private Set<JobCards> jobCardses = new HashSet<JobCards>(0);
private Set<JobCalender> jobCalenders = new HashSet<JobCalender>(0);
// Constructors
/** default constructor */
public MaintainanceTypes() {
}
/** minimal constructor */
public MaintainanceTypes(int mtId, String maintainanceType, Timestamp mtDt) {
this.mtId = mtId;
this.maintainanceType = maintainanceType;
this.mtDt = mtDt;
}
/** full constructor */
public MaintainanceTypes(int mtId, String maintainanceType,
String description, Timestamp mtDt, String createdBy,
String lastUpdatedBy, Timestamp lastUpdatedDt,
Set<JobCards> jobCardses) {
this.mtId = mtId;
this.maintainanceType = maintainanceType;
this.description = description;
this.mtDt = mtDt;
this.createdBy = createdBy;
this.lastUpdatedBy = lastUpdatedBy;
this.lastUpdatedDt = lastUpdatedDt;
this.jobCardses = jobCardses;
}
// Property accessors
#Id
#Column(name = "MT_ID", unique = true, nullable = false, precision = 11, scale = 0)
#SequenceGenerator(name = "MAINTENANCE_TYPES_SEQ", sequenceName = "MAINTENANCE_TYPES_SEQ")
#GeneratedValue(generator = "MAINTENANCE_TYPES_SEQ")
public int getMtId() {
return this.mtId;
}
public void setMtId(int mtId) {
this.mtId = mtId;
}
#Column(name = "MAINTAINANCE_TYPE", nullable = false, length = 20)
public String getMaintainanceType() {
return this.maintainanceType;
}
public void setMaintainanceType(String maintainanceType) {
this.maintainanceType = maintainanceType;
}
#Column(name = "DESCRIPTION", length = 200)
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name = "MT_DT", nullable = false, length = 11)
public Timestamp getMtDt() {
return this.mtDt;
}
public void setMtDt(Timestamp mtDt) {
this.mtDt = mtDt;
}
#Column(name = "CREATED_BY", length = 45)
public String getCreatedBy() {
return this.createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
#Column(name = "LAST_UPDATED_BY", length = 45)
public String getLastUpdatedBy() {
return this.lastUpdatedBy;
}
public void setLastUpdatedBy(String lastUpdatedBy) {
this.lastUpdatedBy = lastUpdatedBy;
}
#Column(name = "LAST_UPDATED_DT", length = 11)
public Timestamp getLastUpdatedDt() {
return this.lastUpdatedDt;
}
public void setLastUpdatedDt(Timestamp lastUpdatedDt) {
this.lastUpdatedDt = lastUpdatedDt;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "maintainanceTypes")
public Set<JobCards> getJobCardses() {
return this.jobCardses;
}
public void setJobCardses(Set<JobCards> jobCardses) {
this.jobCardses = jobCardses;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "maintainanceTypes")
public Set<JobCalender> getJobCalenders() {
return this.jobCalenders;
}
public void setJobCalenders(Set<JobCalender> jobCalenders) {
this.jobCalenders = jobCalenders;
}
}
I am calling below method to Update
public void Update(JobCalender jobCalender) {
update(jobCalender); //update() is generic method
}
public T update(final T t) {
BfmLogger.logger.info("updating "+t+" instance");
try {
T result = this.entityManager.merge(t);
BfmLogger.logger.info("update successful");
return result;
} catch (RuntimeException re) {
BfmLogger.logger.error("update failed", re);
throw re;
}
}
My Controller Code
#RequestMapping(value = "/index/create", method = RequestMethod.POST)
public #ResponseBody List<?> create(#RequestBody Map<String, Object>model,#ModelAttribute JobCalender jobCalender,BindingResult bindingResult, HttpServletRequest request) throws ParseException {
jobCalender.setDescription((String)model.get("description"));
jobCalender.setTitle((String)model.get("title"));
SimpleDateFormat iso8601 = new SimpleDateFormat("yyyy-M-dd'T'HH:mm:ss.SSS'Z'");
iso8601.setTimeZone(TimeZone.getTimeZone("UTC"));
jobCalender.setStart(iso8601.parse((String)model.get("start")));
jobCalender.setEnd(iso8601.parse((String)model.get("end")));
jobCalender.setIsAllDay((boolean) model.get("isAllDay"));
jobCalender.setRecurrenceRule((String)model.get("recurrenceRule"));
jobCalender.setRecurrenceException((String)model.get("recurrenceException"));
if(model.get("recurrenceId")!=null)
jobCalender.setRecurrenceId((Integer)model.get("recurrenceId"));
jobCalender.setScheduleType(Integer.parseInt(model.get("scheduleType").toString()));
jobCalender.setJobNumber((String) model.get("jobNumber"));
jobCalender.setDescription((String) model.get("description"));
jobCalender.setJobGroup((String) model.get("jobGroup"));
jobCalender.setMaintainanceDepartment(maintainanceDepartmentService.find(Integer.parseInt(model.get("departmentName").toString())));
jobCalender.setMaintainanceTypes(maintainanceTypesService.find(Integer.parseInt(model.get("maintainanceTypes").toString())));
jobCalender.setJobTypes(jobTypesService.find(Integer.parseInt(model.get("jobTypes").toString())));
jobCalender.setJobPriority((String) model.get("jobPriority"));
String ids="";
#SuppressWarnings("unchecked")
List<Map<String, Object>> listAssets = (ArrayList<Map<String, Object>>) model.get("assetName");// this is what you have already
for (Map<String, Object> map1 :listAssets) {
for (Map.Entry<String, Object> entry : map1.entrySet()) {
if(entry.getKey().equalsIgnoreCase("assetId")){
ids+=entry.getValue()+",";
}
}
}
jobCalender.setJobAssets(ids);
jobCalenderService.Update(jobCalender);
}
while Updating JOB_CALENDER Table it is Adding NULL Value For MAINTAINANCE_TYPE_ID Column
Please Help Me
Thank You
Regards
Manjunath Kotagi

Resources