Migration from ObjectDB to MySQL in Spring - java

I've been using objectDB as a database in my Spring application, yet it is only free for up to 10 tables, so i've tried to migrate to MySQL. When I look into database the tables are created, but when I try to persist I get the NullPointerException. Here are my configuration files:
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">
<persistence-unit name="cinemabookPU" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>cinemaDbCon</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
</persistence>
spring-servlet.xml:
<?xml version="1.0" encoding="windows-1252"?>
<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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- Use #Component annotations for bean definitions -->
<context:component-scan base-package="cinema"/>
<!-- Use #Controller annotations for MVC controller definitions -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:annotation-driven />
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.glassfish.GlassFishLoadTimeWeaver"/>
</property>
</bean>
<tx:jta-transaction-manager />
<tx:annotation-driven />
<bean class=
"org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/"/>
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<import resource="/spring-security.xml" />
</beans>
Model City:
package cinema.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class City implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String name;
protected City() {
}
public City(Long id, String name) {
this.id = id;
this.name = name;
}
public City(String name) {
this.name = 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;
}
#Override
public String toString() {
return name;
}
}
CityService.java:
package cinema.services;
import cinema.model.City;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
public interface CityService {
// Stores a new city:
#Transactional
public void persist(City city);
// Retrieves all the citys:
public List<City> getAllCities();
public City getCityById(Long id);
public void deleteAllCities();
}
CityServiceImpl.java:
package cinema.services.impl;
import cinema.services.CityService;
import cinema.model.City;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
#Component
public class CityServiceImpl implements CityService {
// Injected database connection:
#PersistenceContext(unitName="cinemabookPU")
private EntityManager em;
public EntityManager getEm() {
return em;
}
public void setEm(EntityManager em) {
this.em = em;
}
// Stores a new city:
#Transactional
public void persist(City city) {
em = getEm();
System.out.println("EM "+em);
em.persist(city);
}
// Retrieves all the citys:
public List<City> getAllCities() {
TypedQuery<City> query = em.createQuery(
"SELECT c FROM City c", City.class);
return query.getResultList();
}
public City getCityById(Long id) {
TypedQuery<City> query = em.createQuery(
"SELECT c FROM City c WHERE c.id = :id", City.class);
return query.setParameter("id", id).getSingleResult();
}
#Transactional(propagation = Propagation.REQUIRED)
public void deleteAllCities() {
TypedQuery<City> query = em.createQuery(
"DELETE FROM City", City.class);
query.executeUpdate();
}
}
Any help will be greatly appreciated.

Related

org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL)

While Executing the program, I'm getting the particular error
**Exception in thread "main" org.springframework.dao.InvalidDataAccessApiUsageException:
Write operations are not allowed in read-only mode (FlushMode.MANUAL):
Turn your Session into FlushMode.
COMMIT/AUTO or remove 'readOnly' marker from transaction definition.**
every time. please someone help me. Here I am giving my codes which contains some error. In the Below code I have taken one employee data which will be stored in the employee table of MSSQL database. While working with only hibernate at that time i can able to persist my data. But, her i am unable to persist my data.
EmployeeHt.java
This is the entity class which is mapped to the employee table of MSSQL database
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="employee")
public class EmployeeHt {
#Id
#Column(name="id")
private int id;
#Column(name="name")
private String name;
#Column(name="salary")
private int 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 int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
#Override
public String toString() {
return "EmployeeHt [id=" + id + ", name=" + name + ", salary=" + salary + "]";
}
}
EmployeeHtDao.java
This is the class which contains hibernate template
import org.springframework.orm.hibernate5.HibernateTemplate;
public class EmployeeHtDao {
private HibernateTemplate ht;
public void setHt(HibernateTemplate ht) {
this.ht = ht;
}
public void saveEmployee(EmployeeHt e){
ht.save(e);
}
}
EmployeeHtTest.java
**This is the main class**
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class EmployeeHtTest {
private static ApplicationContext context;
public static void main(String[] args) {
context = new ClassPathXmlApplicationContext("hibernateTemplate.xml");
EmployeeHtDao dao=(EmployeeHtDao) context.getBean("edao");
EmployeeHt e=new EmployeeHt();
e.setId(104);
e.setName("Prangyan");
e.setSalary(30000);
dao.saveEmployee(e);
}
}
hibernateTemplate.xml
**This is the 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-3.0.xsd">
<bean id="connpool" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="url" value="jdbc:sqlserver://localhost:1433;databaseName=ananta"/>
<property name="username" value="sa"/>
<property name="password" value="pass123"/>
</bean>
<bean id="mysessionfactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="connpool"/>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="mysessionfactory"/>
</bean>
<bean id="edao" class="com.sdrc.hibernatetemplate.EmployeeHtDao">
<property name="ht" ref="hibernateTemplate"/>
</bean>
</beans>
Check for #Transactional annotation in you DAO.
It should be
#Transactional(readOnly = false)

Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named lanceurApplication

I am trying to setup persistence using JPA and Hibernate for a Java project. I use the Oracle 11g express for my database.
I've been on this for hours now, but no matter what I do I always get this exception when I try to create a EntityManagerFactory: I've found quite a few similar questions regarding this exception, but no solutions that I am able to get to work. What am I doing wrong here?
In detail:
The error I am getting is this:
Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named lanceurApplication
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:69)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:47)
at ap.s.tn.test.Main.main(Main.java:15)
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">
<persistence-unit name="lanceurApplication">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>ap.s.tn.beans.Adresse</class>
<properties>
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver"/>
<property name="hibernate.connection.url" value="jdbc:oracle:thin:#localhost:1521:xe"/>
<property name="hibernate.connection.username" value="appACTEL"/>
<property name="hibernate.connection.password" value="appACTEL"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
</properties>
</persistence-unit>
</persistence>
Main.java
package ap.s.tn.test;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
EntityManagerFactory emf = Persistence.createEntityManagerFactory("lanceurApplication");
EntityManager entityManager = emf.createEntityManager();
}
}
Adresse.java
package ap.s.tn.beans;
import java.io.Serializable;
import java.lang.String;
import javax.persistence.*;
/**
* Entity implementation class for Entity: Adresse
*
*/
#Entity
public class Adresse implements Serializable {
private int id_adresse;
private String rue;
private String ville;
private String pays;
private static final long serialVersionUID = 1L;
public Adresse() {
super();
}
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public int getId_adresse() {
return this.id_adresse;
}
public void setId_adresse(int id_adresse) {
this.id_adresse = id_adresse;
}
public String getRue() {
return this.rue;
}
public void setRue(String rue) {
this.rue = rue;
}
public String getVille() {
return this.ville;
}
public void setVille(String ville) {
this.ville = ville;
}
public String getPays() {
return this.pays;
}
public void setPays(String pays) {
this.pays = pays;
}
}
1-delete all your library jar
2-add them again Properties -> Java Build Path -> Add JARs
3-Project -> Clean
4-modification with spring3
Adresse.java:
package com.springJPA.domain;
import java.io.Serializable;
import java.lang.String;
import javax.persistence.*;
/**
* Entity implementation class for Entity: Adresse
*
*/
#Entity
public class Adresse implements Serializable {
private int id_adresse;
private String rue;
private String ville;
private String pays;
private static final long serialVersionUID = 1L;
public Adresse() {
super();
}
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "id_Sequence_adresse")
#SequenceGenerator(name = "id_Sequence_adresse", sequenceName = "ID_SEQ_ADRESSE")
public int getId_adresse() {
return this.id_adresse;
}
public void setId_adresse(int id_adresse) {
this.id_adresse = id_adresse;
}
public String getRue() {
return this.rue;
}
public void setRue(String rue) {
this.rue = rue;
}
public String getVille() {
return this.ville;
}
public void setVille(String ville) {
this.ville = ville;
}
public String getPays() {
return this.pays;
}
public void setPays(String pays) {
this.pays = pays;
}
}
Main.java:
package com.springJPA.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.springJPA.domain.Adresse;
import com.springJPA.domain.Utilisateur;
import com.springJPA.service.AdresseService;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
Utilisateur utilisateur = new Utilisateur();
//--------
Adresse adresse = new Adresse();
adresse.setRue("kantawi");
adresse.setVille("Sousse");
adresse.setPays("Tunisie");
//--------
ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
AdresseService adrService = (AdresseService) context.getBean("adrService");
adrService.ajoutAdresse(adresse);
}
}
MyEntityManagerFactory.java:
package com.springJPA.util;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.springframework.stereotype.Component;
#Component("myEMF")
public class MyEntityManagerFactory {
private EntityManager entityManager;
private String unitName = "SpringJPA";
public EntityManager getEntityManager() {
if(entityManager == null){
EntityManagerFactory emf = Persistence.createEntityManagerFactory(unitName);
entityManager = emf.createEntityManager();
}
return entityManager;
}
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public String getUnitName() {
return unitName;
}
public void setUnitName(String unitName) {
this.unitName = unitName;
}
}
TransactionAspect.java:
package com.springJPA.util;
public class TransactionAspect {
private MyEntityManagerFactory entityManagerFactory;
public void begin(){
entityManagerFactory.getEntityManager().getTransaction().begin();
}
public void commit(){
entityManagerFactory.getEntityManager().getTransaction().commit();
}
public MyEntityManagerFactory getEntityManagerFactory() {
return entityManagerFactory;
}
public void setEntityManagerFactory(MyEntityManagerFactory entityManagerFactory) {
this.entityManagerFactory = entityManagerFactory;
}
}
application-context.xml:
<?xml version="1.0" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.springJPA.service"/>
<context:component-scan base-package="com.springJPA.util"/>
<bean id="tr" class="com.springJPA.util.TransactionAspect">
<property name="entityManagerFactory" ref="myEMF"/>
</bean>
<aop:config>
<aop:pointcut expression="execution(* com.springJPA.service.AdresseService.*(..))" id="adrPC"/>
<aop:pointcut expression="execution(* com.springJPA.service.UtilisateurService.*(..))" id="utlPC"/>
<aop:aspect ref="tr">
<aop:before pointcut-ref="adrPC" method="begin"></aop:before>
<aop:after pointcut-ref="adrPC" method="commit"></aop:after>
<aop:before pointcut-ref="utlPC" method="begin"></aop:before>
<aop:after pointcut-ref="utlPC" method="commit"></aop:after>
</aop:aspect>
</aop:config>
</beans>
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">
<persistence-unit name="SpringJPA" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.springJPA.domain.Adresse</class>
<class>com.springJPA.domain.Utilisateur</class>
<properties>
<property name="hibernate.archive.autodetection" value="class" />
<property name="hibernate.dialect" value="com.mysema.query.jpa.support.ExtendedOracleDialect" />
<property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver" />
<property name="hibernate.connection.url" value="jdbc:oracle:thin:#localhost:1521:xe" />
<property name="hibernate.connection.username" value="appACTEL" />
<property name="hibernate.connection.password" value="appACTEL" />
<property name="hibernate.flushMode" value="FLUSH_AUTO" />
<property name="hibernate.hbm2ddl.auto" value="create" />
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
</properties>
</persistence-unit>
</persistence>

Spring + Oracle doesn't persists

I have a problem with Spring and Oracle, I can select objects, but I can't update and insert. (I usually use MySql)
Aplication context:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- enabling annotation driven configuration /-->
<context:annotation-config/>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="classpath:jdbc.properties" />
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="{jdbc.username}"
p:password="${jdbc.password}" />
<bean class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"
c:dataSource-ref="dataSource" />
<bean id="jdbcTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource"/>
<tx:annotation-driven transaction-manager="jdbcTransactionManager"/>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource" p:jpaVendorAdapter-ref="jpaAdapter">
<property name="loadTimeWeaver">
<bean
class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
<property name="persistenceUnitName" value="namePU"></property>
</bean>
<bean id="jpaAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:database="${jpa.database}" p:showSql="${jpa.showSql}" />
<!-- Scans the classpath of this application for #Components to deploy as beans -->
<context:component-scan base-package="package.repository" />
<context:component-scan base-package="package.service" />
</beans>
jdbc.properties:
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:#172.172.10.83:1521:orcl
jdbc.username=User
jdbc.password=Password
hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
jpa.database = ORACLE
hibernate.generate_statistics = true
hibernate.show_sql = true
jpa.showSql = true
jpa.generateDdl = true
Usuario class
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "USUARIO")
public class Usuario implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "ID_USUARIO")
private String idUsuario;
#Column(name = "LOGIN")
private String login;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "ID_AMBITO")
private Ambito ambito;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "ID_ROL")
private Rol rol;
public String getIdUsuario() {
return idUsuario;
}
public void setIdUsuario(String idUsuario) {
this.idUsuario = idUsuario;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public Ambito getAmbito() {
return ambito;
}
public void setAmbito(Ambito ambito) {
this.ambito = ambito;
}
public Rol getRol() {
return rol;
}
public void setRol(Rol rol) {
this.rol = rol;
}
}
JPAUsuarioDao
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
#Repository(value = "usuarioDao")
public class JPAUsuarioDao implements UsuarioDao {
private EntityManager em = null;
#PersistenceContext
public void setEntityManager(EntityManager em) {
this.em = em;
}
#Override
#Transactional(readOnly = true)
public List<Usuario> getUsuariosList() {
TypedQuery<Usuario> query = em.createQuery("SELECT u FROM Usuario u",
Usuario.class);
return query.getResultList();
}
#Override
#Transactional(readOnly = true)
public Usuario getUsuario(String login) throws NoResultException {
TypedQuery<Usuario> query = em.createQuery("SELECT u FROM Usuario u WHERE u.login ='" + login + "'",
Usuario.class);
return query.getSingleResult() ;
}
#Override
#Transactional(readOnly = false)
public void addUsuario(Usuario usuario) {
em.merge(usuario);
}
}
This is the exception afer em.merge:
TRACE: org.hibernate.action.internal.UnresolvedEntityInsertActions - No unresolved entity inserts that depended on [[package.domain.Usuario#70675c9a-5eb4-4241-aa83-9cdea9211d18]]
TRACE: org.hibernate.action.internal.UnresolvedEntityInsertActions - No entity insert actions have non-nullable, transient entity dependencies.
Thank you

Using JPA with hibernate inserting data in database.. but issue in inserting data

I am using JPA with Hibernate and unable to insert data ..
the serviceImpl class:
package home;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import com.order.OrderBook;
public class OrderServiceImpl implements OrderService {
#Override
public void add(OrderBook orderbook) {
EntityManagerFactory emf=Persistence.createEntityManagerFactory("PU");
System.out.println("in Get Users");
EntityManager em=emf.createEntityManager();
EntityTransaction et=em.getTransaction();
et.begin();
String timeStamp =
new SimpleDateFormat("dd-MM-yyyy:HH.mm.ss").
format(new Timestamp(System.currentTimeMillis()));
orderbook.setOrder_date(timeStamp);
em.persist(orderbook);
System.out.println("after persist");
et.commit();
System.out.println("Inserted");
}
}
OrderBook.java
package com.order;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "order_book")
public class OrderBook {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int order_id;
private int client_id;
private int broker_id;
private String order_date;
private int stock_id;
private int price_per_share;
private int no_of_share;
private int total_amount;
private String trade_type;
public int getOrder_id() {
return order_id;
}
public void setOrder_id(int order_id) {
this.order_id = order_id;
}
public int getClient_id() {
return client_id;
}
public void setClient_id(int client_id) {
this.client_id = client_id;
}
public int getBroker_id() {
return broker_id;
}
public void setBroker_id(int broker_id) {
this.broker_id = broker_id;
}
public String getOrder_date() {
return order_date;
}
public void setOrder_date(String order_date) {
this.order_date =order_date;
}
public int getStock_id() {
return stock_id;
}
public void setStock_id(int stock_id) {
this.stock_id = stock_id;
}
public int getPrice_per_share() {
return price_per_share;
}
public void setPrice_per_share(int price_per_share) {
this.price_per_share = price_per_share;
}
public int getNo_of_share() {
return no_of_share;
}
public void setNo_of_share(int no_of_share) {
this.no_of_share = no_of_share;
}
public int getTotal_amount() {
return total_amount;
}
public void setTotal_amount(int total_amount) {
this.total_amount = total_amount;
}
public String getTrade_type() {
return trade_type;
}
public void setTrade_type(String trade_type) {
this.trade_type = trade_type;
}
}
but while running I getting this error. upto persist() method it is being executed but it is not executing commit() method.
exception
org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.NoSuchMethodError: org.hibernate.event.PreInsertEvent.getSource()Lorg/hibernate/engine/SessionImplementor;
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:812)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:709)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:613)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:536)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause
java.lang.NoSuchMethodError: org.hibernate.event.PreInsertEvent.getSource()Lorg/hibernate/engine/SessionImplementor;
org.hibernate.validator.event.ValidateEventListener.onPreInsert(ValidateEventListener.java:156)
org.hibernate.action.EntityInsertAction.preInsert(EntityInsertAction.java:178)
org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:72)
org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279)
org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:263)
org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:167)
org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027)
org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:365)
org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:53)
home.OrderServiceImpl.add(OrderServiceImpl.java:32)
com.order.web.OrderController.onSubmit(OrderController.java:31)
org.springframework.web.servlet.mvc.SimpleFormController.onSubmit(SimpleFormController.java:415)
org.springframework.web.servlet.mvc.SimpleFormController.onSubmit(SimpleFormController.java:387)
org.springframework.web.servlet.mvc.SimpleFormController.processFormSubmission(SimpleFormController.java:272)
org.springframework.web.servlet.mvc.AbstractFormController.handleRequestInternal(AbstractFormController.java:268)
org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:153)
org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:763)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:709)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:613)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:536)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.0 logs.
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="PU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.order.OrderBook</class>
<!-- <exclude-unlisted-classes /> -->
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
<property name="hibernate.connection.url" value="jdbc:oracle:thin:#localhost:1521:XE"/>
<property name="hibernate.connection.driver_class" value="oracle.jdbc.OracleDriver"/>
<property name="hibernate.connection.username" value="system"/>
<property name="hibernate.connection.password" value="newuser123#"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
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 ">
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
<bean id="orderService" class="home.OrderServiceImpl" />
<bean name="/placeOrder.htm" class="com.order.web.OrderController" p:orderService-ref="orderService"
p:formView="userForm" p:successView="userSuccess" />
</beans>

Spring Framework - Hibernate

I am going to be confused. I am trying to get Hibernate work with Spring, I can not get rid of a BeanCreationException. Please help me. I am new to Spring (and also Hibernate).
The problem is caused in a controller, having a private attribute userService which is annotated with #Autowired.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.aerts.service.UserService com.aerts.controller.TestController.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.aerts.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
I am really confused, please help me somebody.
Here is my root-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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
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.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.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.1.xsd">
<tx:annotation-driven />
<context:component-scan base-package="com.aerts.controller">
</context:component-scan>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="classpath:application.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://....."/>
<property name="username" value="....."/>
<property name="password" value="....."/>
<property name="initialSize" value="5"/>
<property name="maxActive" value="20"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<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">create</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Here is my User.java
package com.aerts.domain;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="User")
public class User {
#Id
#GeneratedValue()
#Column(name="id")
int id;
#Column(name="gender")
private Gender gender;
#Column(name="birthdate")
private Date birthdate;
#Column(name="firstname")
private String firstname;
#Column(name="surname")
private String surname;
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public Date getBirthdate() {
return birthdate;
}
public void setBirthdate(Date age) {
this.birthdate = age;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname.trim();
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname.trim();
}
}
My UserDaoImpl:
package com.aerts.dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import com.aerts.domain.User;
#Service
public class UserDaoImpl implements UserDao{
#Autowired
private SessionFactory sessionFactory;
#Override
public void addUser(User user) {
sessionFactory.getCurrentSession().save(user);
}
#Override
public List<User> listUser() {
return sessionFactory.getCurrentSession().createQuery("from User")
.list();
}
#Override
public void removeUser(int id) {
User user = (User) sessionFactory.getCurrentSession().get(
User.class, id);
if (user != null) {
sessionFactory.getCurrentSession().delete(user);
}
}
#Override
public void updateUser(User user) {
sessionFactory.getCurrentSession().update(user);
}
}
And my UserServiceImpl:
package com.aerts.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.aerts.dao.UserDao;
import com.aerts.domain.User;
#Service
public class UserServiceImpl implements UserService {
#Autowired
private UserDao userDao;
#Override
#Transactional
public void addUser(User user) {
userDao.addUser(user);
}
#Override
#Transactional
public List<User> listUser() {
return userDao.listUser();
}
#Override
#Transactional
public void removeUser(int id) {
userDao.removeUser(id);
}
#Override
#Transactional
public void updateUser(User user) {
userDao.updateUser(user);
}
}
I would really appreciate it if somebody could help me, i am going to be desperate...
Add the service class package to the component-scan base-package list in the application context file
<context:component-scan
base-package="
com.aerts.controller
com.aerts.service">
</context:component-scan>
I'm not expertise in spring but I assume that you have a problem with your service, if you use an interface you should inject ut and not your class...
see this track...
Spring expected at least 1 bean which qualifies as autowire candidate for this dependency

Categories