Spring Boot Multiple Datasource - java

I'm quite new to spring boot and I'd like to create a multiple datasource for my project.
Here is my current case. I have two packages for entity for multiple database. Let's say
com.test.entity.db.mysql ; for entities that belong to MySql
com.test.entity.db.h2 ; for entities that belong to H2 Databases
So, currently I have two entities class
UserMySql.java
#Entity
#Table(name="usermysql")
public class UserMysql{
#Id
#GeneratedValue
public int id;
public String name;
}
UserH2.java
#Entity
#Table(name="userh2")
public class Userh2 {
#Id
#GeneratedValue
public int id;
public String name;
}
I'd like to achieve a configuration where if I create user from UserMySql, it will be saved to MySql Database, and if I create user from Userh2 it will be saved to H2 Databases. So, I also have two DBConfig, let's say MySqlDbConfig and H2DbConfig.
(com.test.model is package where I'll put my Repositories class. It will be defined below)
MySqlDbConfig.java
#Configuration
#EnableJpaRepositories(
basePackages="com.test.model",
entityManagerFactoryRef = "mysqlEntityManager")
public class MySqlDBConfig {
#Bean
#Primary
#ConfigurationProperties(prefix="datasource.test.mysql")
public DataSource mysqlDataSource(){
return DataSourceBuilder
.create()
.build();
}
#Bean(name="mysqlEntityManager")
public LocalContainerEntityManagerFactoryBean mySqlEntityManagerFactory(
EntityManagerFactoryBuilder builder){
return builder.dataSource(mysqlDataSource())
.packages("com.test.entity.db.mysql")
.build();
}
}
H2DbConfig.java
#Configuration
#EnableJpaRepositories(
entityManagerFactoryRef = "h2EntityManager")
public class H2DbConfig {
#Bean
#ConfigurationProperties(prefix="datasource.test.h2")
public DataSource h2DataSource(){
return DataSourceBuilder
.create()
.driverClassName("org.h2.Driver")
.build();
}
#Bean(name="h2EntityManager")
public LocalContainerEntityManagerFactoryBean h2EntityManagerFactory(
EntityManagerFactoryBuilder builder){
return builder.dataSource(h2DataSource())
.packages("com.test.entity.db.h2")
.build();
}
}
My application.properties file
#DataSource settings for mysql
datasource.test.mysql.jdbcUrl = jdbc:mysql://127.0.0.1:3306/test
datasource.test.mysql.username = root
datasource.test.mysql.password = root
datasource.test.mysql.driverClassName = com.mysql.jdbc.Driver
#DataSource settings for H2
datasource.test.h2.jdbcUrl = jdbc:h2:~/test
datasource.test.h2.username = sa
# DataSource settings: set here configurations for the database connection
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.validation-query=SELECT 1
# Specify the DBMS
spring.jpa.database = MYSQL
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate settings are prefixed with spring.jpa.hibernate.*
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.naming_strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.hibernate.show_sql = true
spring.jpa.hibernate.format_sql = true
server.port=8080
endpoints.shutdown.enabled=false
And then for crud I have UserMySqlDao and UserH2Dao
UserMySqlDao.java
#Transactional
#Repository
public interface UserMysqlDao extends CrudRepository<UserMysql, Integer>{
public UserMysql findByName(String name);
}
UserH2Dao.java
#Transactional
#Repositories
public interface UserH2Dao extends CrudRepository<Userh2, Integer>{
public Userh2 findByName(String name);
}
And for last, I have an UserController as endpoint to access my service
UserController.java
#Controller
#RequestMapping("/user")
public class UserController {
#Autowired
private UserMysqlDao userMysqlDao;
#Autowired
private UserH2Dao userH2Dao;
#RequestMapping("/createM")
#ResponseBody
public String createUserMySql(String name){
UserMysql user = new UserMysql();
try{
user.name = name;
userMysqlDao.save(user);
return "Success creating user with Id: "+user.id;
}catch(Exception ex){
return "Error creating the user: " + ex.toString();
}
}
#RequestMapping("/createH")
#ResponseBody
public String createUserH2(String name){
Userh2 user = new Userh2();
try{
user.name = name;
userH2Dao.save(user);
return "Success creating user with Id: "+user.id;
}catch(Exception ex){
return "Error creating the user: " + ex.toString();
}
}
}
Application.java
#Configuration
#EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
#EntityScan(basePackages="com.test.entity.db")
#ComponentScan
public class Application {
public static void main(String[] args) {
System.out.println("Entering spring boot");
ApplicationContext ctx = SpringApplication.run(Application.class, args);
System.out.println("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.print(beanName);
System.out.print(" ");
}
System.out.println("");
}
}
With this configuration my Spring boot run well, but when I access
http://localhost/user/createM?name=myname it writes an exception
Error creating the user: org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute statement; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute statement
I've googling around and haven't got a solution yet. Any ideas why this exception occurs? And is this the best way to implement multiple datasource to implement my case above? I'm open to full refactor if needed.
Thanks

I think you can find it usefull
http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-two-datasources
It shows how to define multiple datasources & assign one of them as primary.
Here is a rather full example, also contains distributes transactions - if you need it.
http://fabiomaffioletti.me/blog/2014/04/15/distributed-transactions-multiple-databases-spring-boot-spring-data-jpa-atomikos/
What you need is to create 2 configuration classes, separate the model/repository packages etc to make the config easy.
Also, in above example, it creates the data sources manually. You can avoid this using the method on spring doc, with #ConfigurationProperties annotation. Here is an example of this:
http://xantorohara.blogspot.com.tr/2013/11/spring-boot-jdbc-with-multiple.html
Hope these helps.

I faced same issue few days back, I followed the link mentioned below and I could able to overcome the problem
http://www.baeldung.com/spring-data-jpa-multiple-databases

I solved the problem (How to connect multiple database using spring and Hibernate) in this way, I hope it will help :)
NOTE: I have added the relevant code, kindly make the dao with the help of impl I used in the below mentioned code.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>MultipleDatabaseConnectivityInSpring</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/dispatcher-servlet.xml
</param-value>
</context-param>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="localPersistenceUnitOne"
transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>in.india.entities.CustomerDetails</class>
<exclude-unlisted-classes />
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver" />
<property name="hibernate.jdbc.batch_size" value="0" />
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/shankar?sslmode=require" />
<property name="hibernate.connection.username" value="username" />
<property name="hibernate.connection.password" value="password" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
<persistence-unit name="localPersistenceUnitTwo"
transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>in.india.entities.CompanyDetails</class>
<exclude-unlisted-classes />
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver" />
<property name="hibernate.jdbc.batch_size" value="0" />
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/shankarTwo?sslmode=require" />
<property name="hibernate.connection.username" value="username" />
<property name="hibernate.connection.password" value="password" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
</persistence>
dispatcher-servlet
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:task="http://www.springframework.org/schema/task" xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util"
default-autowire="byName"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- Configure messageSource -->
<mvc:annotation-driven />
<context:component-scan base-package="in.india.*" />
<bean id="messageResource"
class="org.springframework.context.support.ResourceBundleMessageSource"
autowire="byName">
<property name="basename" value="messageResource"></property>
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="entityManagerFactoryOne"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
autowire="constructor">
<property name="persistenceUnitName" value="localPersistenceUnitOne" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource"
autowire="byName">
<property name="basename" value="messageResource" />
</bean>
<bean id="entityManagerFactoryTwo"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
autowire="constructor">
<property name="persistenceUnitName" value="localPersistenceUnitTwo" />
</bean>
<bean id="manager1" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryOne" />
</bean>
<bean id="manager2" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryTwo" />
</bean>
<tx:annotation-driven transaction-manager="manager1" />
<tx:annotation-driven transaction-manager="manager2" />
<!-- declare dependies here -->
<bean class="in.india.service.dao.impl.CustomerServiceImpl" />
<bean class="in.india.service.dao.impl.CompanyServiceImpl" />
<!-- Configure MVC annotations -->
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
</beans>
java class to persist into one database
package in.india.service.dao.impl;
import in.india.entities.CompanyDetails;
import in.india.service.CompanyService;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.transaction.annotation.Transactional;
public class CompanyServiceImpl implements CompanyService {
#PersistenceContext(unitName = "entityManagerFactoryTwo")
EntityManager entityManager;
#Transactional("manager2")
#Override
public boolean companyService(CompanyDetails companyDetails) {
boolean flag = false;
try
{
entityManager.persist(companyDetails);
flag = true;
}
catch (Exception e)
{
flag = false;
}
return flag;
}
}
java class to persist in another database
package in.india.service.dao.impl;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.transaction.annotation.Transactional;
import in.india.entities.CustomerDetails;
import in.india.service.CustomerService;
public class CustomerServiceImpl implements CustomerService {
#PersistenceContext(unitName = "localPersistenceUnitOne")
EntityManager entityManager;
#Override
#Transactional(value = "manager1")
public boolean customerService(CustomerDetails companyData) {
boolean flag = false;
entityManager.persist(companyData);
return flag;
}
}
customer.jsp
<%#page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<center>
<h1>SpringWithMultipleDatabase's</h1>
</center>
<form:form method="GET" action="addCustomer.htm" modelAttribute="customerBean" >
<table>
<tr>
<td><form:label path="firstName">First Name</form:label></td>
<td><form:input path="firstName" /></td>
</tr>
<tr>
<td><form:label path="lastName">Last Name</form:label></td>
<td><form:input path="lastName" /></td>
</tr>
<tr>
<td><form:label path="emailId">Email Id</form:label></td>
<td><form:input path="emailId" /></td>
</tr>
<tr>
<td><form:label path="profession">Profession</form:label></td>
<td><form:input path="profession" /></td>
</tr>
<tr>
<td><form:label path="address">Address</form:label></td>
<td><form:input path="address" /></td>
</tr>
<tr>
<td><form:label path="age">Age</form:label></td>
<td><form:input path="age" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit"/></td>
</tr>
</table>
</form:form>
</body>
</html>
company.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>ScheduleJobs</title>
</head>
<body>
<center><h1>SpringWithMultipleDatabase's</h1></center>
<form:form method="GET" action="addCompany.htm" modelAttribute="companyBean" >
<table>
<tr>
<td><form:label path="companyName">Company Name</form:label></td>
<td><form:input path="companyName" /></td>
</tr>
<tr>
<td><form:label path="companyStrength">Company Strength</form:label></td>
<td><form:input path="companyStrength" /></td>
</tr>
<tr>
<td><form:label path="companyLocation">Company Location</form:label></td>
<td><form:input path="companyLocation" /></td>
</tr>
<tr>
<td>
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Home</title>
</head>
<body>
<center><h1>Multiple Database Connectivity In Spring sdfsdsd</h1></center>
<a href='customerRequest.htm'>Click here to go on Customer page</a>
<br>
<a href='companyRequest.htm'>Click here to go on Company page</a>
</body>
</html>
success.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>ScheduleJobs</title>
</head>
<body>
<center><h1>SpringWithMultipleDatabase</h1></center>
<b>Successfully Saved</b>
</body>
</html>
CompanyController
package in.india.controller;
import in.india.bean.CompanyBean;
import in.india.entities.CompanyDetails;
import in.india.service.CompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class CompanyController {
#Autowired
CompanyService companyService;
#RequestMapping(value = "/companyRequest.htm", method = RequestMethod.GET)
public ModelAndView addStudent(ModelMap model) {
CompanyBean companyBean = new CompanyBean();
model.addAttribute(companyBean);
return new ModelAndView("company");
}
#RequestMapping(value = "/addCompany.htm", method = RequestMethod.GET)
public ModelAndView companyController(#ModelAttribute("companyBean") CompanyBean companyBean, Model model) {
CompanyDetails companyDetails = new CompanyDetails();
companyDetails.setCompanyLocation(companyBean.getCompanyLocation());
companyDetails.setCompanyName(companyBean.getCompanyName());
companyDetails.setCompanyStrength(companyBean.getCompanyStrength());
companyService.companyService(companyDetails);
return new ModelAndView("success");
}
}
CustomerController
package in.india.controller;
import in.india.bean.CustomerBean;
import in.india.entities.CustomerDetails;
import in.india.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class CustomerController {
#Autowired
CustomerService customerService;
#RequestMapping(value = "/customerRequest.htm", method = RequestMethod.GET)
public ModelAndView addStudent(ModelMap model) {
CustomerBean customerBean = new CustomerBean();
model.addAttribute(customerBean);
return new ModelAndView("customer");
}
#RequestMapping(value = "/addCustomer.htm", method = RequestMethod.GET)
public ModelAndView customerController(#ModelAttribute("customerBean") CustomerBean customer, Model model) {
CustomerDetails customerDetails = new CustomerDetails();
customerDetails.setAddress(customer.getAddress());
customerDetails.setAge(customer.getAge());
customerDetails.setEmailId(customer.getEmailId());
customerDetails.setFirstName(customer.getFirstName());
customerDetails.setLastName(customer.getLastName());
customerDetails.setProfession(customer.getProfession());
customerService.customerService(customerDetails);
return new ModelAndView("success");
}
}
CompanyDetails Entity
package in.india.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
#Entity
#Table(name = "company_details")
public class CompanyDetails {
#Id
#SequenceGenerator(name = "company_details_seq", sequenceName = "company_details_seq", initialValue = 1, allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "company_details_seq")
#Column(name = "company_details_id")
private Long companyDetailsId;
#Column(name = "company_name")
private String companyName;
#Column(name = "company_strength")
private Long companyStrength;
#Column(name = "company_location")
private String companyLocation;
public Long getCompanyDetailsId() {
return companyDetailsId;
}
public void setCompanyDetailsId(Long companyDetailsId) {
this.companyDetailsId = companyDetailsId;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public Long getCompanyStrength() {
return companyStrength;
}
public void setCompanyStrength(Long companyStrength) {
this.companyStrength = companyStrength;
}
public String getCompanyLocation() {
return companyLocation;
}
public void setCompanyLocation(String companyLocation) {
this.companyLocation = companyLocation;
}
}
CustomerDetails Entity
package in.india.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
#Entity
#Table(name = "customer_details")
public class CustomerDetails {
#Id
#SequenceGenerator(name = "customer_details_seq", sequenceName = "customer_details_seq", initialValue = 1, allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "customer_details_seq")
#Column(name = "customer_details_id")
private Long customerDetailsId;
#Column(name = "first_name ")
private String firstName;
#Column(name = "last_name ")
private String lastName;
#Column(name = "email_id")
private String emailId;
#Column(name = "profession")
private String profession;
#Column(name = "address")
private String address;
#Column(name = "age")
private int age;
public Long getCustomerDetailsId() {
return customerDetailsId;
}
public void setCustomerDetailsId(Long customerDetailsId) {
this.customerDetailsId = customerDetailsId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getProfession() {
return profession;
}
public void setProfession(String profession) {
this.profession = profession;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

Update 2018-01-07 with Spring Boot 1.5.8.RELEASE
If you want to know how to config it, how to use it, and how to control transaction. I may have answers for you.
You can see the runnable example and some explanation in https://www.surasint.com/spring-boot-with-multiple-databases-example/
I copied some code here.
First you have to set application.properties like this
#Database
database1.datasource.url=jdbc:mysql://localhost/testdb
database1.datasource.username=root
database1.datasource.password=root
database1.datasource.driver-class-name=com.mysql.jdbc.Driver
database2.datasource.url=jdbc:mysql://localhost/testdb2
database2.datasource.username=root
database2.datasource.password=root
database2.datasource.driver-class-name=com.mysql.jdbc.Driver
Then define them as providers (#Bean) like this:
#Bean(name = "datasource1")
#ConfigurationProperties("database1.datasource")
#Primary
public DataSource dataSource(){
return DataSourceBuilder.create().build();
}
#Bean(name = "datasource2")
#ConfigurationProperties("database2.datasource")
public DataSource dataSource2(){
return DataSourceBuilder.create().build();
}
Note that I have #Bean(name="datasource1") and #Bean(name="datasource2"), then you can use it when we need datasource as #Qualifier("datasource1") and #Qualifier("datasource2") , for example
#Qualifier("datasource1")
#Autowired
private DataSource dataSource;
If you do care about transaction, you have to define DataSourceTransactionManager for both of them, like this:
#Bean(name="tm1")
#Autowired
#Primary
DataSourceTransactionManager tm1(#Qualifier ("datasource1") DataSource datasource) {
DataSourceTransactionManager txm = new DataSourceTransactionManager(datasource);
return txm;
}
#Bean(name="tm2")
#Autowired
DataSourceTransactionManager tm2(#Qualifier ("datasource2") DataSource datasource) {
DataSourceTransactionManager txm = new DataSourceTransactionManager(datasource);
return txm;
}
Then you can use it like
#Transactional //this will use the first datasource because it is #primary
or
#Transactional("tm2")
This should be enough. See example and detail in the link above.

Use multiple datasource or realizing the separation of reading & writing.
you must have a knowledge of Class AbstractRoutingDataSource which support dynamic datasource choose.
Here is my datasource.yaml and I figure out how to resolve this case. You can refer to this project spring-boot + quartz. Hope this will help you.
dbServer:
default: localhost:3306
read: localhost:3306
write: localhost:3306
datasource:
default:
type: com.zaxxer.hikari.HikariDataSource
pool-name: default
continue-on-error: false
jdbc-url: jdbc:mysql://${dbServer.default}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8
username: root
password: lh1234
connection-timeout: 30000
connection-test-query: SELECT 1
maximum-pool-size: 5
minimum-idle: 2
idle-timeout: 600000
destroy-method: shutdown
auto-commit: false
read:
type: com.zaxxer.hikari.HikariDataSource
pool-name: read
continue-on-error: false
jdbc-url: jdbc:mysql://${dbServer.read}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8
username: root
password: lh1234
connection-timeout: 30000
connection-test-query: SELECT 1
maximum-pool-size: 5
minimum-idle: 2
idle-timeout: 600000
destroy-method: shutdown
auto-commit: false
write:
type: com.zaxxer.hikari.HikariDataSource
pool-name: write
continue-on-error: false
jdbc-url: jdbc:mysql://${dbServer.write}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8
username: root
password: lh1234
connection-timeout: 30000
connection-test-query: SELECT 1
maximum-pool-size: 5
minimum-idle: 2
idle-timeout: 600000
destroy-method: shutdown
auto-commit: false

Using two datasources you need their own transaction managers.
#Configuration
public class MySqlDBConfig {
#Bean
#Primary
#ConfigurationProperties(prefix="datasource.test.mysql")
public DataSource mysqlDataSource(){
return DataSourceBuilder
.create()
.build();
}
#Bean("mysqlTx")
public DataSourceTransactionManager mysqlTx() {
return new DataSourceTransactionManager(mysqlDataSource());
}
// same for another DS
}
And then use it accordingly within #Transaction
#Transactional("mysqlTx")
#Repository
public interface UserMysqlDao extends CrudRepository<UserMysql, Integer>{
public UserMysql findByName(String name);
}

Thanks all for your help but it is not complicated as it seems; almost everything is handled internally by SpringBoot.
In my case I want to use Mysql and Mongodb and the solution was to use EnableMongoRepositories and EnableJpaRepositories annotations on to my application class.
#SpringBootApplication
#EnableTransactionManagement
#EnableMongoRepositories(includeFilters = #ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = MongoRepository))
#EnableJpaRepositories(excludeFilters = #ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = MongoRepository))
class TestApplication { ...
NB: All mysql entities have to extend JpaRepository and mongo enities have to extend MongoRepository.
The datasource configs are straight forward as presented by spring documentation:
//mysql db config
spring.datasource.url= jdbc:mysql://localhost:3306/tangio
spring.datasource.username=test
spring.datasource.password=test
#mongodb config
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=tangio
spring.data.mongodb.username=tangio
spring.data.mongodb.password=tangio
spring.data.mongodb.repositories.enabled=true

once you start work with jpa and some driver is in your class path spring boot right away puts it inside as your data source (e.g h2 )
for using the defult data source therefore u will need only to define
spring.datasource.url= jdbc:mysql://localhost:3306/
spring.datasource.username=test
spring.datasource.password=test
if we go one step farther and u want to use two
I would reccomend to use two data sources such as explained here :
Spring Boot Configure and Use Two DataSources

MySqlBDConfig.java
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = "PACKAGE OF YOUR CRUDS USING MYSQL DATABASE",entityManagerFactoryRef = "mysqlEmFactory" ,transactionManagerRef = "mysqlTransactionManager")
public class MySqlBDConfig{
#Autowired
private Environment env;
#Bean(name="mysqlProperities")
#ConfigurationProperties(prefix="spring.mysql")
public DataSourceProperties mysqlProperities(){
return new DataSourceProperties();
}
#Bean(name="mysqlDataSource")
public DataSource interfaceDS(#Qualifier("mysqlProperities")DataSourceProperties dataSourceProperties){
return dataSourceProperties.initializeDataSourceBuilder().build();
}
#Primary
#Bean(name="mysqlEmFactory")
public LocalContainerEntityManagerFactoryBean mysqlEmFactory(#Qualifier("mysqlDataSource")DataSource mysqlDataSource,EntityManagerFactoryBuilder builder){
return builder.dataSource(mysqlDataSource).packages("PACKAGE OF YOUR MODELS").build();
}
#Bean(name="mysqlTransactionManager")
public PlatformTransactionManager mysqlTransactionManager(#Qualifier("mysqlEmFactory")EntityManagerFactory factory){
return new JpaTransactionManager(factory);
}
}
H2DBConfig.java
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = "PACKAGE OF YOUR CRUDS USING MYSQL DATABASE",entityManagerFactoryRef = "dsEmFactory" ,transactionManagerRef = "dsTransactionManager")
public class H2DBConfig{
#Autowired
private Environment env;
#Bean(name="dsProperities")
#ConfigurationProperties(prefix="spring.h2")
public DataSourceProperties dsProperities(){
return new DataSourceProperties();
}
#Bean(name="dsDataSource")
public DataSource dsDataSource(#Qualifier("dsProperities")DataSourceProperties dataSourceProperties){
return dataSourceProperties.initializeDataSourceBuilder().build();
}
#Bean(name="dsEmFactory")
public LocalContainerEntityManagerFactoryBean dsEmFactory(#Qualifier("dsDataSource")DataSource dsDataSource,EntityManagerFactoryBuilder builder){
LocalContainerEntityManagerFactoryBean em = builder.dataSource(dsDataSource).packages("PACKAGE OF YOUR MODELS").build();
HibernateJpaVendorAdapter ven = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(ven);
HashMap<String, Object> prop = new HashMap<>();
prop.put("hibernate.dialect", env.getProperty("spring.jpa.properties.hibernate.dialect"));
prop.put("hibernate.show_sql", env.getProperty("spring.jpa.show-sql"));
em.setJpaPropertyMap(prop);
em.afterPropertiesSet();
return em;
}
#Bean(name="dsTransactionManager")
public PlatformTransactionManager dsTransactionManager(#Qualifier("dsEmFactory")EntityManagerFactory factory){
return new JpaTransactionManager(factory);
}
}
application.properties
#---mysql DATASOURCE---
spring.mysql.driverClassName = com.mysql.jdbc.Driver
spring.mysql.url = jdbc:mysql://127.0.0.1:3306/test
spring.mysql.username = root
spring.mysql.password = root
#----------------------
#---H2 DATASOURCE----
spring.h2.driverClassName = org.h2.Driver
spring.h2.url = jdbc:h2:file:~/test
spring.h2.username = root
spring.h2.password = root
#---------------------------
#------JPA-----
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults = false
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
Application.java
#SpringBootApplication
public class Application {
public static void main(String[] args) {
ApplicationContext ac=SpringApplication.run(KeopsSageInvoiceApplication.class, args);
UserMysqlDao userRepository = ac.getBean(UserMysqlDao.class)
//for exemple save a new user using your repository
userRepository.save(new UserMysql());
}
}

Related

The requested resource is not available in spring mvc

After click on AddEmployee link next page is open given below
when i click on submit the then next page opening like that
addEmployee.jsp file
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Add Employee Data</h2>
<form:form method="POST" action="/save.html">
<table>
<tr>
<td><form:label path="id">Employee ID:</form:label></td>
<td><form:input path="id" value="${employee.id}" readonly="true"/></td>
</tr>
<tr>
<td><form:label path="name">Employee Name:</form:label></td>
<td><form:input path="name" value="${employee.name}"/></td>
</tr>
<tr>
<td><form:label path="age">Employee Age:</form:label></td>
<td><form:input path="age" value="${employee.age}"/></td>
</tr>
<tr>
<td><form:label path="salary">Employee Salary:</form:label></td>
<td><form:input path="salary" value="${employee.salary}"/></td>
</tr>
<tr>
<td><form:label path="address">Employee Address:</form:label></td>
<td><form:input path="address" value="${employee.address}"/></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit"/></td>
</tr>
</table>
</form:form>
<c:if test="${!empty employees}">
<h2>List Employees</h2>
<table align="left" border="1">
<tr>
<th>Employee ID</th>
<th>Employee Name</th>
<th>Employee Age</th>
<th>Employee Salary</th>
<th>Employee Address</th>
<th>Actions on Row</th>
</tr>
<c:forEach items="${employees}" var="employee">
<tr>
<td><c:out value="${employee.id}"/></td>
<td><c:out value="${employee.name}"/></td>
<td><c:out value="${employee.age}"/></td>
<td><c:out value="${employee.salary}"/></td>
<td><c:out value="${employee.address}"/></td>
<td align="center">Edit | Delete</td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
employeeList.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>All Employees</title>
</head>
<body>
<h1>List Employees</h1>
<h3>Add More Employee</h3>
<c:if test="${!empty employees}">
<table align="left" border="1">
<tr>
<th>Employee ID</th>
<th>Employee Name</th>
<th>Employee Age</th>
<th>Employee Salary</th>
<th>Employee Address</th>
</tr>
<c:forEach items="${employees}" var="employee">
<tr>
<td><c:out value="${employee.id}"/></td>
<td><c:out value="${employee.name}"/></td>
<td><c:out value="${employee.age}"/></td>
<td><c:out value="${employee.salary}"/></td>
<td><c:out value="${employee.address}"/></td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring3MVC with Hibernate3 CRUD Example using Annotations</title>
</head>
<body>
<h2>Spring3MVC with Hibernate3 CRUD Example using Annotations</h2>
<h2>1. List of Employees</h2>
<h2>2. Add Employee</h2>
</body>
</html>
web.xml file
<web-app version="2.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
spring-servlet.xml file
<beans xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:component-scan base-package="com"></context:component-scan>
<tx:annotation-driven transaction-manager="hibernateTransactionManager"></tx:annotation-driven>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
<property name="driverClassName" value="org.postgresql.Driver"></property>
<property name="url" value="jdbc:postgresql://localhost:5433/databaseDb"></property>
<property name="username" value="postgres"></property>
<property name="password" value="postgres"></property>
</bean>
<bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" id="sessionFactory">
<property name="dataSource" ref="dataSource"></property>
<property name="annotatedClasses">
<list>
<value>com.model.Employee</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
</props>
</property>
</bean>
<bean class="org.springframework.orm.hibernate4.HibernateTransactionManager" id="hibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
</beans>
EmployeeController class
package com.controller;
import com.bean.EmployeeBean;
import com.model.Employee;
import com.service.EmployeeService;
import com.sun.javafx.collections.MappingChange;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.StringArrayPropertyEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import java.util.*;
/**
* Created by khan on 28/11/16.
*/
#Controller
public class EmployeeController {
#Autowired
private EmployeeService employeeService;
#RequestMapping(value = "/save", method = RequestMethod.POST)
public ModelAndView saveEmployee(#ModelAttribute("command") EmployeeBean employeeBean, BindingResult result) {
Employee employee = prepareModel(employeeBean);
employeeService.addEmployee(employee);
return new ModelAndView("redirect:/add.html");
}
#RequestMapping(value = "/employees", method = RequestMethod.GET)
public ModelAndView listEmployee() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("employees", prepareListofBean(employeeService.listEmployees()));
return new ModelAndView("employeesList", map);
}
#RequestMapping(value = "/add", method = RequestMethod.GET)
public ModelAndView addEmployee(#ModelAttribute("command") EmployeeBean employeeBean, BindingResult result) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("employees", prepareListofBean(employeeService.listEmployees()));
return new ModelAndView("addEmployee", map);
}
#RequestMapping(value = "/index", method = RequestMethod.GET)
public ModelAndView welcome() {
return new ModelAndView("index");
}
#RequestMapping(value = "/delete", method = RequestMethod.GET)
public ModelAndView editEmployee(#ModelAttribute("command") EmployeeBean employeeBean, BindingResult result) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("employee", null);
map.put("employees", prepareListofBean(employeeService.listEmployees()));
return new ModelAndView("addEmployee", map);
}
#RequestMapping(value = "/edit", method = RequestMethod.GET)
public ModelAndView deleteEmployee(#ModelAttribute("command") EmployeeBean employeeBean, BindingResult result) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("employee", prepareEmployeebean(employeeService.getEmployee(employeeBean.getId())));
map.put("employees", prepareListofBean(employeeService.listEmployees()));
return new ModelAndView("addEmployee", map);
}
private EmployeeBean prepareEmployeebean(Employee employee) {
EmployeeBean employeeBean = new EmployeeBean();
employeeBean.setAddress(employee.getEmpAddress());
employeeBean.setAge(employee.getEmpAge());
employeeBean.setSalary(employee.getEmpSalary());
employeeBean.setName(employee.getEmpName());
employeeBean.setId(employee.getEmpId());
return employeeBean;
}
private Employee prepareModel(EmployeeBean employeeBean) {
Employee employee = new Employee();
employee.setEmpAddress(employeeBean.getAddress());
employee.setEmpAge(employeeBean.getAge());
employee.setEmpName(employeeBean.getName());
employee.setEmpSalary(employeeBean.getSalary());
employee.setEmpId(null);
return employee;
}
private List<EmployeeBean> prepareListofBean(List<Employee> employees) {
List<EmployeeBean> employeeBeen = null;
if (employees != null && !employees.isEmpty()) {
employeeBeen = new ArrayList<EmployeeBean>();
EmployeeBean bean = null;
for (Employee employee : employees) {
bean = new EmployeeBean();
bean.setName(employee.getEmpName());
bean.setAge(employee.getEmpAge());
bean.setSalary(employee.getEmpSalary());
bean.setAddress(employee.getEmpAddress());
bean.setId(employee.getEmpId());
employeeBeen.add(bean);
}
}
return employeeBeen;
}
}
EmployeeService interface
package com.service;
import com.dao.EmployeeDao;
import com.model.Employee;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by khan on 28/11/16.
*/
public interface EmployeeService {
public void addEmployee(Employee employee);
public List<Employee> listEmployees();
public Employee getEmployee(int empid);
public void deleteEmployee(Employee employee);
}
EmployeeServiceImpl class
package com.serviceImpl;
import com.dao.EmployeeDao;
import com.model.Employee;
import com.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Created by khan on 28/11/16.
*/
#Service("EmployeeService")
#Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class EmployeeServiceImpl implements EmployeeService {
#Autowired
private EmployeeDao employeeDao;
#Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void addEmployee(Employee employee) {
employeeDao.addEmployee(employee);
}
public List<Employee> listEmployees() {
return (List<Employee>) employeeDao.listEmployees();
}
public Employee getEmployee(int empid) {
return employeeDao.getEmployee(empid);
}
public void deleteEmployee(Employee employee) {
employeeDao.deleteEmployee(employee);
}
}
EmployeeDao interface
package com.dao;
import com.model.Employee;
import java.util.List;
/**
* Created by khan on 28/11/16.
*/
public interface EmployeeDao {
public List<Employee> listEmployees();
public void addEmployee(Employee employee);
public Employee getEmployee(int empid);
public void deleteEmployee(Employee employee);
}
EmployeDaoImpl class
package com.daoImpl;
import com.bean.EmployeeBean;
import com.dao.EmployeeDao;
import com.model.Employee;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by khan on 28/11/16.
*/
#Repository
public class EmployeeDaoImpl implements EmployeeDao {
#Autowired
private SessionFactory sessionFactory;
#SuppressWarnings("unchecked")
public List<Employee> listEmployees() {
Transaction transaction = sessionFactory.getCurrentSession().beginTransaction();
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Employee.class);
List<Employee> list = (List<Employee>) criteria.list();
transaction.commit();
return list;
}
public void addEmployee(Employee employee) {
Transaction transaction = sessionFactory.getCurrentSession().beginTransaction();
sessionFactory.getCurrentSession().saveOrUpdate(employee);
transaction.commit();
}
public Employee getEmployee(int empid) {
return (Employee) sessionFactory.getCurrentSession().get(Employee.class, empid);
}
public void deleteEmployee(Employee employee) {
Transaction transaction = sessionFactory.getCurrentSession().beginTransaction();
sessionFactory.getCurrentSession()
.createQuery("Delete from Employee where id=" + employee.getEmpId()).executeUpdate();
transaction.commit();
}
}
Employee class
package com.model;
import javax.persistence.*;
/**
* Created by khan on 28/11/16.
*/
#Entity
#Table(name = "Employee")
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "empid")
private Integer empId;
#Column(name = "empage")
private Integer empAge;
#Column(name = "empname")
private String empName;
#Column(name = "empaddress")
private String empAddress;
#Column(name = "empsalary")
private Long empSalary;
public Integer getEmpId() {
return empId;
}
public void setEmpId(Integer empId) {
this.empId = empId;
}
public Integer getEmpAge() {
return empAge;
}
public void setEmpAge(Integer empAge) {
this.empAge = empAge;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getEmpAddress() {
return empAddress;
}
public void setEmpAddress(String empAddress) {
this.empAddress = empAddress;
}
public Long getEmpSalary() {
return empSalary;
}
public void setEmpSalary(Long empSalary) {
this.empSalary = empSalary;
}
}
EmployeeBean class
package com.bean;
import org.omg.CORBA.INTERNAL;
/**
* Created by khan on 28/11/16.
*/
public class EmployeeBean {
private Integer id;
private Integer age;
private String name;
private Long salary;
private String address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getSalary() {
return salary;
}
public void setSalary(Long salary) {
this.salary = salary;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Please Help me i try but not getting how to solve this.
Thanks every buddy in advance
change your form action to
<form:form action="${pageContext.request.contextPath}/save.html" method="POST">
..
</form:form>

Spring / Hibernate - NullPointerException

I am completely new to Spring (MVC) and Hibernate and I am trying to learn it.
I made up the following authentication scenario to practice but I am not having much luck getting it to work.
Scenario:
I have an HTML form (homepageForm.jsp) that sends username and password to HomeController.
The HomeController gets the form parameters (username/password) and compares the form params to username & password retrieved from a database.
If there's a match, the user will be presented with the dashboard.jsp. If there's a mismatch, the error.jsp will be loaded instead.
The information from the db is retrieved by the "UserRetrievalService".
I am getting the following error:
:::: ERROR
type Exception report
message Request processing failed; nested exception is java.lang.NullPointerException
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.NullPointerException
com.springdemo.mvc.HomeController.processLoginForm(HomeController.java:91)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
I suspect it's related to the way the servlet.xml is referenced.
The line 91 in the HomeController is this one:
User user = userRetrievalService.getUser();
or perhaps I am using the #Autowired incorrectly.
Could anyone please give me some tips how to resolve this?
Thank you!
Here's some additional info about the project.
**** servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.springdemo.mvc" />
<context:component-scan base-package="com.springdemo.model" />
<mvc:annotation-driven/>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
**** 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" id="WebApp_ID" version="3.1">
<display-name>spring-mvc-demo</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
**** homepageForm.jsp
<html>
<head>
<title>Homepage Form</title>
</head>
<body>
<form action="processLogin" method="POST">
<div>
<label>Username</label> <input type="text" name="username" placeholder="username" />
</div>
<div>
<label>Password</label> <input type="text" name="password" placeholder="password" />
</div>
<input type="submit" value="Login" />
</form>
</body>
</html>
**** User.java
package com.springdemo.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "user")
public class User implements AbstractUser {
#Id
#Column(name = "id")
private int id;
#Column(name = "username")
private String username;
#Column(name = "password")
private String password;
#Column(name = "first_name")
private String firstname;
#Column(name = "last_name")
private String lastname;
#Column(name = "email")
private String email;
public User() {
}
public User(int id, String username, String password, String firstname, String lastname, String email) {
super();
this.id = id;
this.username = username;
this.password = password;
this.firstname = firstname;
this.lastname = lastname;
this.email = email;
}
+ getters & setters
}
**** UserService
public interface UserService {
public User getUser();
}
**** UserRetrievalService
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.stereotype.Component;
#Component
public class UserRetrievalService implements UserService {
#Override
public User getUser() {
System.out.println("UserRetrievalService called...");
Configuration config = new Configuration().configure("hibernate.cfg.xml");
config.addAnnotatedClass(User.class);
SessionFactory sessionFactory = config.buildSessionFactory();
// create a session
Session session = sessionFactory.getCurrentSession();
try {
// start trans
session.beginTransaction();
// get & create user
User user = session.get(User.class, 1);
// commit trans
session.getTransaction().commit();
System.out.println("UserRetrievalService : commit successful...");
System.out.println(" >>>> USER: " + user.getId() + " " + user.getUsername() + " " + user.getPassword() + " " + user.getFirstname() + " " + user.getLastname());
return user;
} finally {
sessionFactory.close();
}
}
}
**** HomeController.java
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.springdemo.model.User;
import com.springdemo.model.UserRetrievalService;
#Controller
public class HomeController {
...
private UserRetrievalService userRetrievalService;
#Autowired
public UserRetrievalService getUserRetrievalService() {
return userRetrievalService;
}
#RequestMapping("/processLogin")
public ModelAndView processLoginForm(HttpServletRequest request) {
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("username : " + username);
System.out.println("password : " + password);
User user = userRetrievalService.getUser();
ModelAndView modelAndView;
if (username.equalsIgnoreCase(user.getUsername()) && (password.equalsIgnoreCase(user.getPassword()))) {
modelAndView = new ModelAndView("dashboard"); // page to be returned
} else {
modelAndView = new ModelAndView("error"); // page to be returned
}
// System.out.println("success: user id = " + user.getId());
modelAndView.addObject("myUser", user);
return modelAndView;
}
...
}
::::: hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- JDBC Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/springtestdb?useSSL=false</property>
<property name="connection.username">*****</property>
<property name="connection.password">*****</property>
<!-- JDBC connection pool settings ... using built-in test pool -->
<property name="connection.pool_size">1</property>
<!-- Select our SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo the SQL to stdout -->
<property name="show_sql">true</property>
<!-- Set the current session context -->
<property name="current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
Your UserRetrievalService not properly injected.
You can use #Autowired or Constructor/Setter injection. In your case you used setter injection but not in a proper way
It should be like
private UserRetrievalService userRetrievalService;
#Autowired
public UserRetrievalService setUserRetrievalService(UserRetrievalService userRetrievalService) {
this.userRetrievalService = userRetrievalService;
}
Suggestion regarding hibernate configuraion.
You need keep hibernate.cfg.xml under classpath
As yours is maven project, the ideal place would be /src/main/resources/
Please refer to https://stackoverflow.com/a/29352557/7063373 for more clarity.
According to the Javadoc for Autowired, the annotation can be used on "a constructor, field, setter method or config method". In HomeController put Autowired annotation in service field.
#Autowired
private UserRetrievalService userRetrievalService;

Spring MVC form error

I am trying to run a project in Spring MVC. Here is the code
index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome to Spring Web MVC project</title>
</head>
<body>
<h1>Spring 3 Register!</h1>
click
<form:form action="${pageContext.request.contextPath}/register" method="POST" modelAttribute="userForm">
<table>
<tr>
<td colspan="2" align="center">Spring MVC Form Demo - Registration</td>
</tr>
<tr>
<td>User Name</td>
<td><form:input path="username" /></td>
</tr>
<tr>
<td>Password</td>
<td><form:password path="password" /></td>
</tr>
<tr>
<td>Email</td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td>BirthDate (mm/dd/yyyy)</td>
<td><form:input path="birthDate" /></td>
</tr>
<tr>
<td>Profession</td>
<td><form:select path="profession" items="${professionList}" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Register" /></td>
</tr>
</table>
</form:form>
</body>
</html>
RegistrationController.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package RegisterInfo;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
*
* #author Harshit Shrivastava
*/
import RegisterInfo.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.Model;
#Controller
#RequestMapping(value = "/register")
public class RegistrationController {
#RequestMapping(method = RequestMethod.GET)
public String viewRegistration(Model model)
{
User userForm = new User();
model.addAttribute("userForm", new User());
/*List<String> professionList = new ArrayList();
professionList.add("Developer");
professionList.add("Designer");
professionList.add("IT Manager");
model.put("professionList", professionList);*/
return "index";
}
#RequestMapping(method = RequestMethod.POST)
public String processRegistration(#ModelAttribute("userForm") User user, Map<String, Object> model)
{
System.out.println("Username : " + user.getUserName());
model.put("userForm", new User());
return "index";
}
}
User.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package RegisterInfo.model;
/**
*
* #author Harshit Shrivastava
*/
import java.util.Date;
public class User {
private String username;
private String password;
private String email;
private Date birthDate;
private String profession;
public String getUserName()
{
return username;
}
public void setUserName(String username)
{
this.username = username;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public Date getBirthDate()
{
return birthDate;
}
public void setBirthDate(Date birthDate)
{
this.birthDate = birthDate;
}
public String getProfession()
{
return profession;
}
public void setProfession(String profession)
{
this.profession = profession;
}
}
dispatcher-servlet.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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd ">
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<context:component-scan base-package="SpringRegister" />
<mvc:annotation-driven />
<!--
Most controllers will use the ControllerClassNameHandlerMapping above, but
for the index controller we are using ParameterizableViewController, so we must
define an explicit mapping for it.
-->
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<!--
The index controller.
-->
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
</beans>
In the above program, Whenever I go to http://localhost:8080/SpringRegister/index.htm, I always gets this error
Error:
neither bindingresult nor plain target object for bean 'userForm' available as request attribute
What is wrong with the code?
When you hit the http://localhost:8080/SpringRegister/index.htm from browser, Your request is handled by ParameterizableViewController which does not set the model attribute (userForm) and forwards to index.jsp, the index.jsp's form tag expects the model attribute userForm <form:form action="${pageContext.request.contextPath}/register" method="POST" modelAttribute="userForm"> , which is not available. that why the error. To resolve this you can create your own conrtoller which handles your http://localhost:8080/SpringRegister/index.htm URL,
ModelAndView modelAndView = new ModelAndView("your view name");
model.addAttribute("userForm", new User());
configure that controller instead of class="org.springframework.web.servlet.mvc.ParameterizableViewController" in your servlet xml. Hope this helps.
You need to Change in Controller To bind userForm with Bean ----
Jsp Form --
<form:form action="userAction" modelAttribute="userForm " class="form-search" role="form">
Controller --
#RequestMapping (value = "/userAction")
public ModelAndView checkFeasibility(#ModelAttribute("userForm ")User userForm)
{
// Any Action
model.addObject("userForm",userForm);
return model;
}
In order to Bind userForm modelAttribute of form with User Bean.

Request processing failed; nested exception is org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned

UserBean.java
package com.school.bean;
public class UserBean
{
private Integer uid;
private String uname;
private String password;
private String email;
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
UserController.java
i am not sure with the use of #ModelAttribute
I am using it to accept input from user.
package com.school.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.school.bean.UserBean;
import com.school.model.User;
import com.school.service.UserService;
import com.school.model.UserRole;
import com.school.service.UserRoleService;
import com.school.bean.UserRoleBean;
#Controller
public class UserController {
#Autowired
private UserService userService;
private UserRoleService userRService;
int urole=0;
#RequestMapping(value = "/save", method = RequestMethod.POST)
public ModelAndView saveUser(#ModelAttribute("user") UserBean userBean,BindingResult result)
{
User user = prepareModel(userBean);
userService.addUser(user);
saveUserRole(user);
return new ModelAndView("index");
}
#RequestMapping(value = "/index", method = RequestMethod.GET)
public ModelAndView welcome() {
System.out.println("signup!!!\n/n");
return new ModelAndView("index");
}
#RequestMapping(value = "/add")
public ModelAndView signup()
{
urole=2; //for normal user
System.out.println("signup!!!\n/n");
return new ModelAndView("addUser");
}
#RequestMapping(value = "/member")
public ModelAndView becomeMember()
{
urole=1; //for school admin
return new ModelAndView("addUser");
}
private User prepareModel(UserBean userBean){
User user = new User();
user.setUserId(userBean.getUid());
user.setUserPassword(userBean.getPassword());
user.setUserEmail(userBean.getEmail());
userBean.setUid(null);
return user;
}
}
UserDaoImpl.java (i am avoiding the UserDao Interface)
package com.school.dao;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.school.model.User;
#Repository("userDao")
public class UserDaoImpl implements UserDao {
#Autowired
private SessionFactory sessionFactory;
public void addUser(User user) {
sessionFactory.getCurrentSession().save(user);
}
public User getUser(String uName){
return (User) sessionFactory.getCurrentSession().get(User.class,uName);
}
}
User.java
package com.school.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="User")
public class User implements Serializable{
private static final long serialVersionUID = -723583058586873479L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name = "userid")
private Integer userId;
#Column(name="username")
private String username;
#Column(name="userpassword")
private String userPassword;
#Column(name="useremail")
private String userEmail;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
}
UserServiceImpl.java(Again avoiding interface UserService
package com.school.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.school.dao.UserDao;
import com.school.model.User;
#Service("userService")
#Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class UserServiceImpl implements UserService {
#Autowired
private UserDao userDao;
#Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void addUser(User user) {
userDao.addUser(user);
}
public User checkUser(String uName)
{
return (userDao.getUser(uName));
}
}
addUser.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>School Review System SignUp</title>
</head>
<body>
<form:form method="POST" action="/AuthorizationAndAuthentication/save.html">
<table>
<tr>
<td><label >USERID</label></td>
<td><input value="${user.uid}" readonly="true" ></td>
</tr>
<tr>
<td><label>USERNAME</label></td>
<td><input value="${user.uname}"></td>
</tr>
<tr>
<td><label>PASSWORD</label></td>
<td><input value="${user.password}"></td>
</tr>
<tr>
<td><label>EMAIL</label></td>
<td><input value="${user.email}"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit"/></td>
</tr>
</table>
</form:form>
</body>
sdnext-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
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/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:property-placeholder location="classpath:resources/database.properties"/>
<context:component-scan base-package="com.school.controller com.school.dao com.school.service"/>
<tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/DAVDB" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.school.model.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Your persistence provider is not able to determine which strategy should use for ID generation. It depens on db used as well, as some db dosn't suport sequence or identity.
try to specify concrete id generation strategypersistence provider.
strategy=GenerationType.IDENTITY
//not for mysql
strategy=GenerationType.SEQUENCE
or set up proper hibernate.dialect in your config
<bean id="SessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
</props>
</property>
</bean>

Persisting to MySQL using Spring Framework, Hibernate and JPA failed, not really persisting to the database

I was reading all the posts on this issue, but none of them helped.
I am trying to persist my entity to MySQL using Hibernate, JPA on Spring Framework 3.0.1. I can find rows from database and display, to do that when the form displayed the textbox holds fields fron the database, but when I try to save to the database, it doesn't change any row at all.
My configuration looks like below ...
My persistence.xml ...
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="userpersistence" transaction-type="RESOURCE_LOCAL">
<provider>
org.hibernate.ejb.HibernatePersistence
</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/acctdatabase"/>
<property name="hibernate.connection.username" value="acct-user"/>
<property name="hibernate.connection.password" value="password"/>
</properties>
</persistence-unit>
</persistence>
My Entity:
package edu.acct.tsegay.model;
import javax.enterprise.context.RequestScoped;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.Version;
import org.springframework.beans.factory.annotation.Autowired;
#Entity
#Table(name = "programs")
public class Program {
private int prog_Id;
private String prog_Name;
public Program() {
super();
}
// #GeneratedValue
#Id
public int getProg_Id() {
return prog_Id;
}
public void setProg_Id(int progId) {
prog_Id = progId;
}
public String getProg_Name() {
return prog_Name;
}
public void setProg_Name(String progName) {
prog_Name = progName;
}
public String toString() {
return "This is a String";
}
}
My DAO:
package edu.acct.tsegay.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import edu.acct.tsegay.model.Program;
#Repository
public class ProgramDaoImpl implements IProgramDao {
protected EntityManager entityManager;
#PersistenceContext
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
#SuppressWarnings("unchecked")
public List<Program> getProgram(int progId) {
// TODO Auto-generated method stub
return entityManager.createQuery("from program o").getResultList();
}
public void save(Program program) {
entityManager.merge(program);
}
public Program getProg(int id) {
return entityManager.createQuery(
"SELECT c FROM Program c WHERE c.prog_Id = :id", Program.class)
.setParameter("id", id).getSingleResult();
}
}
My Service:
package edu.acct.tsegay.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import edu.acct.tsegay.dao.IProgramDao;
import edu.acct.tsegay.model.Program;
#Service("programSerivce")
public class ProgramServiceImpl implements IProgramService {
#Autowired
private IProgramDao programDao;
public IProgramDao getProgramDao() {
return programDao;
}
public void setProgramDao(IProgramDao programDao) {
this.programDao = programDao;
}
#Transactional(propagation = Propagation.REQUIRES_NEW)
public void save(Program program) {
programDao.save(program);
}
public Program getProgram(int id) {
return programDao.getProg(id);
}
}
My contextApplication
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
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/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="org.h2.Driver"
p:url="jdbc:h2:mem:gallery;DB_CLOSE_DELAY=-1" p:username="sa"
p:password="" />
<bean id="mysqlDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.databaseurl}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="mysqlDataSource" />
<!-- MYSQL SERVER 2008 database connection -->
<bean id="entityManagerFactoryMSSQL"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="mssqlDataSource" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory" />
<bean id="userDao" class="edu.acct.tsegay.dao.UserDaoJpa" />
<bean id="programDao" class="edu.acct.tsegay.dao.ProgramDaoImpl" />
<bean id="userSerivce" class="edu.acct.tsegay.service.UserServiceImpl" />
<bean id="programSerivce" class="edu.acct.tsegay.service.ProgramServiceImpl" />
<tx:annotation-driven mode="aspectj"
transaction-manager="transactionManager" />
</beans>
My Controller:
package edu.acct.tsegay.controller;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import edu.acct.tsegay.model.Program;
import edu.acct.tsegay.model.User;
import edu.acct.tsegay.service.IProgramService;
import edu.acct.tsegay.service.IUserService;
#Controller
public class HelloController {
#Autowired
#Qualifier("userSerivce")
private IUserService<User> userService;
#Autowired
#Qualifier("programSerivce")
private IProgramService programService;
public void setUserService(IUserService<User> userService) {
this.userService = userService;
}
public void setProgramService(IProgramService programService) {
this.programService = programService;
}
#RequestMapping(value = "/form", method = RequestMethod.GET)
public ModelAndView displayForm(ModelAndView model) {
Program program = new Program();
program.setProg_Name(programService.getProgram(16).getProg_Name());
model.addObject("program", program);
return model;
}
// Process the form.
#SuppressWarnings("unchecked")
#RequestMapping(value = "/form", method = RequestMethod.POST)
public String processForm(Program program, Map model) {
Program prog = new Program();
prog.setProg_Name("New progrma");
programService.save(prog);
Program pro = programService.getProgram(17);
// Add the saved book to the model
model.put("pro", pro);
model.put("program", program);
return "program";
}
#RequestMapping("/bye")
public ModelAndView sayBye() {
ModelAndView model = new ModelAndView("bye");
model.addObject("msg", "This is a Message from Tsegay done ..");
return model;
}
#RequestMapping("/footer")
public ModelAndView displayFooter() {
ModelAndView model = new ModelAndView("footer");
model.addObject("msg", "This is a footer ..");
return model;
}
}
My view
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Tsegay | Form</title>
</head>
<body>
<form:form action="form.tsegay" method="POST" commandName="program">
<table>
<tr>
<td>First Name:</td>
<td><form:input path="Prog_Id" /> <form:errors path="Prog_Id" />
</td>
</tr>
<tr>
<td>Password:</td>
<td><form:input path="Prog_Name" /> <form:errors
path="Prog_Name" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Login" /></td>
</tr>
</table>
</form:form>
</body>
</html>
The forum post Transactions are not starting saved my life. You need to update (see the question):
<tx:annotation-driven mode="proxy"
transaction-manager="transactionManager" />

Categories