PropertyAccessException: Error accessing field

2019-07-19 13:44发布

问题:

I have an entity User :

@Entity
public class User implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Long id;

    public Long getId() {
    return id;
}
...}

And I'm trying to remove a user from a task the database with :

@Modifying
@Query("DELETE FROM Collaborator c WHERE c.user = :userId AND c.task = :taskId")
void deleteUserFromTask(@Param("userId") Long userId, @Param("taskId") Long taskId);

and this is the relation between User and Collaborator(the table I'm deleting from) : In User

@JsonIgnore
@OneToMany(mappedBy="user", fetch = FetchType.EAGER)
private Set<Collaborator> collaborators = new HashSet<>(); 

In Collaborator

    @ManyToOne(cascade = {CascadeType.MERGE,
                      CascadeType.DETACH,
                      CascadeType.REFRESH }, 
           fetch = FetchType.EAGER)
@JoinColumn(name = "UserID", nullable = true)
private User user;

but I'm getting this error :

Caused by: org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private java.lang.Long gestionprojet.java.entities.beans.User.id] by reflection for persistent property [gestionprojet.java.entities.beans.User#id] : 1

Hibernate Version : 5.2.6.FINAL

回答1:

You have a mismatch in your parameters i.e you try and specify a Long as the parameter for a User type:

You change it in one of two ways:

@Query("DELETE FROM Collaborator c WHERE c.user.id = :userId AND c.task.id = :taskId")
void deleteUserFromTask(@Param("userId") Long userId, @Param("taskId") Long taskId);

or

@Query("DELETE FROM Collaborator c WHERE c.user = :user AND c.task = :task")
void deleteUserFromTask(@Param("user") User user, @Param("task") Task task);