Annotations are prohibited here
I am creating a UserRepository that implements JpaRepository and works with a User object. I need a method to update the username. I decided to do it with @Query. But he was marked by Intellij. Here is my code for the repository:
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
@Modifying
@Query(value = "update User user set user.name= %?username"))
void updatingUser(@Param(value = "username") String username);
}
And for the object:
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id")
private Long id;
@NotNull
@Column(name = "user_name")
private String username;
}
And I ran into this problem: "Annotations are not allowed here," says Intellij Idea and marks the line with the @Query annotation. And it confused me.
source to share
Using annotation @Query
at this point is absolutely essential. But your request is not entirely correct.
The query parameters can be named - ': name' or indexed - '? 1'.
You must use update queries with a "where" clause, otherwise you will update all records.
The code should look like this:
@Modifying
@Query("update User u set u.name = ?1 where u.name = ?2")
void updateByName(String value, String name);
Or like this:
@Modifying
@Query("update User u set u.name = :value where u.name = :name")
void updateByName(@Param("value") String value, @Param("name") String name);
Please note - while the "name" field is not unique, you will update ALL users with the given name. To update only one user, you must use a unique field or primary key in the "where" clause, for example:
@Modifying
@Query("update User u set u.name = ?1 where u.id = ?2")
void updateById(String value, Long id);
By the way, if you need to update all users who have a specific name pattern, use the "like" operator:
@Modifying
@Query("update User u set u.name = ?1 where u.name like '%'||?2||'%'")
void updateByNameLike(String value, String name);
Useful information:
Spring Data JPA - reference documentation
PS @Repository
No annotations required
source to share
Well I got this problem with the following query after copying from SQLyog.
SELECT id FROM (SELECT * FROM departments ORDER BY id) dpt_sorted, (SELECT @pv := '2') initialisation WHERE FIND_IN_SET(parent_dept, @pv) AND LENGTH(@pv := CONCAT(@pv, ',', id));
But when I typed in the request, the error message disappeared. Maybe, copy
and paste
the issue in my case. This might be helpful.
source to share