Page 1 of 2 12 LastLast
Results 1 to 10 of 17

Thread: Hibernate - find() Problem

  1. #1
    Join Date
    May 2010
    Posts
    318

    Default Hibernate - find() Problem

    Hello,

    Im developing a small webapplication using Spring, Spring Security and Hibernate. Im new to that all.
    Users shall register and login.
    Registering with hibernate is no problem.
    Ive got the following tables.

    users (username, password, enabled)
    authorities (username, authority)
    securitysalt (username, salt)

    when I wanted to use a salt I had to rewrite my configuration for using UserDetailsService. But the login did not work anymore.
    I looked at it with the debugger and I found out the the problem is the hibernate data access. I can't select a user from my table users!!!
    everytime I try the program stops there without error message.

    Here is the method from my HibernateDao.java

    Code:
    public List getUser(String username){
    
                    // getHibernateTemplate().find("from users as users where users.username='" + username + "';");
    
                    List test = getHibernateTemplate().find("from users as users where users.username='" + username + "';");
    
                    // List test2 = getHibernateTemplate().find("from users;");
    
                    return test;
    }
    Ive tried a lot of different possibilities to query for my user, but no matter what I try its not working!! Please help me! :-/

  2. #2
    Join Date
    Jun 2006
    Location
    The Netherlands
    Posts
    13,624

    Default

    Use the search...

    You should write HQL not SQL... I suggest the hibernate reference guide....

    Another note NEVER use string concat to include the parameters in your query, unless you want to be vulnerable for sql injection...
    Marten Deinum
    Java Consultant / Pragmatist / Open Source Enthousiast / Author


    Pro Spring MVC: With Web Flow
    Conspect

    Have you read the reference guide.
    Use the [ code ] tags, young padawan

  3. #3
    Join Date
    May 2010
    Posts
    318

    Default

    beside from using the string (Im going to remove that, but since nothing does work I wasnt successfull til now) I thought I was using HQL? ("from users;" should be the most simple hql query you can create or am I wrong?)
    I already researched a lot, but I will look once again through the postings. thank you for your answer!
    Last edited by jeeper; Aug 31st, 2010 at 05:58 AM.

  4. #4
    Join Date
    Jun 2006
    Location
    The Netherlands
    Posts
    13,624

    Default

    You are writting a query for a table not an object hence you are writing sql not hql. Or your class is named Users but I highly doubt that...
    Marten Deinum
    Java Consultant / Pragmatist / Open Source Enthousiast / Author


    Pro Spring MVC: With Web Flow
    Conspect

    Have you read the reference guide.
    Use the [ code ] tags, young padawan

  5. #5
    Join Date
    May 2010
    Posts
    318

    Default

    Quote Originally Posted by Marten Deinum View Post
    You are writting a query for a table not an object hence you are writing sql not hql. Or your class is named Users but I highly doubt that...
    This is my class Users.java which represents my table Users
    ?

    Code:
    
    public class Users {
    	
    	private String username;
    	private String password;
    	private boolean enabled;
    	
    	public Users(){
    		
    	}
    	
    	public String getUsername() {
    		return username;
    	}
    	public void setUsername(String username) {
    		this.username = username;
    	}
    	public String getPassword() {
    		return password;
    	}
    	public void setPassword(String password) {
    		this.password = password;
    	}
    	public boolean isEnabled() {
    		return enabled;
    	}
    	public void setEnabled(boolean enabled) {
    		this.enabled = enabled;
    	}
    	
    	
    	
    	
    
    }

  6. #6
    Join Date
    Jun 2006
    Location
    The Netherlands
    Posts
    13,624

    Default

    IMHO a crappy name for a class it represents a User not Users... But IMHO that is...

    If your query doesn't work imho either your mapping is wrong (haven't seen it) or your hibernate configuration is wrong or you tx setup is wrong...
    Marten Deinum
    Java Consultant / Pragmatist / Open Source Enthousiast / Author


    Pro Spring MVC: With Web Flow
    Conspect

    Have you read the reference guide.
    Use the [ code ] tags, young padawan

  7. #7
    Join Date
    May 2010
    Posts
    318

    Default

    you might be right and I can change that. But first I would like to solve my problem. Im sorry, you might have realized that Im a newbie, but I really need help, because Im stuck.

    Here is my mappingfile. I thought there must be everything right with the configuration, because saving new users works without problem

    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    
    <hibernate-mapping>
    
      <class name="package.backend.hibernate.Users" table="users">
        <id column="username" name="username" type="java.lang.String"/>
        <property name="password" type="java.lang.String"/>
        <property name="enabled" type="boolean"/>
      </class>
    
      <class name="package.backend.hibernate.Authorities" table="authorities">
        <composite-id access="field" class="package.backend.hibernate.AuthoritiesPK" name="authoritiesPK">
          <key-property access="field" column="username" name="username" type="java.lang.String"/>
          <key-property access="field" column="authority" name="authority" type="java.lang.String"/>
        </composite-id>
      </class>
    
      <class name="package.backend.hibernate.Userinformation" table="userinformation">
        <id column="email" name="email" type="java.lang.String"/>
        <property name="username" type="java.lang.String"/>
        <property name="gender" type="java.lang.String"/>
        <property name="birthday" type="java.lang.String"/>
        <property name="city" type="java.lang.String"/>
        <property name="country" type="int"/>
        <property name="foto" type="java.lang.String"/>
      </class>
    
      <class name="package.backend.hibernate.Securitysalt" table="securitysalt">
        <id column="username" name="username" type="java.lang.String"/>
        <property name="salt" type="java.lang.String"/>
      </class>
    
    </hibernate-mapping>
    my web.xml

    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" 
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
             http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    
        <display-name>Project</display-name>
    
        <description>Project</description>
    
        <!-- URL Rewrite Filter -->
        <!-- called for every Page - /* -->
        <filter>
            <filter-name>UrlRewriteFilter</filter-name>
            <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>UrlRewriteFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    
    
        <!-- Dispatcher Servlet - resolves view names and scans the packages for annotations -->
        <servlet>
        <servlet-name>jspDispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
    		<param-value>
    			/WEB-INF/config/dispatcher/*
    		</param-value>
    	</init-param>
        <load-on-startup>1</load-on-startup>
        </servlet>
    
        <servlet-mapping>
            <servlet-name>jspDispatcher</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    
        <!-- thats for static files -->
        
        <servlet-mapping>
    	<servlet-name>default</servlet-name>
    	<url-pattern>/static/*</url-pattern>
        </servlet-mapping>
        
    
        <!-- Configuration Files to be loaded -->
        
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
    
        <context-param>
      	<param-name>contextConfigLocation</param-name>
      	<param-value>
        		 /WEB-INF/config/applicationContext.xml
      	</param-value>
        </context-param>
    
        <!--  Security Configurations -->
        <!-- get the Security Configuration File -->
    
        <!-- All requests are going through the springSecurityFilterChain -->
        <!-- The DelegatingFilterProxy --> 
        <filter>
             <filter-name>springSecurityFilterChain</filter-name>
             <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        </filter>
    
        <filter-mapping>
          <filter-name>springSecurityFilterChain</filter-name>
             <url-pattern>/*</url-pattern>
             <dispatcher>REQUEST</dispatcher>
             <dispatcher>FORWARD</dispatcher>
             <dispatcher>INCLUDE</dispatcher>
             <dispatcher>ERROR</dispatcher>
        </filter-mapping> 
    
        <listener>
          <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
        </listener>
    
    </web-app>
    
    
    
     <!--  with this annotations didnt work so I commented it out
       <filter>
    		<filter-name>HibernateSession</filter-name>
    		<filter-class>
    			org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    		</filter-class>
       </filter>
    
    <filter-mapping>
    	<filter-name>HibernateSession</filter-name>
    		<url-pattern>/*</url-pattern>
    		    <dispatcher>REQUEST</dispatcher>
    		    <dispatcher>FORWARD</dispatcher>
    		    <dispatcher>INCLUDE</dispatcher>
    		    <dispatcher>ERROR</dispatcher>
    </filter-mapping>
    
      -->

  8. #8
    Join Date
    May 2010
    Posts
    318

    Default

    and my applicationContext.xml

    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xmlns:sec="http://www.springframework.org/schema/security"
    	xmlns:tx="http://www.springframework.org/schema/tx"
    	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.xsd
    	http://www.springframework.org/schema/tx 
    	http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
    
            <import resource="/mailing/mail-config.xml"/>
    
      	<sec:authentication-manager>
      		<sec:authentication-provider user-service-ref="myUserDetailsService">
                            <sec:password-encoder hash="md5" ref="passwordEncoder">
                                    <sec:salt-source ref="saltSource"/>
                            </sec:password-encoder>
      		</sec:authentication-provider>
      	</sec:authentication-manager>
    
    
    	<sec:http auto-config="true">
    		<sec:form-login login-page="/main"
    						default-target-url="/main"
    						always-use-default-target="true"
    						authentication-failure-url="/main?login_error=1"/>
    						
    		<sec:logout logout-success-url="/main" />
    	
    		<sec:intercept-url pattern="/**/admin" access="ROLE_ADMIN"/>
    		<sec:intercept-url pattern="/**/user" access="ROLE_USER"/>
    		<sec:intercept-url pattern="/index" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
    
    		<sec:session-management invalid-session-url="/index" session-fixation-protection="newSession">
                <sec:concurrency-control max-sessions="1" error-if-maximum-exceeded="true"/>
            </sec:session-management>
    
    	</sec:http>
    
    <!--  
    <bean id="baseTransactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true">
    <property name="transactionManager" ref="txManager" />
    	<property name="transactionAttributes">
    		<props>
    			<prop key="insert*">PROPAGATION_REQUIRED</prop>
    			<prop key="update*">PROPAGATION_REQUIRED</prop>
    			<prop key="save*">PROPAGATION_REQUIRED</prop>
    			<prop key="remove*">PROPAGATION_REQUIRED</prop>
    			<prop key="delete*">PROPAGATION_REQUIRED</prop>
    			<prop key="*">PROPAGATION_REQUIRED</prop>
    		</props>
    	</property>
    </bean>
    -->
      <!-- for transactional annotations, at the moment not used -->
     <!--
      <tx:annotation-driven transaction-manager="txManager"/>
    -->
      
      <bean id="myUserDetailsService" class="project.business.logic.UserDetailsServiceImpl">
          <property name="dataSource" ref="securityDataSource"/>
          <property name="projectDao" ref="projectDao"/>
      </bean>
    
      <bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder"/>
    
      <bean class="org.springframework.security.authentication.dao.ReflectionSaltSource" id="saltSource">
        <property name="userPropertyToUse" value="loadSaltByUsername"/>
      </bean> 
    
      <bean id="encoderClass" class="project.business.logic.PasswordEncoderMd5Salt">
          <property name="encoder" ref="passwordEncoder"/>
          <property name="randomGenerator" ref="randomGenerator"/>
      </bean>
    
      <bean id="randomGenerator" class="java.util.Random"/>
     
      <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> 
           <property name="sessionFactory" ref="sessionFactory"/>
      </bean>
    
    <!-- Registration of a User: necessary beans -->
    
    <bean id="projectDao" class="project.backend.hibernate.HibernateDao">
    	<property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    
    <bean id="user" class="project.backend.hibernate.Users"/>
    <bean id="auth" class="project.backend.hibernate.Authorities"/>
    <bean id="apk" class="project.backend.hibernate.AuthoritiesPK"/>
    <bean id="userinf" class="project.backend.hibernate.Userinformation"/>
    <bean id="usersalt" class="project.backend.hibernate.Securitysalt"/>
    
    <bean id="regUser" class="project.business.logic.RegisterUser">
        <property name="user" ref="user"/>
        <property name="auth" ref="auth"/>
        <property name="apk" ref="apk"/>
        <property name="userinf" ref="userinf"/>
        <property name="usersalt" ref="usersalt"/>
        <property name="projectDao" ref="projectDao"/>
    </bean>
    
    <bean id="regManager" class="project.business.logic.RegisterManager">
        <property name="encoderClass" ref="encoderClass"/>
        <property name="regUser" ref="regUser"/>
        <property name="regMail" ref="regMail"/>
    </bean>
    
    <bean id="getProfileInformation" class="project.business.logic.GetProfileInformation">
        <property name="projectDao" ref="projectDao"/>
    </bean>
    
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    	<property name="dataSource" ref="securityDataSource"/> 
    	 <property name="mappingResources">
    		<list>
                        <value>mappingdatei.hbm.xml</value>
    		</list>
    	</property>
    	<property name="hibernateProperties">
    		<props>
    			<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
    		</props>
    	</property>
    </bean>
    
       <bean id="securityDataSource" destroy-method="close"
       	class="org.apache.commons.dbcp.BasicDataSource">
            <property name="driverClassName" value="${db.driver}"/>
            <property name="url" value="${db.url}"/>
            <property name="username" value="${db.user}"/>
            <property name="password" value="${db.password}"/>
       </bean>
     
    
       <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
       		<property name="location" value="WEB-INF/config/db.properties"/>
       </bean>
    
      </beans>
    would be really glad if youd help me. maybe its just a dumb error :-(

  9. #9
    Join Date
    Jun 2006
    Location
    The Netherlands
    Posts
    13,624

    Default

    Don't use TransactionProxyFactoryBean it is old and not really recommended, use aop:config. Also not sure what your domain objects are doing in your configuration you don't need those.

    It is also not recommended to use HibenateDaoSupport/HibernateTemplate. Use the sessionFactory directly (use getCurrentSession to get the session).

    Also make sure your tables are InnoDB tables, if not transactions are pretty much useless. Also if you don't have a proper tx setup you might close connections to the database, leading to an unusable application.
    Marten Deinum
    Java Consultant / Pragmatist / Open Source Enthousiast / Author


    Pro Spring MVC: With Web Flow
    Conspect

    Have you read the reference guide.
    Use the [ code ] tags, young padawan

  10. #10
    Join Date
    May 2010
    Posts
    318

    Default

    Don't use TransactionProxyFactoryBean it is old and not really recommended, use aop:config.
    ok. its not used anyway.

    Also not sure what your domain objects are doing in your configuration you don't need those.
    what exactly do you mean?

    It is also not recommended to use HibenateDaoSupport/HibernateTemplate. Use the sessionFactory directly (use getCurrentSession to get the session).
    Im pretty disappointed now. I thought the HibernateDaoSupport would be a good way of programming. and I also shall not use A.1.1.1 nor A.1.1.2?
    http://static.springsource.org/sprin...rnate-template
    well, do you know a good tutorial then, because then I have to rewrite everything!!! :-(

    Also make sure your tables are InnoDB tables, if not transactions are pretty much useless.
    yes, Im using InnoDB tables

    Also if you don't have a proper tx setup you might close connections to the database, leading to an unusable application.
    Isnt that enough?
    Code:
    <tx:annotation-driven transaction-manager="txManager"/>
    
      <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> 
           <property name="sessionFactory" ref="sessionFactory"/>
      </bean>
    I dont use annotations at this moment, so I commented the first line out. But wouldnt that be enough?

    thanks for your help!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •