无法查询 findOne - SpringMVC MongoDB

Posted

技术标签:

【中文标题】无法查询 findOne - SpringMVC MongoDB【英文标题】:unable to query findOne - SpringMVC MongoDB 【发布时间】:2018-01-21 04:01:30 【问题描述】:

我正在尝试登录但无法登录,因为 findOne 查询在 DAO 实现中失败。我放了一系列 system.out.println 看看哪里出错了。

我明白了

email: abcdef Password : 123123

email2: abcdef Password2: 123123

check 1

check 2

由于某种原因,程序无法到达检查 3、检查 4 和内部 if 条件 where user != null。

我尝试了 mongoTemplate,mongoOperations,使用 addCriteria 没有标准但没有运气。

代码:UserDaoImplementation

import com.mthree.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;

@Repository
@Service(value = "userDao")
public class UserDaoImpl implements UserDao 

    @Autowired
    MongoTemplate mongoTemplate;
    private static final String COLLECTION_NAME = "user";

    public List<User> listUser() 
        return mongoTemplate.findAll(User.class, COLLECTION_NAME);
    

    public void add(User user) 
        if(!mongoTemplate.collectionExists(User.class))
            mongoTemplate.createCollection(User.class);
        
        user.setId(UUID.randomUUID().toString());
        mongoTemplate.insert(user, COLLECTION_NAME);
    

    public void update(User user) 
        mongoTemplate.save(user);
    

    public void delete(User user) 
        mongoTemplate.remove(user, COLLECTION_NAME);
    

    public User findUserById(String id) 
        return mongoTemplate.findById(id, User.class);
    

    @Override
    public User login(String Email, String Password) 

        System.out.println("email2: "+ Email + " Password2: "+ Password);
        try 

            System.out.println("check 1");

            Query query = new Query();

            System.out.println("check 2");

           // User user = mongoTemplate
             //       .findOne(query.addCriteria(Criteria.where("Email").is(Email)), User.class, COLLECTION_NAME);

            User user = mongoTemplate.findOne(query(where("Email").is(Email)), User.class,COLLECTION_NAME);
            System.out.println("check 3");

            if(user != null)
                //return user;
                System.out.println("check 4");

                System.out.println("password3: "+ Password + " Password4: "+ user.getPassword());
                BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
                // t y
                if(bCryptPasswordEncoder.matches(Password, user.getPassword())) 
                    return user;
                
            

            return null;

        catch (Exception e)
            return null;
        
    

    @Override
    public void register(User user) 

        mongoTemplate.insert(user);
    

    @Override
    public void changeProfile(User user) 

        mongoTemplate.save(user);
    

控制器

@RequestMapping(value="/login", method= RequestMethod.POST)
    public String login(@ModelAttribute("user") User user, HttpSession session, ModelMap modelMap)

         //simply checking the values my password is not yet encrypted
        System.out.println("email: "+ user.getEmail() + " Password : "+ user.getPassword());
        User user2 = userService.login(user.getEmail(), user.getPassword());
        if(user2 == null)
            modelMap.put("error", "Invalid User");
            return "account/login";
        else
            session.setAttribute("username", user.getFirstname());
            return "account/welcome";
        
        //BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        //user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
       // userService.register(user);

        //return "redirect:../login";
    

用户 - 模型

导入 org.springframework.data.annotation.Id; 导入 org.springframework.data.mongodb.core.mapping.Document;

@文档 公共类用户

@Id
private String id;
private long UserId;
private String Firstname;
private String Lastname;
private String Email;
private String Password;
private String Role;
private long CountryCode;
private long MobileNumber;
private String City;
private String Address;

public User()
    super();


public User(String id, long userId, String firstname, String lastname, String email, String password, String role, long countryCode, long mobileNumber, String city, String address) 
    super();
    this.id = id;
    this.UserId = userId;
    this.Firstname = firstname;
    this.Lastname = lastname;
    this.Email = email;
    this.Password = password;
    this.Role = role;
    this.CountryCode = countryCode;
    this.MobileNumber = mobileNumber;
    this.City = city;
    this.Address = address;



public String getId() 
    return id;


public void setId(String id) 
    this.id = id;


public long getUserId() 
    return UserId;


public void setUserId(long userId) 
    this.UserId = userId;


public String getFirstname() 
    return Firstname;


public void setFirstname(String firstname) 
    this.Firstname = firstname;


public String getLastname() 
    return Lastname;


public void setLastname(String lastname) 
    this.Lastname = lastname;


public String getEmail() 
    return Email;


public void setEmail(String email) 
    this.Email = email;


public String getPassword() 
    return Password;


public void setPassword(String password) 
    this.Password = password;


public String getRole() 
    return Role;


public void setRole(String role) 
    this.Role = role;


public long getCountryCode() 
    return CountryCode;


public void setCountryCode(long countryCode) 
    this.CountryCode = countryCode;


public long getMobileNumber() 
    return MobileNumber;


public void setMobileNumber(long mobileNumber) 
    this.MobileNumber = mobileNumber;


public String getCity() 
    return City;


public void setCity(String city) 
    this.City = city;


public String getAddress() 
    return Address;


public void setAddress(String address) 
    this.Address = address;



堆栈跟踪

e: org.springframework.data.mapping.context.InvalidPersistentPropertyPath: No property email found on com.mthree.model.User!
org.springframework.data.mapping.context.InvalidPersistentPropertyPath: No property email found on com.mthree.model.User!
    at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentPropertyPath(AbstractMappingContext.java:257)
    at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentPropertyPath(AbstractMappingContext.java:230)
    at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentPropertyPath(AbstractMappingContext.java:205)
    at org.springframework.data.mongodb.core.convert.QueryMapper$MetadataBackedField.getPath(QueryMapper.java:867)
    at org.springframework.data.mongodb.core.convert.QueryMapper$MetadataBackedField.<init>(QueryMapper.java:758)
    at org.springframework.data.mongodb.core.convert.QueryMapper$MetadataBackedField.<init>(QueryMapper.java:735)
    at org.springframework.data.mongodb.core.convert.QueryMapper.createPropertyField(QueryMapper.java:231)
    at org.springframework.data.mongodb.core.convert.QueryMapper.getMappedObject(QueryMapper.java:129)
    at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1760)
    at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1750)
    at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:624)
    at org.springframework.data.mongodb.core.MongoTemplate.findOne(MongoTemplate.java:589)
    at org.springframework.data.mongodb.core.MongoTemplate.findOne(MongoTemplate.java:581)
    at com.mthree.dao.UserDaoImpl.login(UserDaoImpl.java:67)
    at com.mthree.service.UserServiceImpl.login(UserServiceImpl.java:38)
    at com.mthree.controller.HomeController.login(HomeController.java:76)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2549)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2538)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

【问题讨论】:

您可以共享任何异常或完整堆栈跟踪吗? in query(where("Email").is(Email) "Email" 指的是一个属性,因此应该是"email" @JensSchauder no "email" 没有成功。检查我的用户模型。 @DanielC。我添加了一个堆栈跟踪,看看它。 在您的 catch 块中,您没有打印堆栈跟踪。尝试 e.printStacktrace() 并再次发布结果。您添加的 Stacktrace 只是您的应用程序启动时的日志。 【参考方案1】:

使用正确的 Java (Beans) 命名约定:

CamelCase 首字母小写:

public User(String id, long userId, String firstname, String lastname, String email, String password, String role, long countryCode, long mobileNumber, String city, String address) 

  super();
  this.id = id;
  this.userId = userId;
  this.firstname = firstname;
  this.lastname = lastname;
  this.email = email;
  this.password = password;
  this.role = role;
  this.countryCode = countryCode;
  this.mobileNumber = mobileNumber;
  this.city = city;
  this.address = address;

Getter 和 Setter 应该是第一个字母大写的字段名称,前缀为 getset(如果存在)。

查询/字符串中引用的属性与字段名称相同。

注意:实际的 Java Beans 规范存在一些偏差,例如没有默认构造函数的选项。

【讨论】:

以上是关于无法查询 findOne - SpringMVC MongoDB的主要内容,如果未能解决你的问题,请参考以下文章

Mongoose.js findOne 返回查询元数据

TypeError:无法读取未定义的属性“findOne”

如何正确使用 findOne mongoDB 查询?

如何使用 findOne 查询 mongodb 并排除数组中的一些嵌套字段

在 mongoose strict : false 中保存后,findOne() 后无法编辑

在 mongoose strict : false 中保存后,findOne() 后无法编辑