简体   繁体   中英

Null constraint on One to many hibernate

Getting

org.postgresql.util.PSQLException: ERROR: null value in column "tournament_id" violates not-null constraint`

Tournament.java

@Data
@Entity
public class Tournament {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String name;

    @OneToMany(mappedBy = "tournament", cascade = CascadeType.PERSIST)
    private List<Group> groups;}

Groups

@Entity
@Data
@Table(schema = "offan", name = "groups")
public class Group {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @ManyToOne
    @JoinColumn(name = "tournament_id")
    private Tournament tournament;

    public Group(){}
    public Group(Tournament tournament){
       this.tournament = tournament;
    }
}

I'm trying to save both in one go. with CrudRepository . Saving just an tournament instance without any groups works fine. I cannot see why groups aren't inserting tournament_id key correctly

I'm using lombok for getters and setters.

DDL:

CREATE TABLE tournaments (
  id SERIAL PRIMARY KEY,
  name VARCHAR(50) NOT NULL
);

CREATE TABLE groups (
    id SERIAL PRIMARY KEY,
    name VARCHAR(50) ,
    tournament_id INTEGER REFERENCES tournaments (id) NOT NULL ,
    UNIQUE (name, tournament_id)
);

Possible problem

I use Spring @RequestBody which will parse my object into Tournament object, this might not set the mapping correctly?

...Was the problem

Parsing the object using the underlying jackson library did not set up the correct mapping. Doing it manually everything was inserted correctly.

@RequestMapping(value = "/tournaments", method = RequestMethod.POST)
public Tournament createTournament(@RequestBody Tournament tournament){
    //Will not work
    //Tournament savedEntry = tournamentRepository.save(tournament); 
    //

    //Setting properties manually works...
    Tournament t = new Tournament();
    t.setName(tournament.getName());

    Group group = new Group();
    group.setTournament(t);

    t.getGroups().add(group)

    // Both tournament and group are inserted
    t = tournamentRepository.save(t); 

    return t; //Overflow here because of jackson another thing to fix :)
}

I guess you will have to save Tournament entity separately and then set that Tournament in the corresponding Group entity and then save that Group entity separately. (In either case of spring saving group entities or you saving the group entity by mapping corresponding Tournament , the number of insert statement remain the same.)

What's happening here is you are expecting Spring to map each Tournament to Group by calling setters of Group , which is not happening.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM