Java Hibernate在DAO查询时停止

Java Hibernate在DAO查询时停止,java,spring,hibernate,spring-mvc,dao,Java,Spring,Hibernate,Spring Mvc,Dao,问题是,当我进入登录页面时,键入用户名/密码登录,即使我写得正确,也会出现错误(我检查了数据库,并且条目存在)。 我知道我应该使用记录器,但我仍在学习使用Hibernate的Spring框架 编辑: 1.测试的第一部分我输入了一个空用户名/密码(它适用于empty/empty)。对于第二部分,我使用了一个应该有效的方法。 2.其他DAO在Hibernate中正常工作(例如,它们正确检索数据,我对它们没有问题) 控制台输出如下所示: --------------------------------

问题是,当我进入登录页面时,键入用户名/密码登录,即使我写得正确,也会出现错误(我检查了数据库,并且条目存在)。 我知道我应该使用记录器,但我仍在学习使用Hibernate的Spring框架

编辑:
1.测试的第一部分我输入了一个空用户名/密码(它适用于empty/empty)。对于第二部分,我使用了一个应该有效的方法。
2.其他DAO在Hibernate中正常工作(例如,它们正确检索数据,我对它们没有问题)

控制台输出如下所示:

-----------------------------------
User Service INVOKED
User Service-- searching for User:
DAO-- Searching for:
Hibernate: select this_.id as id9_0_, this_.accountName as accountN2_9_0_, this_.password as password9_0_, this_.secGrade as secGrade9_0_, this_.userEmail as userEmail9_0_, this_.userName as userName9_0_ from USER this_ where this_.accountName=?
DAO-- End search
DAO--Not found
User Service-- UserProxyImpl instantiated
User Service-- NOT FOUND,
null
true //<-- Error returned to the controller
-----------------------------------
User Service INVOKED
User Service-- searching for User:admin
DAO-- Searching for:admin
Hibernate: select this_.id as id9_0_, this_.accountName as accountN2_9_0_, this_.password as password9_0_, this_.secGrade as secGrade9_0_, this_.userEmail as userEmail9_0_, this_.userName as userName9_0_ from USER this_ where this_.accountName=?
UserService-- Error in retrieving user
// It stops here and i don't understand why
true // still, returns error to the controller.
用户实体:

@Entity
@Table(name = "USER")
public class User implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = -1963505165125499005L;


    private long id;
    private int secGrade;

    private String userName;
    private String accountName;
    private String password;
    private String userEmail;

    public User(String name,
                String user_name,
                String password,
                String email,
                int secGrade){
        this.userName = name;
        this.accountName = user_name;
        this.password = password;
        this.userEmail = email;
        this.secGrade = secGrade;
    }

    @Id
    @GeneratedValue
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public int getSecGrade() {
        return secGrade;
    }
    public void setSecGrade(int secGrade) {
        this.secGrade = secGrade;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getAccountName() {
        return accountName;
    }

    public void setAccountName(String accountName) {
        this.accountName = accountName;
    }

    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

    public String getUserEmail() {
        return userEmail;
    }

    public void setUserEmail(String userEmail) {
        this.userEmail = userEmail;
    }

}
用于处理DB实体的代理类:

public class UserProxyImpl implements UserProxy {

    private int secGrade;   
    private String name;
    private String user_name;
    private String password;
    private String email;

    public UserProxyImpl() { }

    public UserProxyImpl(User usr){
        if( usr != null){
            System.out.println("USER PROXY--- constru from "+usr.getAccountName());
            this.secGrade = usr.getSecGrade();
            this.name = usr.getUserName();
            this.user_name = usr.getAccountName();
            this.password = usr.getPassword();
            this.email = usr.getUserEmail();
        }
    }
+ GETTERS/SETTERS
}
来自UserServiceImpl的方法,该方法创建用户obj并添加权限:

@Override
        public UserDetails loadUserByUsername(String username) 
                throws UsernameNotFoundException,DataAccessException {
                // Declare a null Spring User
                UserDetails user = null;
                System.out.println("-----------------------------------");
                System.out.println("User Service INVOKED");


            try {
                System.out.println("User Service-- searching for User:"+username);
               // Search database for a user that matches the specified username
                UserProxyImpl dbUser = new UserProxyImpl(userDAO.searchDB(username));
                System.out.println("User Service-- UserProxyImpl instantiated");
                if(dbUser.getName() != null){
                    System.out.println("User Service-- FOUND,"+username);
                }
                else{
                    System.out.println("User Service-- NOT FOUND,"+username);
                }

               // Populate the Spring User object with details from the dbUser
               // getAuthorities() will translate the access level to the correct role type
                System.out.println(dbUser.getName());
                user = new User(
                        dbUser.getUser_name(),
                        dbUser.getPassword().toLowerCase(),
                        true,
                        true,
                        true,
                        true,
                        getAuthorities(new Integer(dbUser.getSecGrade()))
                        );
                System.out.println(user.toString());
              } catch (Exception e) {
               System.out.println("UserService-- Error in retrieving user");
               throw new UsernameNotFoundException("Error in retrieving user");
              }

              // Return user to Spring for processing.

              return user;
             }


         @Override
        public Collection<GrantedAuthority> getAuthorities(Integer access) {
               // Create a list of grants for this user
               List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(2);

               // All users are granted with ROLE_USER access

               authList.add(new GrantedAuthorityImpl("ROLE_USER"));

               // Check if this user has admin access
               // We interpret Integer(3) as an admin user
               if ( access.compareTo(3) == 0) {

                    authList.add(new GrantedAuthorityImpl("ROLE_ADMIN"));

               }
               else if ( access.compareTo(2) == 0) {                

                   authList.add(new GrantedAuthorityImpl("ROLE_MOD"));
               }

               // Return list of granted authorities
               return authList;
               }
Spring安全配置。XML:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans 
    xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
                        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                        http://www.springframework.org/schema/security 
                        http://www.springframework.org/schema/security/spring-security-3.1.xsd">


 <http auto-config = 'true' use-expressions="true" access-denied-page="/denied" >

    <intercept-url pattern = "/home/" access="permitAll"/>
    <intercept-url pattern = "/home/login" access="permitAll"/>
    <intercept-url pattern = "/home/jobs" access="permitAll"/>
    <intercept-url pattern = "/home/info" access="permitAll"/>
    <intercept-url pattern = "/home/common" access="hasRole('ROLE_USER')"/>
    <intercept-url pattern = "/home/desk" access="hasRole('ROLE_MOD')"/>
    <intercept-url pattern = "/home/admin" access="hasRole('ROLE_ADMIN')"/>
    <form-login login-page="/login"
                default-target-url="/home"
                authentication-failure-url="/home/login?error=true"/>
    <logout logout-success-url="/home" />               
 </http> 

 <authentication-manager alias="authenticationManager">
    <authentication-provider ref="authenticationProvider"/>
</authentication-manager>

<beans:bean id="authenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
    <beans:property name="userDetailsService" ref="UserServiceImpl"/>
</beans:bean>


 <!-- Use a Md5 encoder  -->
 <beans:bean class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" id="passwordEncoder"/>

 <!-- A custom service where Spring will retrieve users and their corresponding access levels  -->
 <beans:bean id="UserServiceImpl" class="com.x.interview_management.service.impl.UserServiceImpl"/>

</beans:beans>


关于代码布局,很抱歉,这是我第一次在StackExchange上发布。

问题是我没有用户类的默认构造函数

日志显示这不是休眠问题。传递给服务(从而传递给DAO)的用户名是一个空字符串:
用户服务——搜索用户:
是的,对不起,忘了提及。日志的第一部分是当我没有输入用户名/密码时,正如您所看到的,它通过dao和数据库,没有发现为空。在第二部分中,我输入了正确的用户名和密码,它在Hibernate停止了。您可能抛出了一个异常。停止捕获异常,或者至少记录它们:
catch(Exception e){throw new username notfoundexception(“检索用户时出错”);}
打印异常的堆栈跟踪,它会告诉您原因。完全无关的建议:logback或log4j。
public User searchDB(String username){

        User u = (User)this.getSessionFactory().getCurrentSession()
                    .createCriteria(User.class)
                    .add(Restrictions.eq("accountName",username))
                    .uniqueResult();
        System.out.println("DAO-- End search");
        if(u != null){
            System.out.println("DAO-- Found:"+u.getUserName());
            return u;
        }
        else{
            System.out.println("DAO--Not found");
            return null;
        }

    }
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans 
    xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
                        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                        http://www.springframework.org/schema/security 
                        http://www.springframework.org/schema/security/spring-security-3.1.xsd">


 <http auto-config = 'true' use-expressions="true" access-denied-page="/denied" >

    <intercept-url pattern = "/home/" access="permitAll"/>
    <intercept-url pattern = "/home/login" access="permitAll"/>
    <intercept-url pattern = "/home/jobs" access="permitAll"/>
    <intercept-url pattern = "/home/info" access="permitAll"/>
    <intercept-url pattern = "/home/common" access="hasRole('ROLE_USER')"/>
    <intercept-url pattern = "/home/desk" access="hasRole('ROLE_MOD')"/>
    <intercept-url pattern = "/home/admin" access="hasRole('ROLE_ADMIN')"/>
    <form-login login-page="/login"
                default-target-url="/home"
                authentication-failure-url="/home/login?error=true"/>
    <logout logout-success-url="/home" />               
 </http> 

 <authentication-manager alias="authenticationManager">
    <authentication-provider ref="authenticationProvider"/>
</authentication-manager>

<beans:bean id="authenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
    <beans:property name="userDetailsService" ref="UserServiceImpl"/>
</beans:bean>


 <!-- Use a Md5 encoder  -->
 <beans:bean class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" id="passwordEncoder"/>

 <!-- A custom service where Spring will retrieve users and their corresponding access levels  -->
 <beans:bean id="UserServiceImpl" class="com.x.interview_management.service.impl.UserServiceImpl"/>

</beans:beans>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>${error}</h1>
    <sec:authorize access="!isAuthenticated()">
    <div id = "login" style="text-align:center;">

                <h3 style="text-align:center">Login with Username and Password</h3>

                    <form action='/InterviewManagement/j_spring_security_check' method='POST'>
                    <table>
                    <tr>
                        <td>Username:</td>
                        <td><input type='text' name='j_username' value=''><td/>
                    <tr/>
                    <tr>
                        <td>Password:</td>
                        <td><input type='password' name='j_password'/><td/>
                    <tr/>

                    <tr>
                        <td><input name="submit" type="submit"/></td>
                        <td><input name="reset" type="reset"/></td>
                    </tr>
                    </table>
                    </form>

    </div>
    </sec:authorize>    
    <a href="/InterviewManagement/home/">return home</a>
</body>
</html>