Home > Mobile >  @GeneratedValue seemingly does not auto-generate when the Entity is being added using a POST Request
@GeneratedValue seemingly does not auto-generate when the Entity is being added using a POST Request

Time:02-20

This is my Entity class (shortened for obvious reasons):
Song.java:

@Entity
@Table(name = "songs", schema = "dbo")
public class Song {
    @Id
    @GeneratedValue
    @Column(name = "song_id")
    private Integer songId;

    // other properties and getter setters not needed for the question
}

Here's my controller (again, shortened for obvious reasons):
SongsController.java:

@RestController
@RequestMapping("/songs")
public class SongsController {
    
    @Autowired
    private SongRepository songs;

    //GET, DELETE and PUT mappings not neeeded for the question

    //POST: adds a new song to the repository
    @PostMapping("/add")
    public void addSong(@RequestBody(required = true) Song song) throws DuplicateItemException {
        if(songs.existsById(song.getSongId())) {
            throw new DuplicateItemException();  //simplest possible custom exception handler imaginable
        }
        songs.save(song);
    }
}

Here's my POST request from POSTMAN:

{
    "songName": "Song3",
    "songDuration": "490"
}

Here's what the function receives:

songName: "Song3"
songDuration: "490"
songId: null

The Exception that gets thrown is "songId cannot be null". How do I fix this?
My database is PostgreSQL (12.10.1).

CodePudding user response:

You need to explicitly add strategy to generated value. Otherwise it will not work. Try this:

@GeneratedValue(strategy = GenerationType.AUTO)

CodePudding user response:

Your @GeneratedValue is missing how to generate the value! Given that you're using PostgreSQL and such RDMS allows the creation of database sequences, I'll suggest the following configuration ... In your Song class, you need to add the @SequenceGenerator annotation and make the following changes:

@Entity
@Table(name = "songs", schema = "dbo")
@SequenceGenerator(
    name         = "<AnyNameThatFitsYou>",
    sequenceName = "<TheNameOfYourDatabaseSequence>",
    initialValue = <DatabaseSeqInitVal>,
    allocationSize = <HowManyOfTheseValuesShouldBeAllocatedInJPAMemoryForFastAccess>
)
public class Song {
    @Id
    @GeneratedValue(
        generator = "<TheNameYouGiveToTheSequenceGenerator>",
        strategy  = GenerationType.SEQUENCE
    )
    @Column(name = "song_id")
    private Integer songId;

    // other properties and getter setters not needed for the question
}

That should be all ...

  • Related