Angular 5 + Spring Boot post method doesn't work - java

I use Angular 5 + Spring Boot. The problem is that I can not send information to my rest controller by post method.
I do not get any error either from the client side or from the server side.
Below the code you will see that I make get method which works correctly.
Let me apologize for my Еnglish.
Spring Entity { Dish }
#Entity
#Table(name = "DISHES")
#Data
public class Dish implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ID")
private Long id;
#Column(name = "NAME", unique = true)
#NotNull(message = "Ястието трябва да има име.")
#Size(min = 3, max = 30, message = "Името на ястието трябва да е между 3 и 30 символа.")
private String name;
#Column(name = "DESCRIPTION")
#NotNull(message = "Описанието на ястието не може да е празно.")
#Size(min = 3, max = 300, message = "Описанието на ястието трябва да е между 3 и 30 символа.")
private String description;
#JsonIgnore
#OneToMany(cascade = CascadeType.ALL ,mappedBy = "dish")
#JsonBackReference
private List<DishCounter> dishCounters;
}
Angular Entity {Dish}
export class Dish {
constructor(public id?: number, public name?: string, public description?: string) {
}
}
Spring Rest Controller {Dish}
#CrossOrigin(origins = "http://localhost:4200")
#RestController
#RequestMapping("/dish")
public class DishRestController {
private static final Logger logger = LoggerFactory.getLogger(DishRestController.class);
private final DishService dishService;
#Autowired
public DishRestController(final DishService dishService) {
this.dishService = dishService;
}
#GetMapping("/all")
public ResponseEntity<List<Dish>> getAllDishes() {
logger.info("Rest controller find all dishes");
List<Dish> dishes = dishService.getAllDishes();
return ResponseEntity.status(HttpStatus.OK).body(dishes);
}
#PostMapping("/save")
public ResponseEntity<Void> saveDish(#RequestBody Dish dish) {
dishService.saveDish(dish);
return new ResponseEntity<>(HttpStatus.OK);
}
}
And Angular post Method
save(dish: Dish): Observable<Dish> {
let result: Observable<Dish>;
result = this.http.post(this.saveDishUrl, dish)
.map((resp => {
console.log(resp);
return resp;
}))
.catch(e => {
console.log(e);
return Observable.throw(e);
});
console.log(result);
return result;
}

Where are you calling subscribe on the post function? I don't see it here. As http post returns an observable, you must subscribe to it to make the call.
http.post(....).subscribe(response => <DO SOMETHING WITH IT>);

This might not be all of the errors on your code but this is something I noticed.
Your Java #PostMapping doesn't specify what it should be expected to receive and what it should produce in return.
#PostMapping(value = "save", consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
For Angular 5, you're using Angular 4 service Syntax, I thought they changed that on 5.

Related

repoistory.save() getting invoked with invalid entry when unit testing

I'm using java validation API to validate fields in my Note class:
#Entity
#Data
#NoArgsConstructor
#AllArgsConstructor
#Table(name = "note")
public class Note {
#Id
#Column(name = "id", nullable = false)
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "date", columnDefinition = "DATE")
private LocalDate date;
#NotBlank(message = "Enter a topic")
#Column(name = "topic")
private String topic;
#NotBlank(message = "Content can't be empty")
#Column(name = "content")
private String content;
#Column(name = "type")
private NoteType noteType;
#NotNull
#ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
#JoinColumn(name = "user_id")
#JsonIgnore
private User user;
}
NoteService:
#Service
#AllArgsConstructor
public class NoteService {
#Autowired
private NoteRepository noteRepository;
#Autowired
private UserRepository userRepository;
public void addNote(#Valid Note note) {
note.setUser(getLoggedInUser());
if (validateNote(note)) {
noteRepository.save(note);
}
}
public List<Note> getNotes() {
return getLoggedInUser().getNotes();
}
public Note editNote(Note newNote, Long id) {
noteRepository.editNoteById(newNote, id);
return newNote;
}
public List<Note> getNotesByTopic(String topic) {
List<Note> notes = noteRepository.getNotesByTopicAndUser(topic, getLoggedInUser());
return notes;
}
public boolean validateNote(Note note) {
return validateNoteType(note.getNoteType())
&& note.getDate() != null;
}
public boolean validateNoteType(NoteType type) {
return type.equals(NoteType.NOTE)
|| type.equals(NoteType.SKILL);
}
public User getLoggedInUser() {
return userRepository.findByEmail(SecurityContextHolder.getContext().getAuthentication().getName());
}
}
Test:
#ExtendWith(MockitoExtension.class)
#ExtendWith(SpringExtension.class)
class NoteServiceTest {
#Mock
private NoteRepository noteRepositoryMock;
#Mock
private UserRepository userRepositoryMock;
#Mock
SecurityContext mockSecurityContext;
#Mock
Authentication authentication;
private NoteService noteService;
#BeforeEach
void setUp() {
noteService = new NoteService(noteRepositoryMock, userRepositoryMock);
Mockito.when(mockSecurityContext.getAuthentication()).thenReturn(authentication);
SecurityContextHolder.setContext(mockSecurityContext);
}
#Test
void shouldAddNote() {
LocalDate date = LocalDate.now();
Note note = new Note(0L, date, "test", "", NoteType.NOTE, null);
noteService.addNote(note);
Mockito.verify(noteRepositoryMock).save(note);
}
}
The field user in the Note class is annotated with #NotNull and I'm passing a null user to this note but the note is still getting saved. Same thing when I pass an empty string. Any idea why that is happening? I'm new to unit testing
I'm new to unit testing - your perfectly valid question has nothing to do with unit testing.
#NotNull does nothing on it own. Its actually a contract stating the following:
A data member (or anything else annotated with #NotNull like local variables, and parameters) can't be should not be null.
For example, instead of this:
/**
* #param obj should not be null
*/
public void MyShinyMethod(Object obj)
{
// Some code goes here.
}
You can write this:
public void MyShinyMethod(#NotNull Object obj)
{
// Some code goes here.
}
P.S.
It is usually appropriate to use some kind of annotation processor at compile time, or something that processes it at runtime. But I don't really know much about annotation processing. But I am sure Google knows :-)
You need to activate validation on you service class with the #Validated annotation so the validation of parameters kicks in.
#Service
#AllArgsConstructor
#Validated
public class NoteService {
...
See Spring #Validated in service layer and Spring Boot: How to test a service in JUnit with #Validated annotation? for more details.
If for some reason you need to manually perform the validation you can always do something like this:
#Component
public class MyValidationImpl {
private final LocalValidatorFactoryBean validator;
public MyValidationImpl (LocalValidatorFactoryBean validator) {
this.validator = validator;
}
public void validate(Object o) {
Set<ConstraintViolation<Object>> set = validator.validate(o);
if (!set.isEmpty()) {
throw new IllegalArgumentException(
set.stream().map(x -> String.join(" ", x.getPropertyPath().toString(), x.getMessage())).collect(
Collectors.joining("\n\t")));
}
}
}
So your noteRepository is Mocked, so you it's not actually calling save on your repository.
Mockito.verify(noteRepositoryMock).save(note);
All you are verifying here is that a call to save is made, not that it was successful.

java spring boot Entity constructor with arguments does not execute

i do not understand why an Entity no argument constructor is being called when providing a request body? if i delete it and the only constructor that exist is the one that receive arguments, i get the expected output print, but i must implement a no argument constructor in order to save the Entity in the database.
this is the request body:
{
"str": "stringgg",
"intt": 2,
"doublee": 1.003
}
this is the route: when commenting out the empty constructor, the values of the new instance match the request json body
#PostMapping("/save")
public List<Modell> obj(#RequestBody Modell model) {
modelRepository.save(model);
System.out.println(model.toString());
return modelRepository.findAll();
}
this is the entity class:
#Table(name = "modelltbl")
#Entity
public class Modell {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
#Column(name = "id", nullable = false)
private long id;
#Column(name = "str", nullable = true)
private String str;
#Column(name = "intt", nullable = true)
private int intt;
#Column(name = "doublee", nullable = true)
private double doublee;
public Modell(String str, int intt, double doublee)
{
this.str = str;
this.intt = intt;
this.doublee = doublee;
}
public Modell(){}
#Override
public String toString()
{
return String.format("model class,params: %s , %o , %f ", str , intt, doublee);
}
}
First of all: Do not use entities iat controller level. It is bad application Design.
The json will be converted throug jackson library which creates the object by calling the default constructor and the setter of the properties. If you do not want this behavior you can use the #JsonCreator annotation.
#JsonCreator
public Modell(#JsonProperty("str")String str, #JsonProperty("intt")int intt, #JsonProperty("doublee")double doublee)
{
this.str = str;
this.intt = intt;
this.doublee = doublee;
}

JAVA / SPRING JPA : Not returning dependence at creation

First, I apologize if my english is unclear ; I am french.
I also am a very junior developer, and this is my first real personal project with no tutorial or whatsoever.
I am having some trouble with my Rest api.
I use java 11 and Spring/JPA
I have two DO classes that each represent a table in the database : Artist and Country.
An artist can have several nationalities, and a country can have several artist born in it.
So that means : many to many.
I joined them with an Association table ; ArtistNationality, that is also a class.
I know I could do without an additional class but, since in my app some relations also have some extra-fields (like the year of an award) I decided that all many to many relationships would be materialized the same way, by "join"classes (sorry I really have an hard time to explain in english)
When I create an Artist, I want my response json to contain the created artist with all its nationalities. But it always comes null.
The creation works fine. But here is the response :
What is odd is the results of my API call.
Here is the result of POST method :
{
"artistFirstName": "OH",
"artistLastName": "Test",
"artistBiography": "Je suis un test.",
"artistBirthDate": "1380-11-10",
"artistDeathDate": "1500-11-12",
"artistNationalities": [],
"artist_ID": 3
}
As you can see, nationalities come null, always.
What is expected, is the same as when I do a find or findall :
{
"artistFirstName": "OH",
"artistLastName": "Test",
"artistBiography": "Je suis un test.",
"artistBirthDate": "1380-11-10",
"artistDeathDate": "1500-11-12",
"artistNationalities": [
{
"nationality": {
"countryId": 1,
"countryName": "Andorre",
"countryShortCode": "AD",
"countryFlagFileName": "ad_16.png"
},
"nationalityId": 5
},
{
"nationality": {
"countryId": 12,
"countryName": "Autriche",
"countryShortCode": "AT",
"countryFlagFileName": "at_16.png"
},
"nationalityId": 6
}
],
"artist_ID": 3
}
What I don't understand is that my save method returns the result of a "find" method so why isn't it the same ?? Find and findall work perfectly, and the insertion also works fine.
Here are the DataObject classes, I shortened them to leave only the fields related to question but of course they all come with their constructors and getters/setter stuff :
Artist class :
#Entity
#Table(name = "artist")
public class Artist implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id_artist")
private final Integer ARTIST_ID;
#OneToMany(targetEntity = ArtistNationality.class, mappedBy = "artistIdAsForeignKey", cascade = CascadeType.ALL)
#JsonManagedReference
private List<ArtistNationality> artistNationalities;
Artist DTO
public class ArtistDto {
private final Integer ARTIST_ID;
private String artistFirstName;
private String artistLastName;
private String artistBiography;
private String artistBirthDate;
private String artistDeathDate;
private List<NationalityDto> artistNationalities;
Country class :
#Entity
#Table(name = "country")
public class Country implements Serializable {
#Id
#Column(name = "id_country")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private final Integer COUNTRY_ID;
#OneToMany(targetEntity = ArtistNationality.class, mappedBy = "countryIdAsForeignKey", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JsonBackReference
private List<ArtistNationality> artistsComingFromCountry;
** COUNTRY DTO **
public class CountryDto {
private int countryId;
private String countryName;
private String countryShortCode;
private String countryFlagFileName;
ArtistNationality class :
#Entity
#Table(name="artist_x_nationality")
public class ArtistNationality implements Serializable {
#Id
#GeneratedValue
#Column(name="id_nationality")
private final Integer NATIONALITY_ID;
#ManyToOne (fetch = FetchType.LAZY)
#JsonBackReference
#JoinColumn(name= "fk_nationality_to_artist")
private Artist artistIdAsForeignKey;
#ManyToOne (fetch = FetchType.LAZY)
#JsonBackReference
#JoinColumn(name="fk_nationality_to_country")
private Country countryIdAsForeignKey;
Nationality Dto:
public class NationalityDto {
private final Integer NATIONALITY_ID;
private CountryDto nationality;
ArtistService :
#Service
public class ArtistServiceImpl implements IArtistService {
#Autowired
private IArtistDao artistDao;
#Autowired
private IArtistDoDtoMapper mapper;
#Autowired
private IArtistValidator validator;
#Autowired
private IArtistNationalityDao nationalityDao;
#Override
#Transactional(readOnly = true)
public List<ArtistDto> findAll() {
List<ArtistDto> resultList = new ArrayList<ArtistDto>();
List<Artist> artistsFromDatabase = artistDao.findAll();
if (artistsFromDatabase != null && !artistsFromDatabase.isEmpty()) {
resultList = mapper.mapDoListToDto(artistsFromDatabase);
}
return resultList;
}
#Override
#Transactional(readOnly = true)
public ArtistDto find(final int id) {
Optional<Artist> optArtistFromDatabase = artistDao.findById(id);
if (!optArtistFromDatabase.isPresent()) {
throw new ResourceNotFoundException();
}
Artist artistFromDatabase = optArtistFromDatabase.get();
ArtistDto result = mapper.mapDoToDto(artistFromDatabase);
return result;
}
#Override
#Transactional(rollbackFor = Exception.class)
public ArtistDto save(final ArtistDto objDto) {
if(validator.isValidForDatabase(objDto)){
//Save without nationalities (mapper does not map it);
Artist artistToSave = mapper.mapDtoToDo(objDto);
int artistId = artistDao.save(artistToSave).ARTIST_ID();
//Add the id of the artist to all his nationalities, then save the nationalities
for (NationalityDto nationality : objDto.getArtistNationalities()){
ArtistNationality doNationality = new ArtistNationality(nationality.getNationalityId());
doNationality.setArtistIdAsForeignKey(new Artist(artistId));
doNationality.setCountryIdAsForeignKey(new Country(nationality.getNationality().getCountryId()));
nationalityDao.save(doNationality);
}
ArtistDto returnArtist = this.find(artistId);
return returnArtist;
}
throw new InsertionException("Invalid object. Could not insert into database.");
}
Mappers :
#Override
#Transactional(rollbackFor = Exception.class)
public ArtistDto mapDoToDto(final Artist pDataObject) {
ArtistDto artistDto = new ArtistDto(pDataObject.ARTIST_ID());
if (artistValidator.isNotNullAndNotEmpty(pDataObject.getArtistFirstName())) {
artistDto.setArtistFirstName(pDataObject.getArtistFirstName());
}
if (artistValidator.isOptionPresent(pDataObject.getArtistLastName())) {
artistDto.setArtistLastName(pDataObject.getArtistLastName());
}
if (artistValidator.isOptionPresent(pDataObject.getArtistBiography())) {
artistDto.setArtistBiography(pDataObject.getArtistBiography());
}
if (artistValidator.isOptionPresent(pDataObject.getArtistBirthDate())) {
artistDto.setArtistBirthDate(pDataObject.getArtistBirthDate());
}
if (artistValidator.isOptionPresent(pDataObject.getArtistDeathDate())) {
artistDto.setArtistDeathDate(pDataObject.getArtistDeathDate());
}
List<NationalityDto> artistNationalities = new ArrayList<NationalityDto>();
if (artistValidator.isOptionPresent(pDataObject.getArtistNationalities())) {
System.out.println("yes, we're in !");
for (ArtistNationality nationality : pDataObject.getArtistNationalities()) {
NationalityDto nDto = new NationalityDto(nationality.getNationalityId());
CountryDto cDto = countryMapper.mapDoToDto(nationality.getCountryIdAsForeignKey());
nDto.setNationality(cDto);
artistNationalities.add(nDto);
}
}
artistDto.setArtistNationalities(artistNationalities);
return artistDto;
}
/**
* Note : we add nationality separately since we do not have Artist's ID yet.
*/
#Override
#Transactional(rollbackFor = Exception.class)
public Artist mapDtoToDo(final ArtistDto pDataTransfertObject) {
System.out.println(pDataTransfertObject.toString());
Artist artist = new Artist(pDataTransfertObject.getARTIST_ID());
if (artistValidator.isNotNullAndNotEmpty(pDataTransfertObject.getArtistFirstName())) {
artist.setArtistFirstName(pDataTransfertObject.getArtistFirstName());
}
if (artistValidator.isOptionPresent(pDataTransfertObject.getArtistLastName())) {
artist.setArtistLastName(pDataTransfertObject.getArtistLastName());
}
if (artistValidator.isOptionPresent(pDataTransfertObject.getArtistBiography())) {
artist.setArtistBiography(pDataTransfertObject.getArtistBiography());
}
if (artistValidator.isOptionPresent(pDataTransfertObject.getArtistBirthDate())) {
artist.setArtistBirthDate(pDataTransfertObject.getArtistBirthDate());
}
if (artistValidator.isOptionPresent(pDataTransfertObject.getArtistDeathDate())) {
artist.setArtistDeathDate(pDataTransfertObject.getArtistDeathDate());
}
return artist;
}
This is the Json I send to my controller :
{
"ARTIST_ID" : null,
"artistFirstName":"OH",
"artistLastName":"Test",
"artistBiography":"Je suis un test.",
"artistBirthDate":"1380-11-10",
"artistDeathDate": "1500-11-12",
"artistNationalities": [{
"nationality": {
"countryId" : 1
}
},
{"nationality":{
"countryId": 12
}
}
]
}
I also had to find a trick to save nationalities after artist because when I sent nationalities to database, jpa did not automatically add the saved artist to the nationality and the nationality was saved only with the country data, as you can see in the save method and the dto to do mapper.
I am sorry if it is not really clear, I do my best in english, thank you for understanding.
If your find and findAll is working then, you should be able to override return from save and use find jpa method using the artist id returned by save in your service layer that way you will have a complete json to return.

How to send only the ID the of main nested objects in the body request in spring boot

I'm creating eCommerce for merchants using spring boot with JPA.
I have an issue while creating the order service.
I want to only pass the ID of the nested objects in the request body instead of sending the full nest objects because the size will be extremely big.
Here is my code.
Merchant can do many orders
Order
#Entity
#Table(name = "Orders")
#XmlRootElement
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Order extends BasicModelWithIDInt {
#Basic(optional = false)
#Column(name = "Quantity")
private Integer quantity;
#Basic(optional = false)
#Size(min = 1, max = 150)
#Column(name = "Notes")
private String notes;
#JoinColumn(name = "ProductID", referencedColumnName = "ID")
#ManyToOne(optional = false, fetch = FetchType.LAZY)
#JsonIgnoreProperties
private Product productID;
#JoinColumn(name = "MerchantID", referencedColumnName = "ID")
#ManyToOne(optional = false, fetch = FetchType.LAZY)
private Merchent merchent;
#JoinColumn(name = "OrderSatusID", referencedColumnName = "ID")
#ManyToOne(optional = false, fetch = FetchType.EAGER)
private OrderStatus orderStatus;
// Getters and Setters
}
Order Holder
public class OrderHolder {
#NotNull
private Order order;
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this.order = order;
}
}
OrderRepo
public interface OrderRepo extends JpaRepository<Order, Integer> {
}
Order Controller
#RestController
#RequestMapping(value = "order", produces = MediaType.APPLICATION_JSON_VALUE)
public class OrderRestController extends BasicController<OrderHolder>{
#Autowired
private OrderRepo orderRepo;
#PostMapping("create")
public ResponseEntity<?> create(#RequestBody #Valid OrderHolder orderHolder, Principal principal) throws GeneralException {
log.debug( "create order {} requested", orderHolder.toString());
Order order = new Order();
order = orderHolder.getOrder();
System.out.println("###############"+order);
try {
order = orderRepo.save(order);
log.info( "Order {} has been created", order );
} catch (Exception e) {
log.error( "Error creating Order: ", e );
e.printStackTrace();
throw new GeneralException( Errors.ORDER_CREATION_FAILURE, e.toString() );
}
return ResponseEntity.ok( order );
}
}
I need request body to look like the below instead of including the full Merchant and Product objects inside the request.
You can make use of JsonView to return only id of product and merchant
public class OrderView {}
...
public class Product{
#Id
#JsonView(OrderView.class)
private Integer id
private String otherFieldWithoutJsonView
...
}
and then in your controller
#PostMapping("create")
#JsonView(OrderView.class) // this will return the product object with one field (id)
public ResponseEntity<?> create(#RequestBody #Valid OrderHolder orderHolder, Principal principal) throws GeneralException {
...
}
hope this can help you
Just have a separate contract class.
public class OrderContract {
private int merchantID;
private String notes;
....
//getter, setters
}
public class OrderHolder {
#NotNull
private OrderContract orderContract;
public OrderContract getOrderContract() {
return orderContract;
}
public void setOrder(OrderContract orderContract) {
this.orderContract = orderContract;
}
}
And before making a call to the Repository , translate from OrderContract to Order.
I would like to share something regarding this.
I have searched a lot on internet and tried lot of things, but the solution given here suited well for this scenario.
https://www.baeldung.com/jackson-deserialization
You need to create a Custom-deserializer for your model by extending StdDeserializer from com.fasterxml.jackson.databind.deser.std.StdDeserializer, where you just want to pass id's and not the whole object in the request.
I have given below example for User Model with Address object.
User(long userId, String name, Address addressId)
Address(long addressId, String wholeAddress)
Writing Deserializer for User class
public class UserDeserializer extends StdDeserializer<User> {
public User() {
this(null);
}
public User Deserializer(Class<?> vc) {
super(vc);
}
#Override
public User deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JacksonException {
JsonNode node = p.getCodec().readTree(p);
long id = 0;
long addressId = (Long) ((IntNode) node.get("addressId")).numberValue().longValue();
return new User(id, name, new Address(addressId, null)
}
Now you have to use
#JsonDeserialize(using = UserDeserializer.class)
public Class User {
...
}
POST request
Before custom deserialization
{
"name" : "Ravi",
"addressId" : { "id" : 1}
}
After custom Deserialization
{
"name" : "Ravi",
"addressId" : 1
}
Also while GET /user/:id call you will get the whole obj like
{
"name" : "Ravi",
"addressId" : { "id" : 1, "wholeAddress" : "Some address"}
}

Do not update not specified fields in Entity with Spring JPA

I am creating an application with REST API so one of the endpoints is to create and another to update. My issue comes when I try to update the entity it updates the fields I added in the creation but not in the update.
I am trying with #DynamicUpdate and #SelectBeforeUpdate and it still follows the same behaviour.
Controller
#RestController
#RequestMapping("/v01")
#Slf4j
public class ProjectController {
#Autowired
private ProjectServiceIface projectService;
#PostMapping(path = "/project", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Project> createProject(#Valid #RequestBody Project project, BindingResult result){
if(result.hasErrors()){
throw new BusinessServiceException(result.getFieldError().getDefaultMessage(), result.getFieldError().getField() + " " + result.getFieldError().getCode());
}
Project projectSaved = projectService.createProject(project);
HttpHeaders headers = new HttpHeaders();
headers.add("Location", projectSaved.getId().toString());
return new ResponseEntity<>(project, headers, HttpStatus.CREATED);
}
#PatchMapping(path = "/project", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Project> updateProject(#Valid #RequestBody Project project, BindingResult result){
if(result.hasErrors()){
throw new BusinessServiceException(result.getFieldError().getDefaultMessage(), result.getFieldError().getField() + " " + result.getFieldError().getCode());
}
Project projectUpdated = projectService.updateProject(project);
if(projectUpdated == null) {
return new ResponseEntity<>(null, new HttpHeaders(), HttpStatus.NOT_FOUND);
}
HttpHeaders headers = new HttpHeaders();
headers.add("Location", projectUpdated.getId().toString());
return new ResponseEntity<>(projectUpdated, headers, HttpStatus.CREATED);
}
}
Service
#Service
public class ProjectServiceImpl implements ProjectServiceIface {
#Autowired
private ProjectRepository projectRepository;
#Autowired
private ProjectRepository projectRepository;
#Override
public Project createProject(Project project) {
Project projectFound = projectRepository.findByName(project.getName());
if(projectFound != null){
throw new BusinessServiceException(Constants.FUNCTIONAL_ERROR, "The Project already exists");
}
project.setCreateTime(new Date());
Project projectSaved = projectRepository.save(project);
return projectSaved;
}
#Override
public Project findProjectById(String id) {
Project projectFound = null;
if(!StringUtils.isNumeric(id)){
throw new BusinessServiceException(Constants.FUNCTIONAL_ERROR, "The ID is not in a correct format");
}
Optional<Project> projectOptional = projectRepository.findById(Integer.valueOf(id));
if(projectOptional.isPresent()){
projectFound = projectOptional.get();
}
return projectFound;
}
#Override
public Project updateProject(Project project) {
Project projectUpdated = null;
Optional<Project> projectFound = projectRepository.findById(project.getId());
if(projectFound.isPresent()){
project.setUpdateTime(new Date());
//Project projectMapped = EntityMapper.projectMapper(project);
projectUpdated = projectRepository.save(project);
}
return projectUpdated;
}
#Override
public Project findProjectByName(String projectName) {
Project project = projectRepository.findByName(projectName);
return project;
}
}
Repository
public interface ProjectRepository extends CrudRepository<Project, Integer> {
#Query(value = "SELECT * FROM project p WHERE p.name = :projectName", nativeQuery = true)
Project findByName(String projectName);
}
Project (Entity)
#Entity
#Data
#DynamicUpdate
#SelectBeforeUpdate
#Table(name = "project")
public class Project implements Serializable {
private static final long serialVersionUID = -6163778458602900643L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#NotEmpty
private String name;
#NotEmpty
private String tag;
private String icon;
#Column(name = "create_user", updatable = false)
private String createUser;
#Column(name = "update_user")
private String updateUser;
#Column(name = "create_time", updatable = false)
private Date createTime;
#Column(name = "update_time")
private Date updateTime;
}
This is the request I use for creating:
{
"name" : "Test12",
"tag" : "TST",
"icon" : "/var/usr"
}
The response I obtain:
{
"id": 5,
"name": "Test12",
"tag": "TST",
"icon": "/var/usr",
"createUser": null,
"updateUser": null,
"createTime": "2020-01-24T22:33:48.499+0000",
"updateTime": null
}
And this is the request I perform to update:
{
"id": 5,
"name": "Test5",
"tag": "AAA"
}
The response I obtain:
{
"id": 5,
"name": "Test67",
"tag": "AAA",
"icon": null,
"createUser": null,
"updateUser": null,
"createTime": null,
"updateTime": "2020-01-24T22:44:50.914+0000"
}
As you can see both icon and createTime have been set to null. I only want to be updated specifically the fields I send in the request/entity.
You can use Spring Data Rests Patch method, or explicitly call merge on EntityManager
it would be helpful if you share the code that you are trying to insert/update
for creation time remove updatable = false in entity class
Issue is you are not getting the values for Project from database ..you are checking in DB if the value exists but saving the values sent in json in Project Json icon is not there
fix is you need to get the values based on ID and set the values again which are going to be changed..this way old values willl be retrieved and new values will be updated

Categories