Search code examples
javahibernatejpaquarkusquarkus-panache

How to clear database table for embeddable type in Quarkus test


I need to clear the tables of my database in a Quarkus application. I am able to achieve this for Entities extending either PanacheEntity or PanacheEntityBase by calling entity.deleteAll(). How can I clear table for embeddable types?


Solution

  • So I was able to fix the issue myself and here's what I did:

    1. Inject an EntityManager instance
    2. In the clean up method (tearDown() in my case), I wrote and executed a native query to clear my table "course_description". Note: I have an entity Course and an embeddable CourseDescription. CourseDescription is embedded in Course Example:
    @Embedded
    @ElementCollection
    public List<CourseDescription> courseDescriptions;
    

    My Test Class:

        @PersistenceContext
        EntityManager entityManager;
    

    ...

        @AfterEach
        @Transactional
        public void tearDown(){
            Query query = entityManager.createNativeQuery("DELETE FROM course_description")
                    .setHint(COMMENT, "Custom cleanup for embeddable type CourseDescription");
            query.executeUpdate();
            Course.deleteAll();
        }
    

    Update: I could have simply set CourseDescription to null and let JPA take care of the cleanup.

        @AfterEach
        @Transactional
        public void tearDown(){
            Course.findAll().stream()
                    .forEach(course -> {
                        Course c = (Course) course;
                        c.courseDescription = null;
                    });
        }