我从数据库中获取数据并将其转换为我需要的类型时遇到问题。
我尝试使用Spring安全性从数据库中搜索已重置的用户。
它的工作方式如下:我插入userName和密码,方法loadUserByUserName(String userName)
从UserDetailsServiceImpl
类转到数据库,并且cheaks for用户存在于DB中,如果是(用户存在于DB中),则从DB获取它授权用户并为他呈现安全页面。但问题是在我的DAO impl类方法中无法将它转换为需要我的对象 - App1User
我的实体类,我在登录页面上看到这样的消息(原因:[Ljava.lang.Object;不能被强制转换为app1.domain.App1User enter code here
):
我在DAOImpl类中的方法:
public App1User findUserByName(String userName) {
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
List<App1User> listUser = null;
try {
String stringSQL = "select au.userId, au.firstName, au.lastName, au.middleName, au.username, au.password, au.userPosition from App1User au where au.username = :userNameArg";
Query query = session.createQuery(stringSQL);
query.setParameter("userNameArg", userName);
listUser = (List<App1User>)query.list();
session.flush();
session.clear();
transaction.commit();
} catch(HibernateException e) {
System.err.println(e);
if(transaction != null)
transaction.rollback();
} finally {
if(session != null)
session.close();
}
return (App1User)listUser.get(0);
}
我的hibernate.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.default_schema">PUBLIC</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<property name="hibernate.transaction.auto_close_session">false</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.H2Dialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<mapping resource="/WEB-INF/hibernateConf/App1User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
我现在的例外情况:
SEVERE: An internal error occurred while trying to authenticate the user.
org.springframework.security.authentication.InternalAuthenticationServiceException: [Ljava.lang.Object; cannot be cast to app1.domain.App1User
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:125)
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:143)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:167)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:192)
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:93)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:217)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:120)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:120)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:53)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1517)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1474)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to app1.domain.App1User
at app1.persistance.UserManageDAOImpl.findUserByName(UserManageDAOImpl.java:102)
at app1.web.authentification.UserDetailsServiceImpl.loadUserByUsername(UserDetailsServiceImpl.java:36)
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:114)
... 42 more
还有我的UserDetailServiceImpl类:
public UserDetails loadUserByUsername(String userName)
throws UsernameNotFoundException {
App1User listUser = userManageDAOIF.findUserByName(userName);
String password = null;
Collection<GrantedAuthority> authorities = null;
if(listUser != null) {
password = (String)listUser.getPassword();
authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
org.springframework.security.core.userdetails.User secureUser = new
org.springframework.security.core.userdetails.User(userName, password, authorities);
return secureUser;
} else {
throw new UsernameNotFoundException("No user exist in datbase");
}
}
答案 0 :(得分:3)
当您从DB中选择特定列时,您获得的结果不是实体对象,而是Object[]
,其中每个数组元素都包含不同的列值。因此,您从query.list()
方法获得的内容是:List<Object[]>
。因此,当您将list.get(0)
投射到App1User
时,肯定会产生ClassCastException
。
所以,你得到Object[]
并构建App1User
实体对象,如下所示:
// size of this array would be number of columns in select query
Object[] attr = listUser.get(0);
App1User appUser = new App1User(attr[0], attr[1], attr[2], ...);
当然不是最好的方法。更好的方法是从db获得List<App1User>
。为此,只需更改查询:
String stringSQL = "select au.userId, au.firstName, au.lastName, au.middleName, au.username, au.password, au.userPosition from App1User au where au.username = :userNameArg";
为:
String stringSQL = "select au from App1User au where au.username = :userNameArg";