I'm facing a serious problem and I can't figure out how to solve it.
Basically, in my Custom Authentication provider, I can't autowire my customUserDetailsService, it is returning a null pointer exception.
I'm gonna paste all the classes I'm using plus the exception, the problem here is that it autowires but it returns NULL, it doesn't give me an error on the autowiring itself.
SecurityConfig class:
package esercizio.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
DbAuthenticationProvider dbAuthenticationProvider;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// SecurityContextHolder.getContext().getAuthentication();
auth.authenticationProvider(new DbAuthenticationProvider());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
// .addFilterBefore(
// new HeaderUsernamePasswordAuthenticationFilter(authenticationManager()),
// BasicAuthenticationFilter.class)
.csrf().disable().authorizeRequests().antMatchers("/resources/**").permitAll().antMatchers("/auth/**")
.hasRole("USER").anyRequest().authenticated().and().formLogin()
// .loginPage("/login.jsp")
.loginProcessingUrl("/signin").permitAll().failureForwardUrl("/errorPage")
.successForwardUrl("/successPage").and().logout().addLogoutHandler(customLogoutHandler())
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
// .and()
// .exceptionHandling().accessDeniedPage("/403");
}
#Bean
public CustomLogoutHandler customLogoutHandler() {
return new CustomLogoutHandler();
}
}
Custom Authentication Provider:
package esercizio.security;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
#Component
public class DbAuthenticationProvider implements AuthenticationProvider {
Logger logger = LogManager.getLogger(this.getClass());
#Autowired
UserDetailsService customUserDetailsService;
public DbAuthenticationProvider() {
// TODO Auto-generated constructor stub
}
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String name = authentication.getName();
Object credentials = authentication.getCredentials();
List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
UserDetails user = customUserDetailsService.loadUserByUsername(name);
Authentication auth = null;
if (!(credentials instanceof String)) {
return null;
}
String password = null;
try {
password = getMD5(credentials.toString());
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (user != null && (user.getUsername().equals(name) && user.getPassword().equals(password))) {
grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_USER"));
auth = new UsernamePasswordAuthenticationToken(name, password, grantedAuthorities);
} else {
throw new BadCredentialsException("Errore nell'autenticazione");
}
return auth;
}
#Override
public boolean supports(Class<?> arg0) {
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(arg0));
}
public String getMD5(String data) throws NoSuchAlgorithmException {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.update(data.getBytes());
byte[] digest = messageDigest.digest();
StringBuffer sb = new StringBuffer();
for (byte b : digest) {
sb.append(Integer.toHexString((int) (b & 0xff)));
}
return sb.toString();
}
}
CustomUserDetailsService
package esercizio.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import esercizio.database.dao.UsersDAO;
import esercizio.database.dto.UsersDTO;
#Service
public class CustomUserDetailsService implements UserDetailsService {
#Autowired
private UsersDAO usersDAO;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// TODO Auto-generated method stub
UsersDTO userTemp = usersDAO.findByUsername(username);
return userTemp;
}
}
WEB.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>InitServlet</servlet-name>
<servlet-class>esercizio.InitServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/springmvc-servlet.xml
/WEB-INF/spring-security-context.xml
</param-value>
</context-param>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>InitServlet</servlet-name>
<url-pattern>/InitServlet</url-pattern>
</servlet-mapping>
<listener>
<listener-class>esercizio.listener.SessionListener</listener-class>
</listener>
<!-- <filter>
<filter-name>RedirectFilter</filter-name>
<filter-class>esercizio.filters.RedirectFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>RedirectFilter</filter-name>
<url-pattern></url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list> -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
Spring-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.2.xsd
http://www.springframework.org/schema/data/repository
http://www.springframework.org/schema/data/repository/spring-repository-1.5.xsd">
<context:component-scan base-package="esercizio" />
<context:annotation-config />
<jpa:repositories base-package="esercizio.database.dao" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- max upload size in bytes -->
<property name="maxUploadSize" value="20971520" /> <!-- 20MB -->
<!-- max size of file in memory (in bytes) -->
<property name="maxInMemorySize" value="1048576" /> <!-- 1MB -->
</bean>
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations"
value="classpath:/esercizio/properties/db.properties" />
</bean>
<bean id="JDBCDataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="JDBCDataSource" />
</bean>
<!-- <bean id="tjtJTransactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="JDBCDataSource" />
</bean>
<tx:annotation-driven transaction-manager="tjtJTransactionManager" />-->
<mvc:resources mapping="/resources/**" location="/resources/theme1/"
cache-period="31556926" />
<mvc:annotation-driven />
</beans>
Spring Security xml (it is basically used just to scan and activate annotation config)
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<global-method-security pre-post-annotations="enabled"/>
<context:annotation-config />
<context:component-scan base-package="esercizio" />
</beans:beans>
And last but not least the exception it's giving me
java.lang.NullPointerException
esercizio.security.DbAuthenticationProvider.authenticate(DbAuthenticationProvider.java:41)
org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174)
org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:199)
org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94)
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)
If someone can figure out what the problem is I would be thankful forever, it has been like 3 days and I don't seem to be able to solve it.
I think
#Autowired
UserDetailsService customUserDetailsService;
should be
#Autowired
CustomUserDetailsService customUserDetailsService;
The main reason is that in your configure(AuthenticationManagerBuilder) you are building a new instance of the DbAuthenticationProvider while injecting it to the authentication-manager (just in this line: auth.authenticationProvider(new DbAuthenticationProvider());) outside the Spring-framework context so the DbAuthenticationProvider instance injected into the AuthenticationManager has no way to autowire the #Autowired UserDetailsService customUserDetailsService.
As this UserDetailsService field will be null a NullPointerException will be thrown in authenticate() method at this line of code: UserDetails user = customUserDetailsService.loadUserByUsername(name);
You can change the way the classes are loaded in many ways, but probably the easiest is taking this block of code:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
DbAuthenticationProvider dbAuthenticationProvider;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// SecurityContextHolder.getContext().getAuthentication();
auth.authenticationProvider(new DbAuthenticationProvider());
}
And change it to this:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
DbAuthenticationProvider dbAuthenticationProvider;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(dbAuthenticationProvider);
}
I think it is the easiest way of changing your code so that it gets to work
Related
I create my custom authentication filter, provider and successHandler and they are work except successHandler. I set uo authentication-success-handler-ref but it looks like not called. In logs is used default SavedRequestAwareAuthenticationSuccessHandler. I use spring security 4.2.2 and mitreid openid coennect project. I saw many examples how to set up your custom successHandler but they wasn't work.
My filter
#Component("custAuthRequestFilter")
public class custAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
public static final String SPRING_SECURITY_FORM_SESSION_KEY = "custSession";
private String sessionParameter = SPRING_SECURITY_FORM_SESSION_KEY;
private static final Logger LOG = LoggerFactory.getLogger(CustAuthenticationFilter.class);
protected CustAuthenticationFilter() {
super(new AntPathRequestMatcher("/custlogin", "POST"));
}
#Override
public Authentication attemptAuthentication(final HttpServletRequest request, final HttpServletResponse response) {
if (isCustSession(request)) {
final CustAuthenticationToken authRequest = getAuthRequest(request);
return getAuthenticationManager().authenticate(authRequest);
} else {
throw new AuthenticationServiceException("Authentication is not possible, CustSession is missing");
}
}
#Autowired
#Qualifier("custAuthenticationManager")
#Override
public void setAuthenticationManager(final AuthenticationManager authenticationManager) {
super.setAuthenticationManager(authenticationManager);
}
private CustAuthenticationToken getAuthRequest(final HttpServletRequest request) {
final String session = obtainSession(request);
return new CustAuthenticationToken(session);
}
private boolean isCustSession(final HttpServletRequest request) {
return !StringUtils.isEmpty(request.getParameter(sessionParameter));
}
private String obtainSession(final HttpServletRequest request) {
return request.getParameter(sessionParameter);
}
}
My provider
#Component("custAuthenticationProvider")
public class CustAuthenticationProvider
implements AuthenticationProvider {
private final static Logger LOG = LoggerFactory.getLogger(CustAuthenticationProvider.class);
#Autowired
private CoreClient coreClient;
#Autowired
private InMemoryRepository db;
#Override
public Authentication authenticate(final Authentication auth)
throws AuthenticationException {
LOG.debug("Get user info by session from core service");
try {
final List<SimpleGrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
final UserDataMap result = coreClient.getUserDataMap(custToken.getPrincipal().toString());
return new CustAuthenticationToken(custToken.getPrincipal().toString(), authorities);
} catch(final Exception exc) {
throw new InternalAuthenticationServiceException("Internal error", exc);
}
}
#Override
public boolean supports(Class<?> authentication) {
return authentication.equals(CustAuthenticationToken.class);
}
}
My custom successHandler
#Component("custSuccessHandler")
public class CustAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
private static final Logger LOG = LoggerFactory.getLogger(CustAuthenticationSuccessHandler.class);
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
LOG.debug(">>>>>>>>>>>>>>>>>>>>> success handler");
HttpSession session = request.getSession();
super.onAuthenticationSuccess(request, response, authentication);
}
}
user-context.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2-2.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<context:component-scan base-package="io.oidcconnector.auth" />
<security:authentication-manager id="custAuthenticationManager">
<security:authentication-provider ref="custAuthenticationProvider"/>
</security:authentication-manager>
<security:authentication-manager id="authenticationManager">
<security:authentication-provider>
<security:jdbc-user-service data-source-ref="dataSource"/>
</security:authentication-provider>
</security:authentication-manager>
<mvc:view-controller path="/login" view-name="login" />
<security:http authentication-manager-ref="authenticationManager" >
<security:intercept-url pattern="/authorize" access="hasRole('ROLE_USER')" />
<security:intercept-url pattern="/**" access="permitAll" />
<security:form-login login-page="/custlogin" authentication-failure-url="/custlogin?error=failure" authentication-success-handler-ref="custSuccessHandler" />
<security:form-login login-page="/login" authentication-failure-url="/login?error=failure" authentication-success-handler-ref="authenticationTimeStamper" />
<security:custom-filter ref="authRequestFilter" after="SECURITY_CONTEXT_FILTER" />
<security:custom-filter ref="custAuthRequestFilter" before="FORM_LOGIN_FILTER" />
<security:logout logout-url="/logout" />
<security:anonymous />
<security:expression-handler ref="oauthWebExpressionHandler" />
<security:headers>
<security:frame-options policy="DENY" />
</security:headers>
<security:csrf />
</security:http>
<mvc:view-controller path="/custlogin" view-name="custlogin" />
logs
DEBUG: org.springframework.security.web.util.matcher.AntPathRequestMatcher -
Checking match of request : '/custlogin'; against '/custlogin'
DEBUG: io.oidcconnector.auth.CustAuthenticationFilter - Request is to process authentication
DEBUG: org.springframework.security.authentication.ProviderManager - Authentication attempt using io.oidcconnector.auth.CUstAuthenticationProvider
DEBUG: io.oidcconnector.auth.CustAuthenticationProvider - Get user info by session from core service
DEBUG: io.oidcconnector.auth.CUstAuthenticationFilter - Authentication success. Updating SecurityContextHolder to contain: io.oidcconnector.auth.CustAuthenticationToken#441c7a52: Principal: abc; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_USER
DEBUG: org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler - Using default Url: /
DEBUG: org.springframework.security.web.DefaultRedirectStrategy - Redirecting to '/oidc-connector/'
DEBUG: org.springframework.security.web.context.HttpSessionSecurityContextRepository - SecurityContext 'org.springframework.security.core.context.SecurityContextImpl#441c7a52: Authentication: io.oidcconnector.auth.CUstAuthenticationToken#441c7a52: Principal: abc; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_USER' stored to HttpSession: 'org.apache.catalina.session.StandardSessionFacade#328f5fdf
I have no idea why this not working.
I work with Netbeans, Spring MVC and Oracle.
I want to use MappingSqlQuery to execute oracle sql. This is the java class which implements MappingSqlQuery
public class SelectAllDepartamentos extends MappingSqlQuery<Departamento> {
private static final String SQL_SELECT_DEPT =
"SELECT DEPT_NO, DNOMBRE, LOC FROM DEPT";
public SelectAllDepartamentos() {
}
public SelectAllDepartamentos(DataSource dataSource) {
super(dataSource,SQL_SELECT_DEPT);
}
#Override
protected Departamento mapRow(ResultSet rs, int i) throws SQLException {
Departamento dept = new Departamento();
dept.setNumero(rs.getInt("DEPT_NO"));
dept.setNombre(rs.getString("DNOMBRE"));
dept.setLocalidad(rs.getString("LOC"));
return dept;
}
}
The class which use SelectAllDepartamentos is . The method that I use is findAll
public class JdbcDepartamentoDao1 implements InitializingBean,DepartamentoDao{
private javax.sql.DataSource dataSource;
private JdbcTemplate jdbcTemplate;
private SelectAllDepartamentos selectdepartamentos;
public JdbcDepartamentoDao1() {
}
public JdbcDepartamentoDao1(javax.sql.DataSource dataSource) {
this.dataSource = dataSource;
}
public void setDataSource(javax.sql.DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.selectdepartamentos = new SelectAllDepartamentos();
}
#Override
public List<Departamento> findAll() {
return this.selectdepartamentos.execute();
}
#Override
public List<Departamento> findByLocalidad(String localidad) {
return null;
}
#Override
public String findById(int iddepartamento) {
String nombre = jdbcTemplate.queryForObject("SELECT DNOMBRE from DEPT WHERE DEPT_NO = ?",
new Object[]{iddepartamento},String.class);
return nombre;
}
#Override
public void insertarDepartamento(Departamento departamento) {
}
#Override
public void modificarDepartamento(Departamento departamento) {
}
#Override
public void eliminarDepartamento(Departamento departamento) {
}
#Override
public void afterPropertiesSet() throws Exception {
if (dataSource == null){
throw new BeanCreationException("Debe establece el dataSource ContactDao");
}
}
}
My application-context.xml is
<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="departamentoDao" class="dao.JdbcDepartamentoDao1">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) -->
<bean id="selectAllDepartamentos" class="modelos.SelectAllDepartamentos">
<property name="dataSource" ref="dataSource"></property>
<constructor-arg type="DataSource" ref="dataSource"></constructor-arg>
</bean>
</beans>
When I executed the method findAll
#Override
public List<Departamento> findAll() {
return this.selectdepartamentos.execute();
}
I get the error
Remove
/*public void setDataSource(javax.sql.DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.selectdepartamentos = new SelectAllDepartamentos();
}*/
Change to arg
<bean id="departamentoDao" class="dao.JdbcDepartamentoDao1">
<constructor-arg ref="dataSource" />
</bean>
Update constructor
public JdbcDepartamentoDao1(javax.sql.DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.selectdepartamentos = new SelectAllDepartamentos();
}
Here is the stack trace of an error i am getting:
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userManagerREST': Invocation of init method failed; nested exception is org.apache.cxf.service.factory.ServiceConstructionException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
Caused by: org.apache.cxf.service.factory.ServiceConstructionException
at org.apache.cxf.jaxrs.JAXRSServerFactoryBean.create(JAXRSServerFactoryBean.java:215)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeCustomInitMethod(AbstractAutowireCapableBeanFactory.java:1702)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1641)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570)
... 21 more
Here is my code
UserManagerDao.java
public interface UserManagerDao
{
public User fetchUserById(int id);
public List<User> fetchAllUsers();
public void insertUser(User user);
public void updateUser(User user);
public void deleteUser(User user);
}
UserManager.java
#Service
#Consumes("application/json")
#Produces("application/json")
public interface UserManager {
#POST
#Path("/insertUser/")
public UserResponse insertUser(UserRequest request);
}
UserManagerService.java
public class UserManagerService implements UserManager{
public UserManagerService(){
}
#Autowired
private UserManagerDaoImpl userDao;
public UserManagerDaoImpl getUserDao() {
return userDao;
}
public void setUserDao(UserManagerDaoImpl userDao) {
this.userDao = userDao;
}
#Override
public UserResponse insertUser(UserRequest request) {
UserResponse response = new UserResponse();
try{
getUserDao().insertUser(request.getUser());
}
catch(Exception e){
response.setSuccess(false);
response.setErrorMessage(e.getClass() + ":" + e.getMessage());
}
return response;
}
}
UserManagerDaoImpl.java
public class UserManagerDaoImpl implements UserManagerDao {
public UserManagerDaoImpl(){
}
private int nextUserId=0;
List<User> userList= new ArrayList<User>();
#Override
public User fetchUserById(int id) {
for(User user : userList){
if(user.getId()==id){
return user;
}
}
throw new RuntimeException("User not found : " + id);
}
#Override
public List<User> fetchAllUsers() {
return userList;
}
#Override
public void insertUser(User user) {
user.setId(nextUserId++);
userList.add(user);
}
#Override
public void updateUser(User user) {
User editUser = fetchUserById(user.getId());
editUser.setBirthDate(user.getBirthDate());
editUser.setCity(user.getCity());
editUser.setEmail(user.getEmail());
editUser.setName(user.getName());
editUser.setState(user.getName());
}
#Override
public void deleteUser(User user) {
User delUser = fetchUserById(user.getId());
userList.remove(delUser);
}
}
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app version="3.0" 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_3_0.xsd"
metadata-complete="true">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/*-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
</web-app>
springrest-context.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:cxf="http://cxf.apache.org/core"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xsi:schemaLocation="
http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<context:component-scan base-package="com.ihc.*" />
<cxf:bus>
<cxf:features>
<cxf:logging />
</cxf:features>
</cxf:bus>
<bean id="userDao" class="com.ihc.bg.dao.impl.UserManagerDaoImpl">
</bean>
<bean id="userManagerService" class="com.ihc.bg.services.impl.UserManagerService">
<property name="userDao" ref="userDao" />
</bean>
<bean id="jsonProvider" class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
<jaxrs:server id="userManagerREST" address="/UserManager">
<jaxrs:serviceBeans>
<ref bean="userManagerService"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean='jsonProvider' />
</jaxrs:providers>
</jaxrs:server>
</beans>
The error is from the <jaxrs:server> tag part of the springrest-context.xml
Can anybody tell me why i am getting this error?
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="url" value="jdbc:sqlserver://localhost:1433/orderdb"/>
<property name="username" value="abc"/>
<property name="password" value="pqr"/>
</bean>
When i try to make connection using dataSource.getConnection()
Not allowing please help
*****Connection Code **********
public class DatabaseBeanH2 {
private DataSource dataSource;
private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseBeanH2.class);
public DatabaseBeanH2(){}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public void create() throws SQLException{
Statement sta = dataSource.getConnection().createStatement();
try {
sta.executeUpdate("CREATE TABLE orders ( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, item VARCHAR(50), amount INT, description VARCHAR(300), processed BOOLEAN, consumed BOOLEAN);");
} catch (SQLException e) {
LOGGER.info("Table orders already exists");
}
}
public void destroy() throws SQLException {
dataSource.getConnection().close();
}
}
You have to inject the dataSource bean in your DatabaseBeanH2 in the camel/spring context, something like this:
<bean id="databaseBean" class="my.package.DatabaseBeanH2">
<property name="dataSource" ref="dataSource" />
</bean>
I want to do native sql in hibernate using this:
public void removeTagsFromNews(int id)
{ Query query = session.createSQLQuery( "delete from NEWS_TAG where news_id=:id") .setParameter("id", id); }
But it returns me: Request processing failed; nested exception is java.lang.NullPointerException
Also I don't know how to declare session, because I used to work with sesionFactory.
Please help.
Root-context:
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang" xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<context:annotation-config />
<context:component-scan base-package="net.babobka.blog" />
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/db/jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>/WEB-INF/db/hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">${jdbc.show_sql}</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<mvc:annotation-driven />
<tx:annotation-driven />
<bean id="urlForwardController"
class="org.springframework.web.servlet.mvc.UrlFilenameViewController" />
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.tiles2.TilesView" />
</bean>
</beans>
Full stacktrace:
java.lang.NullPointerException
at net.babobka.blog.dao.NewsDAOImpl.removeTagsFromNews(NewsDAOImpl.java:100)
at net.babobka.blog.service.NewsServiceImpl.removeTagsFromNews(NewsServiceImpl.java:73)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:318)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at com.sun.proxy.$Proxy25.removeTagsFromNews(Unknown Source)
at net.babobka.blog.controller.HomeController.deleteNews(HomeController.java:165)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:311)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:116)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:101)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:139)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:182)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:173)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)
And DAOImpl:
#Repository
public class NewsDAOImpl implements NewsDAO {
#Autowired
private SessionFactory sessionFactory;
private Session session;
#SuppressWarnings("unchecked")
public List<News> listNews() {
return sessionFactory.getCurrentSession()
.createQuery("from News WHERE title!='About'").list();
}
public List<News> findAllWithDetail() {
List<News> news = (List<News>) sessionFactory.getCurrentSession()
.createQuery("from News WHERE title!='About'").list();
return news;
}
public List<News> findAllById(int id) {
List<News> news = (List<News>) sessionFactory.getCurrentSession()
.createQuery("from News where news_id=:id")
.setInteger("id", id).list();
return news;
}
public List<News> searchAllWithDetail(String name) {
List<News> news = (List<News>) sessionFactory
.getCurrentSession()
.createQuery(
"from News where title LIKE :name OR content LIKE :name AND title!='About'")
.setString("name", "%" + name + "%").list();
return news;
}
public List<News> getRandom() {
List<News> news = (List<News>) sessionFactory.getCurrentSession()
.createQuery("from News WHERE title!='About 'ORDER BY RAND()")
.setMaxResults(1).list();
return news;
}
public List<News> getAboutPage() {
return sessionFactory.getCurrentSession()
.createQuery("from News WHERE title='About'").list();
}
public List<News> getSomeNews(long b, long hm) {
List<News> news = (List<News>) sessionFactory
.getCurrentSession()
.createQuery(
"from News WHERE title!='About' ORDER BY publish_time")
.setMaxResults((int) hm).setFirstResult((int) b).list();
return news;
}
public Long getNumRows() {
return (Long) sessionFactory.getCurrentSession()
.createQuery("select count(*) from News WHERE title!='About'")
.uniqueResult();
}
public void addNews(News news) {
sessionFactory.getCurrentSession().save(news);
}
public void removeNews(int id) {
News news = (News) sessionFactory.getCurrentSession().load(News.class,
id);
if (null != news) {
sessionFactory.getCurrentSession().delete(news);
}
}
public void removeTagsFromNews(int id) {
Query query = session.createSQLQuery(
"delete from NEWS_TAG where news_id=:id")
.setInteger("id", id);
int updated = query.executeUpdate();
}
}
Extend the class with Hibernate DAO Support
public class YourClassName extends HibernateDaoSupport {
public void removeTagsFromNews(int id) {
try {
Session session = getSessionFactory().openSession();
Query query = session.createSQLQuery( "delete from NEWS_TAG where news_id=:id")
.setParameter("id", id);
// TODO:
} catch(Exception e) {
}
}
}
and you need to put the mapping in spring dispatcher-servlet.xml as following
<bean class="com.packagename.YourClassName" id="DaoName">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>