my code is executed successfully but data not stored in database with spring and hibernate - spring

when i am going to execute this program.
my program is successfully executed but it doesn't store data in database.
what is the problem in this program.
this is my Employee.java class
package com.spring.demo;
public class Employee {
private int id;
private String name;
private float salary;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
}
this is my EmployeeDao.java class
package com.spring.demo;
import org.springframework.orm.hibernate5.HibernateTemplate;
public class EmployeeDao {
HibernateTemplate template;
public void setTemplate(HibernateTemplate template) {
this.template = template;
}
public void saveEmployee(Employee e) {
Integer i = (Integer) template.save(e);
if (i > 0) {
System.out.println("Success");
} else {
System.out.println("Not Success");
}
}
public void updateEmployee(Employee e) {
template.update(e);
}
public void deleteEmployee(Employee e) {
template.delete(e);
}
}
this is my Test.java class
package com.spring.demo;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext bean = new
ClassPathXmlApplicationContext("spring.xml");
EmployeeDao emp = (EmployeeDao) bean.getBean("obj");
Employee e = new Employee();
e.setId(2);
e.setName("Amit Goyal");
e.setSalary(40000);
emp.saveEmployee(e);
// emp.updateEmployee(e);
bean.close();
}
}
this is my Employee.hbm.xml file
<?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>
<class name="com.spring.demo.Employee" table="amit1234">
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="name"></property>
<property name="salary"></property>
</class>
</hibernate-mapping>
and last this is my spring.xml file
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-
4.2.xsd">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:#localhost:1521:xe" />
<property name="username" value="system" />
<property name="password" value="tiger" />
</bean>
<bean id="mysessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mappingResources">
<list>
<value>Employee.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.Oracle10gDialect
</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="template"
class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="mysessionFactory"></property>
<property name="checkWriteOperations" value="false"></property>
</bean>
<bean id="obj" class="com.spring.demo.EmployeeDao">
<property name="template" ref="template"></property>
</bean>
</beans>

In this configuration you are missing transaction management configuration. Use #transactional annotation over your service method.
In you situation data is not committing in the database it just save the data and not commit the data in database.

Related

Table not auto create in HeidiSql(mysql) by spring hibernate. And no error shows in console but jdbc details missing, my code details given below

Table not auto create in HeidiSql(mysql) by spring hibernate. And no error shows in console but jdbc details missing, my code details given below
Model class
my entity java class
#Entity
#Table(name = "Payment_Table")
public class Payment implements Serializable {
private static final long serialVersionUID = 4501753715497967062L;
#Id
#GeneratedValue
private int id;
private String transactionId;
private String vendor;
private Date paymentDate;
private double amount;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTransactionId() {
return transactionId;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
public String getVendor() {
return vendor;
}
public void setVendor(String vendor) {
this.vendor = vendor;
}
public Date getPaymentDate() {
return paymentDate;
}
public void setPaymentDate(Date paymentDate) {
this.paymentDate = paymentDate;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public Payment() {
super();
// TODO Auto-generated constructor stub
}
public Payment(String transactionId, String vendor, Date paymentDate, double amount) {
super();
this.transactionId = transactionId;
this.vendor = vendor;
this.paymentDate = paymentDate;
this.amount = amount;
}
}
application-context.xml
my data base configuration
<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/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.spring.rest.curd.model.Payment</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernet.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
web.xml
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/application-context.xml</param-value>
</context-param>
<display-name>Spring Rest Application</display-name>
<servlet>
<servlet-name>springRest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>springRest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
springRest-servlet.xml
<context:component-scan base-package="com.spring.rest.curd.*"></context:component-scan>
<mvc:annotation-driven />
<tx:annotation-driven />

Unable to insert record into DB using hibernate integrated with Spring using XML

I am trying to implement a signup page using Spring MVC integrated with hibernate using XML.
Application Context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
xmlns:tx="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">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
<property name="url" value="jdbc:oracle:thin:#localhost:1521:xe"></property>
<property name="username" value="hr"></property>
<property name="password" value="umashetti123"></property>
</bean>
<bean id="mysessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mappingResources">
<list>
<value>Login_Detailshbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="checkWriteOperation" >false</prop>
</props>
</property>
</bean>
<bean id="template" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="mysessionFactory"></property>
<property name="checkWriteOperations" value="false"></property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="mysessionFactory" />
</bean>
<bean id="d" class="com.uday.Login_DetailsDao">
<property name="template" ref="template"></property>
</bean>
</beans>
Controller Class
package com.uday;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
#Controller
public class ControllerSignUp_Login {
public ControllerSignUp_Login() {
// TODO Auto-generated constructor stub
}
#RequestMapping("/hello")
public String diaplay(#RequestParam("name") String name, #RequestParam("pass") String pass,Model m) {
Login_DetailsDao dao = (Login_DetailsDao) getBean();
if(dao.isLogoinSuccessfull(name , pass)) {
m.addAttribute("message", "Hello"+name);
return "Success";
}
else {
m.addAttribute("message", "You have Entered Wrong pin");
return "Failure";
}
}
#RequestMapping("/SignUp")
public String redirect() {
System.out.println("ControllerSignUp_Login.display()");
return "signup";
}
#RequestMapping("/login")
public String display() {
System.out.println("ControllerSignUp_Login.display()");
return "login";
}
#RequestMapping("/updateDetails")
#Transactional
public String display(HttpServletRequest req , Model M) {
String firstName=req.getParameter("firstName");
String lastName=req.getParameter("lastName");
String mobileNo=req.getParameter("mobileNo");
String address=req.getParameter("address");
String city=req.getParameter("city");
String password=req.getParameter("password");
Login_DetailsDao dao = (Login_DetailsDao) getBean();
if(checkLength(firstName) && checkLength(lastName) && checkLength(mobileNo) && checkLength(address) && checkLength(city) && checkLength(password)) {
Login_Details ld = new Login_Details();
ld.setFirstName(firstName);
ld.setLastName(lastName);
ld.setCity(city);
ld.setAddress(address);
ld.setMobileNo(mobileNo);
ld.setPassword(password);
dao.saveEmployee(ld);
M.addAttribute("message", "SignUp Successfull !! Thank You");
M.addAttribute("displayLogin", true);
return "Success";
}
else {
M.addAttribute("message","SignUp Failed !! All details are mandatory.");
return "signup";
}
}
public boolean checkLength(String s) {
if(s != null && s.length() > 0) {
return true;
}
return false;
}
public Object getBean() {
ApplicationContext appcontext = new ClassPathXmlApplicationContext("Applicationcontext.xml");
Login_DetailsDao lDDao =(Login_DetailsDao)appcontext.getBean("d");
return lDDao;
}
}
DAO class
package com.uday;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.transaction.annotation.Transactional;
public class Login_DetailsDao {
HibernateTemplate template;
HibernateTransactionManager hbt;
public HibernateTransactionManager getHbt() {
return hbt;
}
public void setHbt(HibernateTransactionManager hbt) {
this.hbt = hbt;
}
public Login_DetailsDao() {
// TODO Auto-generated constructor stub
}
#Transactional
public void saveEmployee(Login_Details e){
System.out.println("Login_DetailsDao.saveEmployee()"+e.getMobileNo());
SessionFactory sf = hbt.getSessionFactory();
Session session =sf.getCurrentSession();
Transaction t =session.beginTransaction();
session.persist(e);
t.commit();
session.close();
}
public void setTemplate(HibernateTemplate template) {
this.template = template;
}
public List<Login_Details> getEmployees(){
List<Login_Details> list=new ArrayList<Login_Details>();
list=template.loadAll(Login_Details.class);
return list;
}
}
I am able to get the login_details data but unable to insert the record.
getting below exception
org.xml.sax.SAXParseException; lineNumber: 51; columnNumber: 29; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'.
Could any one please suggest to solve this?
Your code is flawed on multiple levels.
Never create a BeanFactory or ApplicationContext just because you need an instance of a bean. Instead use dependency injecting for that bean.
The fact that you use a BeanFactory over an ApplicationContext is one of the reasons your code doesn't work. See this for why you shouldn't use a BeanFactory.
You aren't using transactions and without transactions nothing will be persisted in the database.
Now first in your controller you need to dependency inject the Login_DetailsDao instead of creating a BeanFactory and obtain an instance.
#Controller
public class ControllerSignUp_Login {
private final Login_DetailsDao dao;
#Autowired // If using Spring 4.3 or later this isn't needed
public ControllerSignUp_Login(Login_DetailsDao dao) {
this.dao=dao;
}
}
Now in your method use this instance, instead of doing the lookup.
Your Login_DetailsDao should operate on the SessionFactory and nothing else.
public class Login_DetailsDao {
private final SessionFactory sf;
public Login_DetailsDao(SessionFactory sf) {\
this.sf=sf;
}
#Transactional
public void saveEmployee(Login_Details e){
sf.getCurrentSession().save(e);
}
#Transactional(readOnly=true)
public List<Login_Details> getEmployees(){
return sf.getCurrentSession()
.createQuery("SELECT ld FROM Login_Details", Login_Details.class)
.getResult();
}
}
That is all you need. Now finally in your XML tie all this together.
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"
xmlns:tx="http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<tx:annotation-driven />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
<property name="url" value="jdbc:oracle:thin:#localhost:1521:xe"></property>
<property name="username" value="hr"></property>
<property name="password" value="umashetti123"></property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mappingResources">
<list>
<value>Login_Detailshbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="checkWriteOperation" >false</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="d" class="com.uday.Login_DetailsDao">
<constructor-arg ref="sessionFactory" />
</bean>
</beans>
One simple change made this application worked.
1 > Deleted applicationcontext.xml and added the contents in disapatcher-servlet.xml
disaptcher-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"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:annotation-config/>
<tx:annotation-driven />
<!-- Provide support for component scanning -->
<context:component-scan base-package="com.uday" />
<!--Provide support for conversion, formatting and validation -->
<mvc:annotation-driven/>
<!-- Define Spring MVC view resolver -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/page/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
<property name="url" value="jdbc:oracle:thin:#localhost:1521:xe"></property>
<property name="username" value="hr"></property>
<property name="password" value="umashetti123"></property>
</bean>
<bean id="mysessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mappingResources">
<list>
<value>Login_Detailshbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="checkWriteOperation" >false</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="mysessionFactory" />
</bean>
<bean id="d" class="com.uday.Login_DetailsDao">
<constructor-arg ref="mysessionFactory" />
</bean>
</beans>
DAO Class:
package com.uday;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;
public class Login_DetailsDao {
private final SessionFactory sessionFactory;
public Login_DetailsDao(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Transactional
public void saveEmployee(Login_Details e){
sessionFactory.getCurrentSession().save(e);
}
public boolean isLogoinSuccessfull(String uName , String password) {
List<Login_Details> a= getEmployees();
Iterator<Login_Details> i = a.iterator();
while(i.hasNext()) {
Login_Details ld = i.next();
String mobileNo = ld.getMobileNo();
String pas = ld.getPassword();
if(mobileNo != null && mobileNo.equals(uName) && pas != null && pas.equals(password)) {
return true;
}
}
return false;
}
#Transactional
public List<Login_Details> getEmployees(){
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Login_Details.class);
List<Login_Details> l = criteria.list();
return l;
}
}
Controller Class:
package com.uday;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
#Controller
public class ControllerSignUp_Login {
#Autowired
private final Login_DetailsDao dao;
#Autowired
public ControllerSignUp_Login(Login_DetailsDao login_DetailsDao) {
this.dao = login_DetailsDao;
}
#RequestMapping("/hello")
#Transactional
public String diaplay(#RequestParam("name") String name, #RequestParam("pass") String pass,Model m) {
if(dao.isLogoinSuccessfull(name , pass)) {
m.addAttribute("message", "Hello"+name);
return "Success";
}
else {
m.addAttribute("message", "You have Entered Wrong pin");
return "Failure";
}
}
#RequestMapping("/SignUp")
public String redirect() {
System.out.println("ControllerSignUp_Login.display()");
return "signup";
}
#RequestMapping("/login")
public String display() {
System.out.println("ControllerSignUp_Login.display()");
return "login";
}
#RequestMapping("/updateDetails")
#Transactional
public String display(HttpServletRequest req , Model M) {
String firstName=req.getParameter("firstName");
String lastName=req.getParameter("lastName");
String mobileNo=req.getParameter("mobileNo");
String address=req.getParameter("address");
String city=req.getParameter("city");
String password=req.getParameter("password");
if(checkLength(firstName) && checkLength(lastName) && checkLength(mobileNo) && checkLength(address) && checkLength(city) && checkLength(password)) {
Login_Details ld = new Login_Details();
ld.setFirstName(firstName);
ld.setLastName(lastName);
ld.setCity(city);
ld.setAddress(address);
ld.setMobileNo(mobileNo);
ld.setPassword(password);
dao.saveEmployee(ld);
M.addAttribute("message", "SignUp Successfull !! Thank You");
M.addAttribute("displayLogin", true);
return "Success";
}
else {
M.addAttribute("message","SignUp Failed !! All details are mandatory.");
return "signup";
}
}
public boolean checkLength(String s) {
if(s != null && s.length() > 0) {
return true;
}
return false;
}
}
Project Structure looks like below
Instead of getting current session and making the transaction opened new session that's it worked like charm!!!
I don't know why it is not working if I am getting current session!!
#Transactional
public void saveEmployee(Login_Details e){
System.out.println("Login_DetailsDao.saveEmployee()"+e.getMobileNo());
SessionFactory sf = hbt.getSessionFactory();
//Changed here
Session session =sf.openSession(); //Session session =sf.getCurrentSession();
Transaction t =session.beginTransaction();
session.persist(e);
t.commit();
session.close();
}

Creating Table Using Hibernate and Oracle

I would like to create a simple table "account" using hibernate in an oracle database.
Here's my bean class Account:
#Entity
#Table(name = "account")
public class Account implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(nullable = false)
private String id;
#Column(nullable = false)
private String iban;
#Column(nullable = false)
private String name;
#Column(name = "`usage`", nullable = false)
private String usage;
#Column(nullable = false)
private String type;
#Column(nullable = false)
private String ccy;
#Column(nullable = false)
private String psuStatus;
#Column(nullable = false)
private String balances;
public Account() {
}
public Account(String id, String iban, String name, String usage,
String type, String ccy, String psuStatus, String balances) {
this.id = id;
this.iban = iban;
this.name = name;
this.usage = usage;
this.type = type;
this.ccy = ccy;
this.psuStatus = psuStatus;
this.balances = balances;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getIban() {
return iban;
}
public void setIban(String iban) {
this.iban = iban;
}
public String getUsage() {
return usage;
}
public void setUsage(String usage) {
this.usage = usage;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCcy() {
return ccy;
}
public void setCcy(String ccy) {
this.ccy = ccy;
}
public String getPsuStatus() {
return psuStatus;
}
public void setPsuStatus(String psuStatus) {
this.psuStatus = psuStatus;
}
public String getBalances() {
return balances;
}
public void setBalances(String balances) {
this.balances = balances;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Account other = (Account) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
And here's the config file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx" 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
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<!-- dataSource (connexion vers la base de données) -->
<!-- dataSource côté serveur <jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/myDataSource"
/> -->
<!-- datasource locale -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="removed for privacy purposes" />
<property name="username" value="removed for privacy purposes" />
<property name="password" value="removed for privacy purposes" />
</bean>
<!-- support d'annotations JPA -->
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<!-- config de la sessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>fr.bnpparibas.dsp2aisp.beans</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQL5InnoDBDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<!-- <prop key="hibernate.generate_statistics">true</prop> -->
<prop key="hibernate.hbm2ddl.auto">create</prop> <!-- update -->
<!-- Cache de niv2 -->
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.region.factory_class">
org.hibernate.cache.ehcache.EhCacheRegionFactory
</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<!-- Configuring Connection Pool -->
<prop key="hibernate.c3p0.min_size">5</prop>
<prop key="hibernate.c3p0.max_size">20</prop>
<prop key="hibernate.c3p0.timeout">50</prop>
<prop key="hibernate.c3p0.max_statements">50</prop>
<prop key="hibernate.c3p0.idle_test_period">2000</prop>
</props>
</property>
</bean>
<!-- support des transactions par annotations #Transactional -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
<property name="autodetectDataSource" value="true" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- MailService -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<!-- SMTP settings -->
<property name="host" value="smtp.dsl.ovh.net" />
<!-- <property name="port" value="21" /> -->
<!-- <property name="username" value="USER_NAME" />
<property name="password" value="PASSWORD" /> -->
<property name="javaMailProperties">
<!-- additional properties specific to JavaMail -->
<props>
<prop key="mail.transport.protocol">smtp</prop>
<prop key="mail.smtp.auth">false</prop>
<prop key="mail.smtp.starttls.enable">false</prop>
</props>
</property>
</bean>
<!-- surcouche de l'entityManager => Hibernate -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="accountDao" class="fr.bnpparibas.dsp2aisp.daos.AccountDao">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>
</beans>
The problem is, when I run the app, it doesn't create the table account in the database. I used the same example with an MySQL JDBC driver and a wampserver and it worked perfectly. But with an Oracle driver, for some reason, it doesn't work. Anybody knows why?
UPDATE: I was able to display the error by setting the hbm2ddl logger to true, and here's what I have now:
java.sql.SQLException: Listener refused the connection with the following error:
ORA-12505, TNS:listener does not currently know of SID given in connect descriptor
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:673)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:711)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:385)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:30)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:558)
at java.sql.DriverManager.getConnection(DriverManager.java:675)
at java.sql.DriverManager.getConnection(DriverManager.java:219)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:153)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:144)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:196)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:159)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
at org.hibernate.tool.hbm2ddl.SuppliedConnectionProviderConnectionHelper.prepare(SuppliedConnectionProviderConnectionHelper.java:33)
at org.hibernate.tool.hbm2ddl.DatabaseExporter.<init>(DatabaseExporter.java:35)
at org.hibernate.tool.hbm2ddl.SchemaExport.execute(SchemaExport.java:425)
at org.hibernate.tool.hbm2ddl.SchemaExport.create(SchemaExport.java:361)
at org.hibernate.tool.hbm2ddl.SchemaExport.create(SchemaExport.java:350)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:469)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:711)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:727)
at org.springframework.orm.hibernate5.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:511)
at org.springframework.orm.hibernate5.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:495)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1688)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1626)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:742)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:443)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at com.ibm.ws.webcontainer.webapp.WebApp.notifyServletContextCreated(WebApp.java:2384)
at com.ibm.ws.webcontainer31.osgi.webapp.WebApp31.notifyServletContextCreated(WebApp31.java:514)
at com.ibm.ws.webcontainer.webapp.WebApp.initialize(WebApp.java:1012)
at com.ibm.ws.webcontainer.webapp.WebApp.initialize(WebApp.java:6574)
at com.ibm.ws.webcontainer.osgi.DynamicVirtualHost.startWebApp(DynamicVirtualHost.java:467)
at com.ibm.ws.webcontainer.osgi.DynamicVirtualHost.startWebApplication(DynamicVirtualHost.java:462)
at com.ibm.ws.webcontainer.osgi.WebContainer.startWebApplication(WebContainer.java:1132)
at com.ibm.ws.webcontainer.osgi.WebContainer.access$000(WebContainer.java:108)
at com.ibm.ws.webcontainer.osgi.WebContainer$3.run(WebContainer.java:944)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:522)
at java.util.concurrent.FutureTask.run(FutureTask.java:277)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1153)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.lang.Thread.run(Thread.java:785)
Does this mean that I need to define the oracle schema?
UPDATE 2: Now I have this error:
14:29:58.026 [Default Executor-thread-12] ERROR org.hibernate.tool.hbm2ddl.SchemaExport - HHH000389: Unsuccessful: create table account (id varchar(255) not null, balances varchar(255) not null, ccy varchar(255) not null, iban varchar(255) not null, name varchar(255) not null, psuStatus varchar(255) not null, type varchar(255) not null, `usage` varchar(255) not null, primary key (id)) ENGINE=InnoDB
14:29:58.027 [Default Executor-thread-12] ERROR org.hibernate.tool.hbm2ddl.SchemaExport - ORA-00911: invalid character
But what's strange is that I'm generating the query using Hibernate. I didn't write the query myself.

javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread cannot reliably process

I am trying to upgrade Spring from 4.0.6 to 4.3.9 version. While doing so I am getting following error "javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread". Entire code was working fine earlier but I am getting this error just because of library upgrade. Hibernate version which is being used in my project is 4.3.7.
Here is my applicationcontext.xml
<beans default-autowire="byName"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="premier" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="false" />
</bean>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#***:1521:PSPRODDB" />
<property name="username" value="**" />
<property name="password" value="*****" />
</bean>
<!-- entity manager configuration -->
<!--<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- externals -->
<bean id="mapperFactory" class="org.dozer.spring.DozerBeanMapperFactoryBean">
<property name="mappingFiles" value="classpath*:dozerBeanMapping.xml" />
</bean>
</beans>
My Entity class
#SuppressWarnings("serial")
#Entity
#Table(name = "ROLES")
#NamedQueries({
#NamedQuery(name = "RoleModuleMO.findById", query = "SELECT rolemodule FROM RoleModuleMO rolemodule WHERE rolemodule.id =:id");
#Proxy(lazy = false)
#EntityListeners(value = SimpleAuditListener.class)
public class RoleModuleMO implements Serializable, SimpleAuditable {
public RoleModuleMO () {
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "ROLEMODULE_ID_SQ")
#SequenceGenerator(name = "ROLEMODULE_ID_SQ", sequenceName = "ROLEMODULE_ID_SQ")
private Long id;
#Column(name="ISVISIBLE", nullable = false)
private Boolean isVisible;
#Column(name="ISENABLED", nullable = false)
private Boolean isEnabled;
#Column(name="NAME", nullable = false)
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getVisible() {
return isVisible;
}
public void setVisible(Boolean visible) {
isVisible = visible;
}
public Boolean getEnabled() {
return isEnabled;
}
public void setEnabled(Boolean enabled) {
isEnabled = enabled;
}
}
My Service class
#Transactional
public class RolesServiceImpl implements RolesService {
#PersistenceContext
private EntityManager em;
private RolesDAO rolesDAO;
private Mapper mapper;
public RolesServiceImpl(RolesDAO rolesDAO, Mapper mapper) {
this.rolesDAO = rolesDAO;
this.mapper = mapper;
}
#Transactional
public RoleModule saveOrUpdateModule(RoleModule vo) {
RoleModuleMO mo = new RoleModuleMO();
mapper.map(vo, mo);
mo = rolesDAO.saveOrUpdateModule(mo);
vo = mapper.map(mo, RoleModule.class);
return vo;
}
}
This was working in spring 4.0.6 and after upgrading to 4.3.9 facing the error.
Is there any changes made by spring community which is causing this error or there is something else which I need to change?
Thanks in advance.

CustomDateEditor not working in Spring 4.1.6

I am using a Date dob; field in my pojo class in spring 4.1.6 using maven
below are the files associated with my app.
// this is my pojo class.
package com.aamir;
import java.util.Date;
public class Student {
private String firstName;
private Date dob;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
}
// this is my client class
package com.aamir;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ClientStud1 {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) context.getBean("s1");
System.out.println(student.getFirstName());
System.out.println(student.getDob());
}
}
// and finally this is my beans.xml file
<?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"
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">
<bean id="s1" class="com.aamir.Student">
<property name="firstName" value="aamir"/>
<property name="dob" value="12-12-1996"/>
</bean>
<bean id="dateEditor"
class="org.springframework.beans.propertyeditors.CustomDateEditor">
<constructor-arg>
<bean class="java.text.SimpleDateFormat">
<constructor-arg value="dd-MM-yyyy"/>
</bean>
</constructor-arg>
<constructor-arg value="true"/>
</bean>
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.util.Date" value-ref="dateEditor"/>
</map>
</property>
</bean>
</beans>
and I get this exception every time I try to run the client
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.beans.factory.config.CustomEditorConfigurer#0' defined in class path resource [beans.xml]:
Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type 'java.util.LinkedHashMap' to required type 'java.util.Map' for property 'customEditors'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [org.springframework.beans.propertyeditors.CustomDateEditor] to required type [java.lang.Class] for property 'customEditors[java.util.Date]': PropertyEditor [org.springframework.beans.propertyeditors.ClassEditor] returned inappropriate value of type [org.springframework.beans.propertyeditors.CustomDateEditor]
Note that PropertyEditor are stateful, so you should not register instances directly.
Register property editor classes via customEditor property
Add PropertyEditorRegistrars via propertyEditorRegistrars property in CustomEditorConfigurer
As you want to configure the property editor instance, use property editor registrar instead.
<bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="propertyEditorRegistrars">
<list>
<bean class="org.example.CustomDateEditorRegistrar"/>
</list>
</property>
</bean>
As per the official documentation , the recommended way of registering a PropertyEditor is to create a class that implements propertyEditorRegistrar interface. Each propertyEditorRegistrar can register any number of propertyEditors on a given registry.
Two such implementaions are descibed below:
Approach 1: create a generalized class that implements PropertyEditorRegistrar.
This class can be used for any propertyEditor(s), so you can keep this class in your utils.
Lets name it CustomEditorRegistrar and it looks like this:
public class CustomEditorRegistrar implements PropertyEditorRegistrar
{
Class<?> t;
PropertyEditor propertyEditor;
public CustomEditorRegistrar(Class<?> t, PropertyEditor propertyEditor)
{
this.t = t;
this.propertyEditor = propertyEditor;
}
#Override
public void registerCustomEditors(PropertyEditorRegistry registry)
{
registry.registerCustomEditor(t, propertyEditor);
}
}
. The bean definition to register a CustomDateEditor is as below:
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="propertyEditorRegistrars">
<list>
<bean class="mky.spring.property.editor.date.CustomEditorRegistrar">
<constructor-arg index="0">
<value type="java.lang.Class">java.util.Date</value>
</constructor-arg>
<constructor-arg index="1">
<bean class="org.springframework.beans.propertyeditors.CustomDateEditor">
<constructor-arg index="0">
<bean class="java.text.SimpleDateFormat">
<constructor-arg value="dd-MM-yyyy" />
</bean>
</constructor-arg>
<constructor-arg index="1" value="true" />
</bean>
</constructor-arg>
</bean>
</list>
</property>
</bean>
<bean
name="Customer"
class="mky.spring.property.editor.date.Customer"
p:name="Customer 1"
p:address="CounterHills LA"
p:deliveryDate="12-11-2016"
p:issueDate="12-10-2016" />
Sys-out client:
public class TestGenericClient
{
ApplicationContext ctx;
public TestGenericClient()
{
ctx = new ClassPathXmlApplicationContext("genericPropertyEditorRegistrar-beans.xml");
}
public static void main(String[] args)
{
System.out.println(new TestGenericClient().ctx.getBean("Customer"));
}
}
And the output is this:
Name=Customer 1
Address=CounterHills LA
Issue Date=Wed Oct 12 00:00:00 GST 2016
deliveryDate=Sat Nov 12 00:00:00 GST 2016
Approach2: create a specific propertyEditorRegistrar eg, for Date
public class CustomDateEditorRegistrar implements PropertyEditorRegistrar
{
#Override
public void registerCustomEditors(PropertyEditorRegistry registry)
{
registry.registerCustomEditor(java.util.Date.class, new CustomDateEditor(new SimpleDateFormat("dd-MM-yyyyy"),true));
}
}
And the bean declaration for this specific CustomDateEditor is :
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="propertyEditorRegistrars">
<list>
<bean class="mky.spring.property.editor.date.CustomDateEditorRegistrar" />
</list>
</property>
</bean>
Sys-out cleint:
public TestDateClient()
{
ctx = new ClassPathXmlApplicationContext("datePropertyEditorRegistrar-beans.xml");
}
public static void main(String[] args)
{
System.out.println(new TestDateClient().ctx.getBean("Customer"));
}
And the same output :
Name=Customer 1
Address=CounterHills LA
Issue Date=Wed Oct 12 00:00:00 GST 2016
deliveryDate=Sat Nov 12 00:00:00 GST 2016

Resources