Я попытался проверить отношения с одним ко многим для Hibernate. Я определил объекты Post и PostComment, как ниже:
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
}
< /code>
postcomment.java
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
}
< /code>
postrepository.java
public interface PostRepository extends JpaRepository {
}
< /code>
и db-changelog.xml < /strong> < /p>
< /code>
Затем я использовал Springjunit, чтобы добавить новый пост, как в posterviceittest.java < /p>
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);
}
}
< /code>
К сожалению, тест бросает ошибку PostgreSQL, связанную с ограничением нулевого виолата: < /p>
Caused by: org.postgresql.util.PSQLException: ERROR: null value in column "post_id" violates not-null constraint
Detail: Failing row contains (null, Post 1).
< /code>
Я очень ценю ваше время. < /p>
Подробнее здесь: https://stackoverflow.com/questions/423 ... n-using-on