Home > Software design >  Use enumerations in JPA Query
Use enumerations in JPA Query

Time:11-25

I'm trying to use JPA to update an entity property which is an enumeration in my domain model, and I can't make it work.

I have the following entities:

public class A {

    @Id
    @Column(name = "id")
    private Long id;

    @ManyToOne
    @JoinColumn(name = "status")
    private Status status;

}

public class Status {

    @Id
    @Enumerated(EnumType.STRING)
    @Column(name = "id")
    private StatusId id;

    public enum StatusId {

        B, C, D, E, F

    }

}

and this JPA repository:

public interface ARepository extends JpaRepository<A, Long> {

    @Modifying
    @Transactional
    @Query("UPDATE A SET status = ?2 WHERE id = ?1")
    void updateStatus(Long id, Status.StatusId status);

}

Executing this method throws the following error:

Caused by: java.lang.IllegalArgumentException: Parameter value [B] did not match expected type [com.***.Status (n/a)]

Any ideas on how to solve this?

CodePudding user response:

The error says:

Parameter value [B] did not match expected type [com.***.Status

and in your query you are effectively trying to assign an object of type Status.StatusId to a field of type Status

You should try to change the query to something like this:

UPDATE A SET status.id = ?2 WHERE id = ?1

  • Related