Skip to content
Advertisement

I can not mapped Model and DTO could not execute statement; SQL [n/a] constraint [null]

This is base person entity it extends baseEntity which has only Id Auto creament

@Setter
@Getter
@Entity
public class Person extends BaseEntity {
    private String username;
    private String firstName;
    private String lastName;

    @ManyToOne(fetch = FetchType.EAGER, optional = false)
    @JoinColumn(name = "location_id")
    private Location location;
}

This is location Entity which also extends base entity

@Setter
@Getter
@Entity
public class Location extends BaseEntity {

    private double lat;
    private double lng;
    private String place;
    private String description;
}

Now I want to save peron entity which includes location table id also

@Data
public class PersonDTO {
    private String username;
    private String firstName;
    private String lastName;
    private Long location;
}

My PostMan Request is below

{
    
    "username":"bulbul",
    "firstName":"Bulbul",
    "lastName":"Ahmed",
    "location":1
}

My Service class is below

 public Person create(PersonDTO personDTO) {
        return this.personRepository.save(convertToPerson2(personDTO));
    }
 private Person convertToPerson2(PersonDTO personDTO) {
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.LOOSE);
        Person person = modelMapper.map(personDTO, Person.class);
        return person;
    }
```
Now I faced a error :: Column 'location_id' cannot be null
 "could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement"

But I have also location table data in database which id is 1. Here Location Id can not map from personDTO 

Advertisement

Answer

This is not the correct way to do this. You are mapping your PersonDTO to the Person class. But their location variable has completely different types. One is a Location and the other a long.

The correct way to do this would be to change the PersonDTO class like this:

public class PersonDTO {
    private String username;
    private String firstName;
    private String lastName;
    private Location location; // Change this to the same type as in the Person class
}

And then, make a postman request this way:

{
    "username":"bulbul",
    "firstName":"Bulbul",
    "lastName":"Ahmed",
    "location":{
          "id": 1 // This part is important, you have an object which has an ID attribute..
     }
}

Make sure that the names and variable types are the same…

Good luck!

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement