Monoxyd
Monoxyd

Reputation: 486

javax.persistence.NonUniqueResultException: query did not return a unique result

I am using Spring Boot with Spring-data-jpa

I have two entities Category and Course. They are associated by @ManyToMany.

  public class Course {
        @Id
        @GeneratedValue(generator = "inc")
        @GenericGenerator(name = "inc", strategy = "increment")
        private int courseId;
        @NotBlank(message = "Add the course's title!")
        private String title;
    
        @ManyToMany(mappedBy = "courses", fetch = FetchType.EAGER)
        private Set<Category> categories;
}

public class Category {
    @Id
    @GeneratedValue(generator = "inc")
    @GenericGenerator(name = "inc", strategy = "increment")
    private int categoryId;
    @NotBlank(message = "category's name must be not empty!")
    private String name;

    @ManyToMany(cascade = CascadeType.PERSIST)
    @JoinTable(
            name="course_category",
            joinColumns = @JoinColumn(name = "category_id"),
            inverseJoinColumns = @JoinColumn(name = "course_id")
    )
    private Set<Course> courses;

When I download one category I want to download all its courses as well ( without fetchType.EAGER because I don't want to get courses while downloading all categories ). This is my overriden query in CategoryRepository (JpaRepository):

    @Override
    @Query("SELECT cat FROM Category cat JOIN FETCH cat.courses")
    Optional<Category> findById(Integer id); 

Since I want to send my client data from two tables, I have created a DTO:

public class CategoryAndCourses {
    private Category category;
    private List<Course> courses;

    public CategoryAndCourses(Category category, List<Course> courses) {
        this.category = category;
        this.courses = courses;
    }

And there is a place where I actually send both the courses and the category by DTO:

public CategoryAndCourses getCourses(int id) {
        var category = repository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("No category with given id"));
            var result = new CategoryAndCourses(category, new ArrayList<>(category.getCourses()));
        return result;
    }

With such a code I get this error: javax.persistence.NonUniqueResultException: query did not return a unique result: 8 How to solve it ?

Upvotes: 0

Views: 7826

Answers (2)

Mugo Lastbon
Mugo Lastbon

Reputation: 1

user List<> in fetching more than one item instead of Optional. Also check your @Query() at the repository; eg

#####List findById(Integer id);#####

Upvotes: -1

Ga&#235;l J
Ga&#235;l J

Reputation: 15115

The error is pretty clear: you have a query returnin more than 1 result and your code is defined as expecting a single result.

Aren't you missing a WHERE on the id on the following query?

@Query("SELECT cat FROM Category cat JOIN FETCH cat.courses")
Optional<Category> findById(Integer id);

Upvotes: 1

Related Questions