简体   繁体   中英

How to save an Entity with a OneToMany relationship using auto incremented IDs that are related

I am trying to save a "User" object that is related by a OneToMany relationship to a "Volunteer" object.

When I try to save it, it only works when I provide the primary IDs for both these objects. However, what I need is to save the entity and let the database dictate the ID's via autoIncrement. I am not sure how am I suppose to do this or even if it's possible.

Json Mapping that works:

{
    "id":8,
    "userName": "user8",
    "password": "pass1234",
    "volunteersId": 6,
    "volunteers": [{
            "id":6,
            "committeesId": 2,
            "outreachDate": "2019-12-07",
            "usersId": 8
        }]
}

Json Mapping that I need (but will not work):

{
    "userName": "user8",
    "password": "pass1234",
    "volunteersId": 6,
    "volunteers": [{
            "committeesId": 2,
            "outreachDate": "2019-12-07",
        }]
}

So I am thinking maybe there's a way to connect the foreign keys so that I wont have to explicitly add the autoIncrement IDs (usersId, volunteersId).

User controller:

@Controller
public class UserController {
    @RequestMapping(value = "/v1/users", method = RequestMethod.POST)
    public ResponseEntity<Object> saveUsers( @RequestBody UserEntity request){
        try {
            return ResponseEntity.ok(userService.saveUser(request));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }   
    }
}

User service:

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public Page<UserEntity> saveUser(UserEntity user){
        userRepository.save(user);
        Pageable pageable = PageRequest.of(0, 10, Sort.by("id").descending());
        return userRepository.findAll(pageable);
    }
}

User Repository:

public interface UserRepository extends JpaRepository<UserEntity, Long> {
    public List<UserEntity> findAllByOrderByIdAsc();
    public List<UserEntity> findAllByOrderByIdDesc();
    public Page<UserEntity> findByUserNameContaining(String userName, Pageable pageable);
}

User Entity:

@Entity
@Table(name = "users")
public class UserEntity {

    @Id
    private long id;
    @Column(name = "username")
    private String userName;
    private String password;
    @Column(name = "volunteers_id", nullable = true)
    private Long volunteersId;
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "users_id")
    private List<VolunteerEntity> volunteers = new ArrayList<>();

// omitted getters and setters
}

Volunteer Entity:

@Entity
@Table(name = "volunteers")

public class VolunteerEntity {

     @Id
     private long id;
     @Column(name = "committees_id")
     private long committeesId;
     @Column(name = "outreach_date")
     private Date outreachDate;
     @Column(name = "users_id")
     private Long usersId;

// omitted getters and setters
}

Any ideas or suggestions how to save this whole entity? I am wondering if this is really possible to save as in one whole process. Though if not, I am thinking of just saving them independently (User info first, then Volunteer next) but just in case it would be possible, it would really be a great help

You need to add @GeneratedValue anotation next to the @id

@Id
@GeneratedValue(strategy = GenerationType.selectOne)
private long id;

In case of sequence you need to add an extra anotation

@Id
@SequenceGenerator(name = "customName", sequenceName = "sequenceNameInDatabase")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="customName")
private long id;

This will make the primary id generation auto

@Entity
@Table(name = "user")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

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