Spring Data JpaRepository saveAndFlush not working in @Transactional test method

Using JPA Spring Data I have created a couple of entities Ebook and Review, which are linked by a ManyToOne relationship from Review towards Ebook. I have tried to insert a review for an existent ebook, but the result is not being reflected in the database (Postgres DB), even though I am using a saveAndFlush inside a @Transactional. I retrieve inserted review correctly, it is just that is not saving the record in the table.

Entities:

Ebook:

@Entity
public class Ebook {

    @Id
    @SequenceGenerator(
            name="ebook_sequence",
            sequenceName = "ebook_sequence",
            allocationSize = 1
    )
    @GeneratedValue (
            strategy = GenerationType.SEQUENCE,
            generator ="ebook_sequence"
    )
    private Long idEbook;
    private String title;
}

Review:

@Entity
public class Review {
    @Id
    @SequenceGenerator(
            name="sequence_review",
            sequenceName = "sequence_review",
            allocationSize = 1
    )
    @GeneratedValue(
            strategy = GenerationType.SEQUENCE,
            generator = "sequence_review"
    )
    private Long idReview;
    private String reviewText;

    //ManytoOne Ebook
    @ManyToOne(
            cascade = CascadeType.ALL,
            fetch = FetchType.LAZY
    )
    @JoinColumn(
            name = "id_ebook",
            referencedColumnName = "idEbook"
    )
    private Ebook ebook;
}

And the test in which I am trying to insert just a review corresponding to a preexisting ebook record:

    @Test
    @Transactional
    public void saveReviewWithEbook() {

        Ebook ebook = ebookRepository.getById((long)1);

        Review review = Review.builder()
                .reviewText("review text ebook 1")
                .ebook(ebook)
                .build();

        Review reviewInserted = reviewRepository.saveAndFlush(review); //saveAndFlush(review);
        Review reviewLoaded = reviewRepository.getById(reviewInserted.getIdReview());
        System.out.println("reviewLoaded = " + reviewLoaded);
    }

After executing it, there is no record inserted in table 'review', although data appear correctly in variable 'reviewLoaded'. Why is that? How can I save just a review corresponding to an existing ebook?



from Recent Questions - Stack Overflow https://ift.tt/rWbeniC2N
https://bit.ly/3GblJNq

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation