Post.java
Код: Выделить всё
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "post")
public class Post {
@Id
@Column(name="post_id")
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long postId;
@Column(name="title")
private String title;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "post",
orphanRemoval = true)
private List
comments = new ArrayList();
public Post() {};
public Post(String title) {
this.title = title;
}
// Add getter and setter
}
Код: Выделить всё
import javax.persistence.*;
@Entity
@Table(name = "post_comment")
public class PostComment {
@Id
@Column(name="comment_id")
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long commentId;
@Column(name="review")
private String review;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "post_id")
private Post post;
public PostComment() {};
public PostComment(String review) {
this.review = review;
}
// Add getter and setter
}
Код: Выделить всё
public interface PostRepository extends JpaRepository
{
}
Код: Выделить всё
Код: Выделить всё
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import java.util.Arrays;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {Application.class})
@WebAppConfiguration
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
@ActiveProfiles("devmock")
public class PostServiceITTest {
@Autowired
private PostRepository postRepository;
@Test
public void testAddPost(){
Post post = new Post(" Post 1");
PostComment postComment1 = new PostComment(" Post comment 1");
PostComment postComment2 = new PostComment(" Post comment 2");
post.setComments(Arrays.asList(postComment1,postComment2));
postRepository.save(post);
}
}
Код: Выделить всё
Caused by: org.postgresql.util.PSQLException: ERROR: null value in column "post_id" violates not-null constraint
Detail: Failing row contains (null, Post 1).
Подробнее здесь: https://stackoverflow.com/questions/423 ... n-using-on
Мобильная версия