Ricardo Ricardo - 1 year ago 68
Java Question

Java repository - Spring Data JPA

I'm doing a dummy project in spring to remember old skills. I've implemented the following Repository.

User Repository

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

User findByUuid(String uuid);

User findByEmail(String email);

@Override
List<User> findAll();
}


User Entity with getters and setters, removed for clarity

@NamedQueries({
@NamedQuery(name = "User.findByEmail", query = "SELECT u FROM User u WHERE u.email = :email")})
public class User implements Serializable {

private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(nullable = false)
private Long id;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 64)
@Column(nullable = false, length = 64)
private String uuid;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 128)
@Column(nullable = false, length = 128)
private String username;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 128)
@Column(nullable = false, length = 128)
private String email;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 64)
@Column(nullable = false, length = 64)
private String password;
}


After run the project and using the query
findByEmail
I'm getting the following error:


java.lang.IllegalArgumentException: Parameter with that position [1]
did not exist


So, I've searched for some possible solutions for my problem and actually found one. Replacing the query for:

User findByEmail(@Param("email") String email);


This is not my first attempt on spring and I've developed some minor projects using this framework, and I've used the normal approach without any problems. I've read the documentation trying to find an explanation for this but I didn't manage to find any.


  • Can someone explain to me why my first attempt didn't work?


Answer Source

Please see the following jira ticket DATAJPA-733

From Oliver Gierke

You can only use named parameters in your query if you either use Java 8 with -parameters enabled for compilation or use @Param annotations on the query method arguments as documented in the reference documentation. The reason for the required annotation is that prior to Java 8 there was no way to retain the variable names in the code for interface methods.

The workaround provided is to delete the named query

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download