0

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>

1 Answer 1

2

For the first time of reading your post I can detect that your 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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.