Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a problem with my spring, hibernate app. I'm trying to make a login with spring security and im having little trouble geting my user account query to DB to work.

Problem is that my code will reach "test1" but it won't reach "test2" and since I'm not getting any errors to console and also app will continue running I have no clue what the problem might be.

When I press "login" button, I will directed to login failed page. Also I'll point out that I am new with spring and hibernate.

Anybody have any ideas what I'm doing wrong?

UserAccountService.java

package main.java.services;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import main.java.model.UserAccount;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("userAccountService")
@Transactional
public class UserAccountService {

    private EntityManager entityManager;

    @PersistenceContext
    public void setEntityManager(EntityManager entityManager){ 
            this. entityManager = entityManager; 
        }
    public UserAccount get(Integer id)
    {
        Query query = entityManager.createQuery("FROM user_account as ua WHERE ua.id="+id);
        return (UserAccount) query.getSingleResult();
    }

    public UserAccount get(String username)
    {
        System.out.println("test1");
        Query query = entityManager.createQuery("FROM user_account as ua WHERE ua.username='"+username+"'");
        System.out.println("test2");
        return (UserAccount) query.getSingleResult();
    }

    public void add(UserAccount userAccount)
    {
        entityManager.persist(userAccount);
    }
}

LoginService.java

package main.java.services;

import javax.annotation.Resource;

import main.java.model.UserAccount;
import main.java.security.CustomUserDetails;
import main.java.security.UserGrantedAuthority;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

public class LoginService implements UserDetailsService{

    @Resource(name="userAccountService")
    private UserAccountService userAccountService;

    public LoginService(){  }

    public UserDetails loadUserByUsername(String username){
     if (username != null && !username.equals("")){
         UserAccount userAccount = userAccountService.get(username);
         System.out.println(userAccount);
         if (userAccount == null) {
             return null;
         }
         GrantedAuthority grantedAuth = new UserGrantedAuthority(userAccount.getAuthority());
         System.out.println(userAccount.getId() + userAccount.getAuthority()+userAccount.getPassword());
         return new CustomUserDetails(userAccount.getId(), userAccount.getUsername(), userAccount.getPassword(), new GrantedAuthority[]{ grantedAuth });
     } else {
         return null;
     }
 }  
}

hibernateContext.xml

<?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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.1.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">

    <context:property-placeholder location="/WEB-INF/jdbc.properties" />

    <tx:annotation-driven transaction-manager="transactionManager" />

    <!-- Declare a datasource that has pooling capabilities-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
          destroy-method="close"
          p:driverClass="${jdbc.driverClassName}"
          p:jdbcUrl="${jdbc.url}"
          p:user="${jdbc.username}"
          p:password="${jdbc.password}"
          p:acquireIncrement="5"
          p:idleConnectionTestPeriod="60"
          p:maxPoolSize="100"
          p:maxStatements="50"
          p:minPoolSize="10" />

    <!-- Declare a JPA entityManagerFactory-->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >
        <property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml"></property>
        <property name="persistenceUnitName" value="hibernatePersistenceUnit" />
        <property name="dataSource" ref="dataSource"/>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" >
                <property name="databasePlatform">
                    <value>${jdbc.dialect}</value>
                </property>
                <property name="showSql" value="true"/>
            </bean>
        </property>
    </bean>

    <!-- Declare a transaction manager-->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

</beans>
share|improve this question

1 Answer 1

up vote 2 down vote accepted

On a first reading of your post I can detect that you query is wrong... Your query is an sql query. In this case you should use createNativeQuery() instead of createQuery(). The proper query is (assuming that I do not know you classes):

Query query = entityManager.createQuery("SELECT us FROM UserAccount as ua WHERE ua.username='"+username+"'");

where UserAccount is the name of the class, not the name of the table. Moreover it is better using a prepared statement (google it) for passing arguments to the query.

share|improve this answer
    
When I used this query "FROM UserAccount as ua WHERE ua.username='"+username+"'", the result waqs the same, it didn't go past "test2". When i tryed nativeQuery, I did get result from hibernate, but it didn't get any results from DB (so I might have DB conf error?). Even if I get native Query to work, I wouldn't want to stick with those. Not sure yet how to properly use preparedStatemtn with EntityManager, but I will keep working on with that. –  Kapaacius Apr 28 '13 at 9:09

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.