sql datasource in blueprint.xml in servicemix - sql

<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>

Related

Autowiring is null in Custom Authentication Provider

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

Spring mvc MappingSqlQuery Property 'sql' is required

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();
}

Exception: java.io.NotSerializableException: org.springframework.jdbc.datasource.DriverManagerDataSource

I created a spring project (Spring 4.0.2). I present the required files:
spring.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="employeeDAO" class="com.journaldev.spring.jdbc.dao.EmployeeDAOImpl">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="employeeDAOJDBCTemplate" class="com.journaldev.spring.jdbc.dao.EmployeeDAOJDBCTemplateImpl">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="url" value="jdbc:sqlserver://localhost:1433;database=springdb"/>
<property name="username" value="lm" />
<property name="password" value="pp" />
</bean>
</beans>
Employee.java
#Entity
#Table(name="Employee")
public class Employee {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "id", unique = true, nullable = false)
private int id;
#Column(name = "name")
private String name;
#Column(name = "role")
private String role;
// with getters, setters, default constructor, constructor using fields
}
EmployeeDAO.java
public interface EmployeeDAO
{
public List<Employee> getAll();
}
EmployeeDAOImpl.java
public class EmployeeDAOImpl implements EmployeeDAO {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
#Override
public List<Employee> getAll() {
String query = "select id, name, role from Employee";
List<Employee> empList = new ArrayList<Employee>();
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
con = dataSource.getConnection();
ps = con.prepareStatement(query);
rs = ps.executeQuery();
while(rs.next()){
Employee emp = new Employee();
emp.setId(rs.getInt("id"));
emp.setName(rs.getString("name"));
emp.setRole(rs.getString("role"));
empList.add(emp);
}
}catch(SQLException e){
e.printStackTrace();
}finally{
try {
rs.close();
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return empList;
}
}
EmployeeDAOJDBCTemplateImpl.java
public class EmployeeDAOJDBCTemplateImpl implements EmployeeDAO,Serializable {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
#Override
public List<Employee> getAll() {
String query = "select id, name, role from Employee";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
List<Employee> empList = new ArrayList<Employee>();
List<Map<String,Object>> empRows = jdbcTemplate.queryForList(query);
for(Map<String,Object> empRow : empRows){
Employee emp = new Employee();
emp.setId(Integer.parseInt(String.valueOf(empRow.get("id"))));
emp.setName(String.valueOf(empRow.get("name")));
emp.setRole(String.valueOf(empRow.get("role")));
empList.add(emp);
}
return empList;
}
}
The bean to call in order to extract the list of employees DataModelD.java :
#ManagedBean
#ViewScoped
public class DataModelD implements Serializable
{
private List<Employee> list;
private Employee employee;
private EmployeeDAO eDao;
#PostConstruct
public void init()
{
System.out.println("-----------------------------BEGIN List");
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
eDao = ctx.getBean("employeeDAOJDBCTemplate", EmployeeDAO.class);
employee = new Employee();
list = eDao.getAll();
System.out.println("---------------------------------------List size= " + list.size());
}
}
After running it(to display the list of employees), the following exception is displayed:
08:14:46,222 INFO [org.jboss.as.server] (DeploymentScanner-threads - 2) JBAS018559: Deployed "HiSpring.war"
08:15:29,271 INFO [stdout] (http-localhost-127.0.0.1-8080-1) -----------------------------BEGIN List
08:15:29,529 INFO [org.springframework.context.support.ClassPathXmlApplicationContext] (http-localhost-127.0.0.1-8080-1) Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#ca34ed: startup date [Wed Aug 17 08:15:29 GMT-08:00 2016]; root of context hierarchy
08:15:29,591 INFO [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] (http-localhost-127.0.0.1-8080-1) Loading XML bean definitions from class path resource [spring.xml]
08:15:29,718 INFO [org.springframework.jdbc.datasource.DriverManagerDataSource] (http-localhost-127.0.0.1-8080-1) Loaded JDBC driver: com.microsoft.sqlserver.jdbc.SQLServerDriver
08:15:30,736 INFO [stdout] (http-localhost-127.0.0.1-8080-1) ---------------------------------------List size= 5
08:15:30,832 SEVERE [javax.enterprise.resource.webcontainer.jsf.application] (http-localhost-127.0.0.1-8080-1) Error Rendering View[/sarsoura/list.xhtml]: java.io.NotSerializableException: org.springframework.jdbc.datasource.DriverManagerDataSource
at java.io.ObjectOutputStream.writeObject0(Unknown Source) [rt.jar:1.7.0_55]
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source) [rt.jar:1.7.0_55]
Have you please any idea about this issue?.Any reply will be appreciated.

one-to-many relationship with table having composite key

This is the full code for mapping of the tables I am doing. But dont know why I am getting
java heap space error. I am using Jboss server and the exact error message is java.lang.OutOfMemoryError: Java heap space.
package com.mercer.chat.app.dataobject;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class MHRContChatSessionDO {
private Long id;
private String chatBucketHeadline;
private String preChatLongHeadline;
private String postChatLongHeadline;
private String preChatSummary;
private String postChatSummary;
private String chatBucketImage;
private String chatLogPath;
private Integer roomId;
private List<MHRContChatAlertsDO> chatAlerts;
public MHRContChatSessionDO() {
super();
}
public MHRContChatSessionDO(Long id, String chatBucketHeadline, String preChatLongHeadline,
String postChatLongHeadline, String preChatSummary, String postChatSummary, String chatBucketImage,
String chatLogPath,Integer roomId, List<MHRContChatAlertsDO> chatAlerts) {
super();
this.id = id;
this.chatBucketHeadline = chatBucketHeadline;
this.preChatLongHeadline = preChatLongHeadline;
this.postChatLongHeadline = postChatLongHeadline;
this.preChatSummary = preChatSummary;
this.postChatSummary = postChatSummary;
this.chatBucketImage = chatBucketImage;
this.chatLogPath = chatLogPath;
this.roomId = roomId;
this.chatAlerts = chatAlerts;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getChatBucketHeadline() {
return chatBucketHeadline;
}
public void setChatBucketHeadline(String chatBucketHeadline) {
this.chatBucketHeadline = chatBucketHeadline;
}
public String getPreChatLongHeadline() {
return preChatLongHeadline;
}
public void setPreChatLongHeadline(String preChatLongHeadline) {
this.preChatLongHeadline = preChatLongHeadline;
}
public String getPostChatLongHeadline() {
return postChatLongHeadline;
}
public void setPostChatLongHeadline(String postChatLongHeadline) {
this.postChatLongHeadline = postChatLongHeadline;
}
public String getPreChatSummary() {
return preChatSummary;
}
public void setPreChatSummary(String preChatSummary) {
this.preChatSummary = preChatSummary;
}
public String getPostChatSummary() {
return postChatSummary;
}
public void setPostChatSummary(String postChatSummary) {
this.postChatSummary = postChatSummary;
}
public String getChatBucketImage() {
return chatBucketImage;
}
public void setChatBucketImage(String chatBucketImage) {
this.chatBucketImage = chatBucketImage;
}
public String getChatLogPath() {
return chatLogPath;
}
public void setChatLogPath(String chatLogPath) {
this.chatLogPath = chatLogPath;
}
public Integer getRoomId() {
return roomId;
}
public void setRoomId(Integer roomId) {
this.roomId = roomId;
}
public List<MHRContChatAlertsDO> getChatAlerts() {
return chatAlerts;
}
public void setChatAlerts(List<MHRContChatAlertsDO> chatAlerts) {
this.chatAlerts = chatAlerts;
}
}
public class MHRContChatAlertsDO implements Serializable {
private Long id;
private String userId;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public MHRContChatAlertsDO() {
}
public MHRContChatAlertsDO(Long id,String userId) {
this.id=id;
this.userId=userId;
}
#Override
public boolean equals(Object arg0) {
if(arg0 == null) return false;
if(!(arg0 instanceof MHRContChatAlertsDO)) return false;
MHRContChatAlertsDO arg1 = (MHRContChatAlertsDO) arg0;
return (this.id.longValue() == arg1.getId().longValue()) && (this.userId.equals(arg1.getUserId()) );
}
#Override
public int hashCode() {
int hsCode;
hsCode = id.hashCode();
hsCode = 19 * hsCode+ userId.hashCode();
return hsCode;
}
}
<?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 default-lazy="true">
<class name="com.mercer.chat.app.dataobject.MHRContChatSessionDO"
table="QA_TEST2">
<cache usage="read-only" include="all"/>
<id name="id" type="java.lang.Long">
<column name="ID_CHAT_SESSION" precision="22" scale="0" />
<generator class="assigned" />
</id>
<property name="chatBucketHeadline" type="string">
<column name="CHAT_BUCKET_HEADLINE" />
</property>
<property name="preChatLongHeadline" type="string">
<column name="PRE_CHAT_LONGHEADLINE" scale="0" />
</property>
<property name="postChatLongHeadline" type="string">
<column name="POST_CHAT_LONGHEADLINE" />
</property>
<property name="preChatSummary" type="string">
<column name="PRE_CHAT_SUMMARY" />
</property>
<property name="postChatSummary" type="string">
<column name="POST_CHAT_SUMMARY" not-null="true" />
</property>
<property name="chatBucketImage" type="string">
<column name="CHAT_BUCKET_IMAGE_PATH" />
</property>
<property name="chatLogPath" type="string">
<column name="CHAT_LOG_PATH" />
</property>
<property name="roomId" type="java.lang.Integer">
<column name="ROOM_ID" scale="0" />
</property>
<list name="chatAlerts" batch-size="5" cascade="all" lazy="false">
<cache usage="read-only" include="all" />
<key column="ID_CHAT_SESSION" />
<list-index column="ID_USER" />
<one-to-many
class="com.mercer.chat.app.dataobject.MHRContChatAlertsDO" />
</list>
</class>
</hibernate-mapping>
<hibernate-mapping default-lazy="true">
<class name="com.mercer.chat.app.dataobject.MHRContChatAlertsDO" table="QA_TEST3">
<cache usage="read-only" include="all" />
<composite-id >
<key-property name="id" type="java.lang.Long">
<column name="ID_CHAT_SESSION" precision="22" scale="0" />
</key-property>
<key-property name="userId" type="string">
<column name="ID_USER" />
</key-property>
</composite-id>
</class>
</hibernate-mapping>

NHibernate Does Not Popluate DB Record

I am new to NHibernate and have been working with some tutorials. I created an object (Project) and passed it to the Session.Save(obj) method. To test, I had default values in each DB field and the method returned the primary key but the fields were blank. I removed the default values from the DB and I get a SQL error "cannot insert NULL into the first field".
Here is the Project class:
public class Project
{
private int _projectId;
public virtual int ProjectId
{
get { return _projectId; }
set { _projectId = value; }
}
private string _projectCode;
public virtual string ProjectCode
{
get { return _projectCode; }
set { _projectCode = value; }
}
private int _customerKey;
public virtual int CustomerKey
{
get { return _customerKey; }
set { _customerKey = value; }
}
private DateTime _insertDate;
public virtual DateTime InsertDate
{
get { return _insertDate; }
set { _insertDate = value; }
}
}
Here is the mapping file:Project.hbm.xml
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping
xmlns="urn:nhibernate-mapping-2.2"
assembly="MosaicCrm.Core"
namespace="MosaicCrm.Core">
<class name="Project" >
<id name="ProjectId">
<generator class="native"></generator>
</id>
<properties name="ProjectCode" ></properties>
<properties name="CustomerKey"></properties>
<properties name="InsertDate"></properties>
</class>
</hibernate-mapping>
Here is the config file.
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.provider">
NHibernate.Connection.DriverConnectionProvider
</property>
<property name="dialect">
NHibernate.Dialect.MsSql2005Dialect
</property>
<property name="connection.driver_class">
NHibernate.Driver.SqlClientDriver
</property>
<property name="connection.connection_string">
Data Source=localhost;Initial Catalog=MosaicCrm;Integrated Security=SSPI;
</property>
<property name='proxyfactory.factory_class'>NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
</session-factory>
</hibernate-configuration>
Here is a snippet of the console app
var config = new Configuration();
config.Configure();
//config.AddAssembly(typeof(Project).Assembly);
config.AddAssembly("MosaicCrm.Core");
var factory = config.BuildSessionFactory();
//TODO: NHibernate access code here
ISession session = null;
ITransaction trans = null;
try
{
session = factory.OpenSession();
trans = session.BeginTransaction();
var project = new Project();
project.CustomerKey = 12;
project.ProjectCode = "ProjectCode";
project.InsertDate = DateTime.Now;
session.Save(project);
trans.Commit();
int i = project.ProjectId;
}
catch (Exception ex)
{
trans.Rollback();
}
finally
{
session.Close();
}
What am I doing missing?
Your mapping is wrong. The element used to map a property is property, not properties.