Я пытаюсь вставить postId
в таблицу ресурсов при создании POST
и RESOURCE
. Но, к сожалению, каждый раз я получаю postId
-> null в таблице ресурсов. Ниже приведены подробные сведения о карте гибернации.
Post. java
@Entity
@Table(name = "POST")
@DynamicInsert
@DynamicUpdate
public class Post implements Serializable{
private static final long serialVersionUID = 1L;
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private int id;
@OneToMany(mappedBy = "post", cascade = {CascadeType.MERGE,CascadeType.PERSIST}, orphanRemoval = true,fetch = FetchType.LAZY)
private List<Resource> resources = new ArrayList<>();
//...Getters Setters
}
Ресурс. java
@Entity
@Table(name = "RESOURCE")
@DynamicInsert
@DynamicUpdate
public class Resource implements Serializable{
private static final long serialVersionUID = 1L;
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private int id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="post_id",nullable=false)
private Post post;
...
//Getters Setters
}
PostController. java
@RestController
@RequestMapping("/posts")
public class PostController {
@Autowired
private PostService postService;
@Autowired
private ResourceService resourceService;
@PostMapping("/create")
public ResponseEntity<PostDto> createPost(@Valid @RequestBody Post post) {
Optional<User> userObj = userService.getOne(post.getUser().getId());
//Check whether that user exist and resource null or not.
if (userObj == null || post.getResources().isEmpty())
return ResponseEntity.notFound().build();
post.setUser(userObj.get());
// ----Issue HERE----> TRYING TO SET post id in RESOURCE TABLE.. WHICH IS NOT HAPPENNIG PREVIOUSLY
Iterable<Resource> res = post.getResources();
int id = post.getId();
for(Resource r : res) {
r.setPostFlag("1");
r.setResourceFlag("1");;
}
// -----> Here Post and Resources are saved in database
// But in resource-table post_id is null
post = this.postService.savePost(post);
if (post != null) {
PostDto postDto = modelMapper.map(post, PostDto.class);
return ResponseEntity.ok().body(postDto);
}
return ResponseEntity.notFound().build();
}
}
PostService. java
@Service
public class PostService {
@Autowired
private PostRepository postRepository;
// save Post
public Post savePost(Post post) {
return (Post) this.postRepository.save(post);
}
}
PostRepository. java
public interface PostRepository extends CrudRepository<Post,Integer> { ... }
Объект JSON, который я передаю контроллеру:
{
"location":"NewEnry",
"description":"NoDes",
"state":"Active",
"like":1234,
"user": {"id":4},
"resources":[{
"url":"URL2",
"state":"B1",
"likes":200,
"type":"My Type 1"
},{
"url":"URL3",
"state":"B2",
"likes":100,
"type":"My Type 2"
}
]
}
Может кто-нибудь сообщить мне, что я пропустил или делаю неправильно?