如何使用相关的自动递增ID保存具有OneToMany关系的实体

时间:2019-05-30 13:25:52

标签: java hibernate spring-boot jpa

我正在尝试保存与OneToMany关系与“志愿者”对象相关的“用户”对象。

当我尝试保存它时,仅当我为这两个对象提供主要ID时,它才起作用。但是,我需要保存实体,并让数据库通过autoIncrement指示ID。我不确定应该怎么做,甚至可能。

有效的Json映射:

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

我需要(但无法使用)的Json Mapping:

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

所以我在想,也许有一种方法可以连接外键,这样我就不必显式添加autoIncrement ID(usersId,自愿者ID)。

用户控制器:

@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();
        }   
    }
}

用户服务:

@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);
    }
}

用户存储库:

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

用户实体:

@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
}

志愿者实体:

@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
}

任何想法或建议如何保存整个实体?我想知道是否真的有可能将其保存为一个完整的过程。虽然没有,但我想只保存它们(首先保存用户信息,然后保存志愿者),但以防万一,这确实有很大帮助

2 个答案:

答案 0 :(得分:0)

您需要在@id旁边添加@GeneratedValue注释

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

如果是序列,则需要添加一个额外的注释

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

答案 1 :(得分:0)

这将使主要ID自动生成

@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;