Basically I am not understanding that how to send data rest-api class using Postman ?
When I use Postman to run rest-api to save record it gives me errors like application json format not supported..
I have following class to represent Many to Many relation
package com.ps.usercourse;
import java.io.Serializable;
import java.util.Objects;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.MapsId;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.ps.course.Course;
import com.ps.user.User;
#Entity
public class UserCourse implements Serializable
{
private static final long serialVersionUID = 46419863112677606L;
#EmbeddedId
private UserCourseId id;
#ManyToOne
#MapsId("emailId")
#JsonBackReference
User user;
#ManyToOne
#MapsId("courseId")
#JsonBackReference
Course course;
Boolean isActive = true;
public UserCourse() {
}
public UserCourse(User user, Course course, Boolean isActive) {
this.user = user;
this.course = course;
this.isActive = isActive;
}
public UserCourse(UserCourseId id, User user, Course course, Boolean isActive) {
this.id = id;
this.user = user;
this.course = course;
this.isActive = isActive;
}
public UserCourseId getId() {
return id;
}
public void setId(UserCourseId id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
public Boolean getIsActive() {
return isActive;
}
public void setIsActive(Boolean isActive) {
this.isActive = isActive;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
return false;
UserCourse that = (UserCourse) o;
return Objects.equals(user, that.user) &&
Objects.equals(course, that.course);
}
#Override
public int hashCode() {
return Objects.hash(user, course);
}
}
This is rest api that I am trying to call through Postman
#RequestMapping(value="/UserCourse",method=RequestMethod.POST)
#ResponseBody
public UserCourse addUser(#RequestBody UserCourse userCourse, HttpServletRequest req, HttpServletResponse res)
{
return userCourseService.save(userCourse);
}
Related
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;
}
I have two entities User and Focus for which I must store a ranking such that a User can have a ranking for many Focus', and a Focus may have many users. To handle this I've followed https://www.baeldung.com/jpa-many-to-many part 3 whereby I have the 2 following classes:
#Entity(name = "UserBaseRatings")
public class Rating {
#EmbeddedId
RatingKey id;
#ManyToOne
#MapsId("userID")
#JoinColumn(name="userID")
private User user;
#ManyToOne
#MapsId("focusID")
#JoinColumn(name="focusID")
private Focus focus;
private BigDecimal baseRating;
protected Rating(){}
public Rating(User user, Focus focus, BigDecimal baseRating) {
this.user = user;
this.focus = focus;
this.baseRating = baseRating;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Focus getFocus() {
return focus;
}
public void setFocus(Focus focus) {
this.focus = focus;
}
public BigDecimal getBaseRating() {
return baseRating;
}
public void setBaseRating(BigDecimal baseRating) {
this.baseRating = baseRating;
}
}
and
#Embeddable
public class RatingKey implements Serializable {
#Column(name="userID")
private Long userID;
#Column(name="focusID")
private Long focusID;
protected RatingKey(){}
public RatingKey(Long userID, Long focusID) {
this.userID = userID;
this.focusID = focusID;
}
public Long getUserID() {
return userID;
}
public void setUserID(Long userID) {
this.userID = userID;
}
public Long getFocusID() {
return focusID;
}
public void setFocusID(Long focusID) {
this.focusID = focusID;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RatingKey ratingKey = (RatingKey) o;
return Objects.equals(userID, ratingKey.userID) &&
Objects.equals(focusID, ratingKey.focusID);
}
#Override
public int hashCode() {
return Objects.hash(userID, focusID);
}
}
The table for UserBaseRatings has a default value of 1 for baseRating such that if a user does not have a rating on the current focus their rating should be 1. I'm running into a problem where if the user hasn't made a rating then the set of Rating's is empty instead of having a rating of 1 for each focus that exists.
User:
public class User {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long userID;
#Column(name = "userHashedPassword")
private String password;
#Column(name = "userName")
private String userName;
#Column(name = "userEmail")
private String email;
//probably being reset
#Transient
private List<String> groups = new LinkedList<>();
#ManyToMany
#JoinTable(name = "UserRoles",
joinColumns = #JoinColumn(
name = "userID"),
inverseJoinColumns = #JoinColumn(
name = "roleID"))
private Set<Role> roles = new HashSet<>();
#OneToMany(mappedBy = "user")
private Set<Rating> ratings;
protected User(){}
public User(String userHashedPassword, String userName, String email, Set<Role> roles){
this.password = userHashedPassword;
this.userName = userName;
this.email = email;
this.roles = roles;
}
public Long getUserId() {
return userID;
}
public void setId(Long userID) {
this.userID = userID;
}
public String getPassword(){
return password;
}
public void setPassword(String password){
this.password = password;
}
public String getUsername() {
return userName;
}
public void setUsername(String name) {
this.userName = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
public Set<Rating> getRatings() {
return ratings;
}
public void setRatings(Set<Rating> ratings) {
this.ratings = ratings;
}
}
Focus:
#Entity
public class Focus {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long focusID;
private String focusCategory;
private String focusName;
private String focusExplanation;
#OneToMany(mappedBy = "focus")
Set<Rating> ratings;
//image
protected Focus(){}
public Focus(String focusCategory, String focusName, String focusExplanation, Set<Rating> ratings){
this.focusCategory = focusCategory;
this.focusName = focusName;
this.focusExplanation = focusExplanation;
this.ratings = ratings;
}
public Long getFocusId() {
return focusID;
}
public void setFocusId(Long focusID) {
this.focusID = focusID;
}
public String getFocusCategory() {
return focusCategory;
}
public void setFocusCategory(String focusCategory) {
this.focusCategory = focusCategory;
}
public String getFocusName() {
return focusName;
}
public void setFocusName(String focusName) {
this.focusName = focusName;
}
public String getFocusExplanation() {
return focusExplanation;
}
public void setFocusExplanation(String focusExplanation) {
this.focusExplanation = focusExplanation;
}
public Set<Rating> getRatings() {
return ratings;
}
public void setRatings(Set<Rating> ratings) {
this.ratings = ratings;
}
}
What am I missing that will allow a User's Ratings to be populated with the default value for each Focus that exists in the database?
Edit: Added #PrePersist and #PreUpdate to the Rating entity:
#Entity(name = "UserBaseRatings")
public class Rating {
#EmbeddedId
RatingKey id;
#ManyToOne
#MapsId("userID")
#JoinColumn(name="userID")
private User user;
#ManyToOne
#MapsId("focusID")
#JoinColumn(name="focusID")
private Focus focus;
private BigDecimal baseRating;
protected Rating(){}
public Rating(User user, Focus focus, BigDecimal baseRating) {
this.user = user;
this.focus = focus;
this.baseRating = baseRating;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Focus getFocus() {
return focus;
}
public void setFocus(Focus focus) {
this.focus = focus;
}
public BigDecimal getBaseRating() {
return baseRating;
}
public void setBaseRating(BigDecimal baseRating) {
this.baseRating = baseRating;
}
#PrePersist
public void prePersist() {
if(baseRating == null) {
baseRating = BigDecimal.ONE;
}
}
#PreUpdate
public void preUpdate() {
if(baseRating == null) {
baseRating = BigDecimal.ONE;
}
}
}
Changing spring.jpa.hibernate.ddl-auto= from none to update also made no difference.
If you use ORM all default values have to be explicitly declared. It can be done this way
#Entity(name = "UserBaseRatings")
public class Rating {
// ...
private BigDecimal baseRating = BigDecimal.ONE;
// ...
}
or use #PrePersist and #PreUpdate
#Entity(name = "UserBaseRatings")
public class Rating {
// ...
private BigDecimal baseRating;
// ...
#PrePersist
public void prePersist() {
if(baseRating == null) {
baseRating = BigDecimal.ONE;
}
}
#PreUpdate
public void preUpdate() {
if(baseRating == null) {
baseRating = BigDecimal.ONE;
}
}
}
could you help me with this question?
I built a project on sts4. I am trying to let users register an account on Postman. The primary method I am testing is Put(PutMapping), which I wrote on sts4. I got the project initialized completely, but when I click send from Postman, I got errors like below.
not-null property references a null or transient value: com.appsdeveloperblog.app.ws.io.entity.UserEntity.firstName
The following is part of my project.
UserDetailsRequestModel, (for processing incoming requestbody)
public class UserDetailsRequestModel {
private String firstName;
private String lastName;
private String email;
private String password;
public String getFirstname() {
return firstName;
}
public void setFirstname(String firstname) {
this.firstName = firstname;
}
public String getLastname() {
return lastName;
}
public void setLastname(String lastname) {
this.lastName = lastname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}```
2. UserRest, (Class, which will be returned back to Postman)
```package com.appsdeveloperblog.app.ws.ui.model.response;
public class UserRest {
// public id, not auto increment key from database
private String userId;
private String firstName;
private String lastName;
private String email;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}```
3. UserDTO
```package com.appsdeveloperblog.app.ws.shared.dto;
import java.io.Serializable;
public class UserDTO implements Serializable {
private static final long serialVersionUID = -5607842248454975055L;
// auto increment key from database
private long id;
// public user id, which could be returned back to application
private String userId;
private String firstName;
private String lastName;
private String email;
// clear text password
private String password;
// password which is encrypted, stored,
private String encryptedPassword;
private String emailVerificationToken;
private Boolean emailVerificationStatus = false;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEncryptedPassword() {
return encryptedPassword;
}
public void setEncryptedPassword(String encryptedPassword) {
this.encryptedPassword = encryptedPassword;
}
public String getEmailVerificationToken() {
return emailVerificationToken;
}
public void setEmailVerificationToken(String emailVerificationToken) {
this.emailVerificationToken = emailVerificationToken;
}
public Boolean getEmailVerificationStatus() {
return emailVerificationStatus;
}
public void setEmailVerificationStatus(Boolean emailVerificationStatus) {
this.emailVerificationStatus = emailVerificationStatus;
}
}
UserEntity
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity(name = "users")
public class UserEntity implements Serializable {
private static final long serialVersionUID = 5313493413859894403L;
// this Id is a primary key and auto incremented
// once a new record is inserted into database table
#Id
#GeneratedValue
private long id;
#Column(nullable = false)
private String userId;
#Column(nullable = false, length = 50)
private String firstName;
#Column(nullable = false, length = 50)
private String lastName;
#Column(nullable = false, length = 120)
private String email;
#Column(nullable = false)
private String encryptedPassword;
private String emailVerificationToken;
#Column(nullable = false)
private Boolean emailVerificationStatus = false;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getEncryptedPassword() {
return encryptedPassword;
}
public void setEncryptedPassword(String encryptedPassword) {
this.encryptedPassword = encryptedPassword;
}
public String getEmailVerificationToken() {
return emailVerificationToken;
}
public void setEmailVerificationToken(String emailVerificationToken) {
this.emailVerificationToken = emailVerificationToken;
}
public Boolean getEmailVerificationStatus() {
return emailVerificationStatus;
}
public void setEmailVerificationStatus(Boolean emailVerificationStatus) {
this.emailVerificationStatus = emailVerificationStatus;
}
}
UserServiceImpl
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.appsdeveloperblog.app.ws.UserRepository;
import com.appsdeveloperblog.app.ws.io.entity.UserEntity;
import com.appsdeveloperblog.app.ws.service.UserService;
import com.appsdeveloperblog.app.ws.shared.dto.UserDTO;
#Service
public class UserServiceImpl implements UserService {
#Autowired
UserRepository userRepository;
#Override
public UserDTO createUser(UserDTO user) {
// (0) check whether the email already exist in database
if(userRepository.findByEmail(user.getEmail()) != null) {
throw new IllegalArgumentException("Email already exists.");
}
// 1. create an object UserEntity,
UserEntity userEntity = new UserEntity();
// 2. copy info from userDTO to userEntity
BeanUtils.copyProperties(user, userEntity);
// 3. encryptedPassword can't be got from user
// we have to assign value here for testing
userEntity.setEncryptedPassword("test");
// 4. the second data that is generated during this class is userID
userEntity.setUserId("testUserId");
// 5. now we can save userEntity into database,
// since it contains info from user, have to use userRepository
// after Auto-wired, we can use its methods
// use save method, we can save userEntity into database
UserEntity storedUserDetails = userRepository.save(userEntity);
// 6. we can return it back to RestController
// so we need an UserDTO object
UserDTO returnValue = new UserDTO();
BeanUtils.copyProperties(storedUserDetails, returnValue);
return returnValue;
}
}
UserController
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
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.RestController;
import com.appsdeveloperblog.app.ws.service.UserService;
import com.appsdeveloperblog.app.ws.shared.dto.UserDTO;
import com.appsdeveloperblog.app.ws.ui.model.request.UserDetailsRequestModel;
import com.appsdeveloperblog.app.ws.ui.model.response.UserRest;
#RestController // to make this class receive requests from HTTP
#RequestMapping("users") // http://localhost:8080/users + methods
public class UserController {
#Autowired
UserService userService;
#GetMapping
public String getUser() {
return "get user was called";
}
#PostMapping
public UserRest createUser(#RequestBody UserDetailsRequestModel userDetails) {
// 1. instantiate a new object, which will be returned.
UserRest returnValue = new UserRest();
System.out.println(userDetails.getFirstname());
// 2. instantiate a new User Data transfer object,
// which could be shared across different layers
// we will populate this object with info we received from request body
UserDTO userDTO = new UserDTO();
// 3. use class BeanUtils class, which is from spring framework
// to copy properties from source object(userDetails) to our data transfer object
// so, we can populate info from request body into our data transfer object
// so, we have a data transfer object, which is populated info from request body
BeanUtils.copyProperties(userDetails, userDTO);
// 4.
// (1) userDTO, will be created at UI level, then be passed to service layer
// (2) service class will perform some additional business logic
// and generate some additional values, these values will be added to userDTO,
// (3) then userDTO will be used in business logic with a data layer
// to prepare an entity class, which will be stored in database
UserDTO createdUser = userService.createUser(userDTO);
// 5. populate returnValue object
// copy information from createdUser into returnValue
// other sensitive info, like password, should not be included
BeanUtils.copyProperties(createdUser, returnValue);
// 6. return, to mobile applications,or in here to Postman(HTTP client)
return returnValue;
}
#PutMapping
public String updateUser() {
return "update user was called";
}
#DeleteMapping
public String deleteUser() {
return "delete user was called";
}
}
Configuration on Postman
enter image description here
enter image description here
The Error I got
enter image description here
I spent a day on it. Help, please.
Try this:
#PutMapping
public String updateUser(#RequestBody) {
return "update user was called";
}
whenever i am using cartRepository.save(cart) user is again inserted in user table ?(Cart is having a field User).
how not to save the user again?
Users class:
#Entity
#Table(name="users")
public class Users {
#Id
#GeneratedValue
private int id;
#Column(name="nameofuser")
//#UniqueElements
private String nameofuser;
#Column(name="password")
private String password;
#OneToOne(mappedBy="user",cascade = {CascadeType.ALL})
Cart cart;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNameofuser() {
return nameofuser;
}
public void setNameofuser(String nameofuser) {
this.nameofuser = nameofuser;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Cart Entity:
#Entity
#Table(name="cart")
public class Cart {
#Id
#GeneratedValue
#Column(name="id")
int id;
#OneToOne(cascade = CascadeType.ALL)
Users user;
public Users getUser() {
return user;
}
public void setUser(Users user) {
this.user = user;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
CartService class:
package com.praful.lastTry.Services;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.praful.lastTry.MenuRepository.CartRepository;
import com.praful.lastTry.Models.Cart;
import com.praful.lastTry.Models.Users;
#Service
public class CartService {
#Autowired CartRepository cartRepository;
public void bindingWithUser(Users user) {
Cart cart=new Cart();
Users user1=new Users();
cart.setUser(user1);
System.out.println(" from here==================================");
cartRepository.save(cart);
System.out.println("till here ==================================");
}
}
whenever i am using cartRepository.save(cart) user is again inserted in user table
Because of this code :
Users user1=new Users();
Every time you are sending a new user.
Change it to something:
public void bindingWithUser(Users user) {
Cart cart=new Cart();
Users user1= getUser();
cart.setUser(user1);
System.out.println(" from here==================================");
cartRepository.save(cart);
System.out.println("till here ==================================");
}
private Users getUser(){
//return logged in user or your logic to get user which is already there in Database
}
Seems like in your bindingWithUser function you are passing a User object user but inside the function, you are initializing a new User object user1 and setting it to the cart object before saving it
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);
}
}