简体   繁体   English

在 JpaRepository function 'findby...' 中使用我自己的值名称创建 bean 时出错

[英]Error creating bean with my own value name in JpaRepository function 'findby...'

Springboot hibernate ORM弹簧启动 hibernate ORM

First, I am using the springboot 2.5.12 version, and I tried to implement the login function in my project.首先,我使用的是springboot 2.5.12版本,我尝试在我的项目中实现登录function。

I declared the email and password as 'uEmail' and 'uPassword' among the variables of User Entity in the User layer that I created for login.我在为登录创建的用户层中的用户实体变量中将 email 和密码声明为“uEmail”和“uPassword”。 After writing the code and building it, I saw an error that I couldn't create bean.写好代码建好后,看到无法创建bean的错误。 When I looked at it, I found an error in the findByEmailAndPassword function in the JpaRepository library.看的时候发现JpaRepository库中的findByEmailAndPassword function 报错。

The error statement is as follows:报错说明如下:

Error creating bean with name 'userController': 
Unsatisfied dependency expressed through field 'userService'; 
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: 
Error creating bean with name 'userService': 
Unsatisfied dependency expressed through field 'userRepository'; 
nested exception is org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'userRepository' defined in com.lululala.peopleofwork.persistance.UserRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: 
Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract com.lululala.peopleofwork.model.UserEntity com.lululala.peopleofwork.persistance.UserRepository.findByEmailAndPassword(java.lang.String,java.lang.String)! 
Reason: Failed to create query for method public abstract com.lululala.peopleofwork.model.UserEntity com.lululala.peopleofwork.persistance.UserRepository.findByEmailAndPassword(java.lang.String,java.lang.String)! 
No property email found for type UserEntity! Did you mean 'uEmail','UEmail'?; 
nested exception is java.lang.IllegalArgumentException: 
Failed to create query for method public abstract com.lululala.peopleofwork.model.UserEntity com.lululala.peopleofwork.persistance.UserRepository.findByEmailAndPassword(java.lang.String,java.lang.String)! 
No property email found for type UserEntity! Did you mean 'uEmail','UEmail'?

At first, I was wondering if there was a problem with the variable being written in CamelCase, so I changed the variable to SnakeCase, but the same error came out.一开始我在想是不是变量写成CamelCase有问题,于是把变量改成SnakeCase,结果还是一样的错误。

Below is my code.下面是我的代码。

UserEntity.java用户实体.java

@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(uniqueConstraints = {@UniqueConstraint(columnNames = "uEmail")})

public class UserEntity {
    @Id
    @GeneratedValue(generator="system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "uuid")
    private String id; // Unique id granted to user
    
    @Column(nullable = false)
    private String uName; // User name

    @Column(nullable = false)
    private String uEmail; // User email(Id)
    
    @Column(nullable = false)
    private String uPassword; // User password
    
}

UserService.java用户服务.java

@Slf4j
@Service
public class UserService {
    
    @Autowired
    private UserRepository userRepository;
    
    public UserEntity create(final UserEntity userEntity) {
        
        if(userEntity == null || userEntity.getUEmail() == null) {
            throw new RuntimeException("Invalid arguments");
        }
        
        final String email = userEntity.getUEmail();
        if(userRepository.existsByEmail(email)) {
            log.warn("Email already exists {}", email);
            throw new RuntimeException("Email already exists");
        }
        
        return userRepository.save(userEntity);
    }
    
    public UserEntity getByCredentials(final String uEmail, final String uPassword) {
        return userRepository.findByEmailAndPassword(uEmail, uPassword);
    }
}

UserRepository.java UserRepository.java

@Repository
public interface UserRepository extends JpaRepository<UserEntity, String> {
    UserEntity findByEmail(String uEmail);
    Boolean existsByEmail(String uEmail);
    UserEntity findByEmailAndPassword(String uEmail, String uPassword);
}

UserController.java UserController.java

@Slf4j
@RestController
@RequestMapping("/auth")
public class UserController {
        
    @Autowired
    private UserService userService;
    
    //skip signup method 

    @PostMapping("/signin")
    public ResponseEntity<?> authenticate(@RequestBody UserDTO userDTO){
        UserEntity user = userService.getByCredentials(
                userDTO.getUEmail(),
                userDTO.getUPassword());
        
        if(user != null) {
            final UserDTO responseUserDTO = UserDTO.builder()
                    .uEmail(user.getUEmail())
                    .id(user.getId())
                    .build();
            
            return ResponseEntity.ok().body(responseUserDTO);
        } else {
            ResponseDTO responseDTO = ResponseDTO.builder()
                    .error("Login failed.")
                    .build();
            
            return ResponseEntity.badRequest().body(responseDTO);
        }
    }
}

UserDTO.java用户DTO.java

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserDTO {
    private String token;
    private String uEmail;
    private String uName;
    private String uPassword;
    private String id;
}

I also looked for naming strategies in hibernate ORM, but I didn't get a clear answer.我也在hibernate ORM找过命名攻略,也没有得到明确的答复。 Below is the site I looked for.下面是我找的网站。

https://docs.jboss.org/hibernate/orm/5.3/userguide/html_single/Hibernate_User_Guide.html#naming https://docs.jboss.org/hibernate/orm/5.3/userguide/html_single/Hibernate_User_Guide.html#naming

https://www.jpa-buddy.com/blog/hibernate-naming-strategies-jpa-specification-vs-springboot-opinionation/ https://www.jpa-buddy.com/blog/hibernate-naming-strategies-jpa-specification-vs-springboot-opinionation/

https://docs.jboss.org/hibernate/orm/5.4/javadocs/org/hibernate/boot/model/naming/Identifier.html https://docs.jboss.org/hibernate/orm/5.4/javadocs/org/hibernate/boot/model/naming/Identifier.html

Eventually, I changed the variable name to 'email' and 'password' and solved it, but anyway, what UserRepository does is write queries, and the variable name is at the discretion of the person who writes the code, so I wonder why there is an error.最终,我将变量名改为'email'和'password'并解决了它,但无论如何,UserRepository所做的是编写查询,变量名由编写代码的人自行决定,所以我想知道为什么会有是一个错误。

Any help is appreciated!任何帮助表示赞赏!

This seems to be the issue:这似乎是问题所在:

UserEntity findByEmailAndPassword(String uEmail, String uPassword);

Since the method is findByEmailAndPassword, JPA is trying to create the query as: select email,password from User and while doing so, it is looking for attributes email and password in UserEntity.由于该方法是 findByEmailAndPassword,JPA 试图将查询创建为: select email,password from User ,同时它正在 UserEntity 中查找属性emailpassword

Since you have defined the attribute name as uEmail it is throwing the indicative error:由于您已将属性名称定义为uEmail ,因此它会抛出指示性错误:

No property email found for type UserEntity! Did you mean 'uEmail','UEmail'?; 

The obvious solution will be to just rename the repository method as:显而易见的解决方案是将存储库方法重命名为:

UserEntity findByUEmailAndUPassword(String uEmail, String uPassword);

In conclusion the repository method should match with the entity attribute name.总之,存储库方法应与实体属性名称相匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM