In relation to my post/question "EntityManager is always NULL using SpringFramework",
I am encountering the below exception on this portion of my code:
ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tblFileinfoHome': Injection of persistence fields failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.AbstractMethodError: org.springframework.orm.jpa.persistenceunit.SpringPersistenceUnitInfo.getValidationMode()Ljavax/persistence/ValidationMode;
Below are the files related to my Spring + Hibernate Project
<--- 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_1_0.xsd"
version="1.0">
<persistence-unit name="msh" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.msh.TblFileinfo</class>
</persistence-unit>
</persistence>
<--- applicationContext.xml --->
<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"
xmlns:lang="http://www.springframework.org/schema/lang"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/lang
http://www.springframework.org/schema/lang/spring-lang-3.0.xsd
http://www.springframework.org/schema/security">
<!-- need to create database.properties file -->
<context:property-placeholder location="classpath:database.properties"/>
<context:component-scan base-package="com.msh"/>
<!-- tell Spring that it should act on any #PersistenceContext and #Transactional annotations found in bean classes -->
<!-- <tx:annotation-driven/> -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean class="com.msh.TblFileinfoHome" />
<bean class="com.msh.TblFileinfo" />
<bean id="sample" class="com.msh.Sample" />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!-- <property name="databasePlatform" value="${platform}" /> -->
<property name="showSql" value="${database.showSql}" />
<property name="generateDdl" value="${database.generateDdl}" />
</bean>
<bean id="entityManagerFactory" class="org.org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="msh" />
<property name="dataSource" ref="dataSource" />
<!-- <property name="loadTimeWeaver" class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" /> -->
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driverClassName}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.username}" />
<property name="password" value="${database.password}" />
</bean>
</beans>
<--- Main java code --->
package com.msh;
public class MavenSpringHibernate {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Sample s = (Sample)appContext.getBean("sample");
s.persist();ew Sample();
s.persist();
}
}
<--- DAO --->
package com.msh;
import javax.ejb.Stateless;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Home object for domain model class TblFileinfo.
* #see com.trendmicro.grid.mshPackage.TblFileinfo
* #author Hibernate Tools
*/
/**
#Stateless
#Repository
#Transactional
*/
#Repository
public class TblFileinfoHome {
private static final Log log = LogFactory.getLog(TblFileinfoHome.class);
#PersistenceContext(unitName="msh")
private EntityManager entityManager;
#Transactional
public void persist(TblFileinfo transientInstance) {
log.debug("persisting TblFileinfo instance");
try {
entityManager.persist(transientInstance);
log.debug("persist successful");
}
catch (RuntimeException re) {
log.error("persist failed", re);
throw re;
}
}
#Transactional
public void remove(TblFileinfo persistentInstance) {
log.debug("removing TblFileinfo instance");
try {
entityManager.remove(persistentInstance);
log.debug("remove successful");
}
catch (RuntimeException re) {
log.error("remove failed", re);
throw re;
}
}
#Transactional
public TblFileinfo merge(TblFileinfo detachedInstance) {
log.debug("merging TblFileinfo instance");
try {
TblFileinfo result = entityManager.merge(detachedInstance);
log.debug("merge successful");
return result;
}
catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}
#Transactional
public TblFileinfo findById( Long id) {
log.debug("getting TblFileinfo instance with id: " + id);
try {
TblFileinfo instance = entityManager.find(TblFileinfo.class, id);
log.debug("get successful");
return instance;
}
catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
}
--- Entity ---
package com.msh;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* TblFileinfo generated by hbm2java
*/
#Entity
#Table(name="tbl_fileinfo"
,catalog="behavior"
)
public class TblFileinfo implements java.io.Serializable {
private Long fileId;
private String filename;
private String filetype;
public TblFileinfo() {
}
public TblFileinfo(String filename, String filetype) {
this.filename = filename;
this.filetype = filetype;
}
#Id #GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="file_id", unique=true, nullable=false)
public Long getFileId() {
return this.fileId;
}
public void setFileId(Long fileId) {
this.fileId = fileId;
}
#Column(name="filename", length=200)
public String getFilename() {
return this.filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
#Column(name="filetype", length=50)
public String getFiletype() {
return this.filetype;
}
public void setFiletype(String filetype) {
this.filetype = filetype;
}
}
<--- Sample class controller --->
package com.msh;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.trendmicro.grid.msh.TblFileinfo;
import com.trendmicro.grid.msh.TblFileinfoHome;
#Transactional
public class Sample {
private TblFileinfo tinfo;
#Autowired
private TblFileinfoHome tinfoh;
public Sample()
{
tinfo = new TblFileinfo("c:/jayson/murillo/pryde.exe", "uv_win32");
//tinfoh = new TblFileinfoHome();
}
public void persist()
{
tinfoh.persist(tinfo);
}
}
Seems like a library versions mismatch, thats why your getting AbstractMethodError when spring is calling SpringPersistenceUnitInfo see this question
Related
Error Message
Please click for error message
I am looking for the solution of this error for the last 2 days but couldn't find. Please help me solve this. I also check other similar posts but unable to find a solution.
BEAN FILE
'''
package model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "student")
public class Student {
#Id
private int id;
private String name;
private String email;
private String address;
public Student(int id, String name, String address, String email) {
this.id = id;
this.name = name;
this.email = email;
this.address = address;
}
geter/seter
'''
DAO INTERFACE
'''
package DAO;
import java.util.List;
import model.Student;
public interface StudentDAO {
public int save(Student st);
public boolean update(Student st);
public boolean delete(Student st);
public Student findByPK(int pk);
public List<Student> findAllUsingHQL(Student st);
public List<Student> findAllUsingCriteria(Student st);
}
'''
DAO IMPLEMENTATION
'''
package DAO;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate3.HibernateTemplate;
import model.Student;
public class StudentDAOImpl implements StudentDAO {
private HibernateTemplate ht;
public HibernateTemplate getHt() {
return ht;
}
public void setHt(HibernateTemplate ht) {
this.ht = ht;
}
public int save(Student st) {
return (Integer) ht.save(st);
}
public boolean update(Student st) {
ht.update(st);
return true;
}
public boolean delete(Student st) {
ht.delete(st);
return false;
}
public Student findByPK(int pk) {
Student std = ht.get(Student.class, pk);
return std;
}
public List<Student> findAllUsingHQL(Student st) {
#SuppressWarnings("unchecked")
List<Student> list = (List<Student>) ht.find("from Student");
return list;
}
public List<Student> findAllUsingCriteria(Student st) {
DetachedCriteria dc = DetachedCriteria.forClass(Student.class);
List<Student> list = (List<Student>) ht.findByCriteria(dc);
return list;
}
}
'''
main method*
Currently only looking for save operation.
'''
package test;
import org.springframework.beans.BeansException;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import DAO.StudentDAOImpl;
import model.Student;
public class Client {
public static void main(String[] args) {
try {
ConfigurableApplicationContext ap = new ClassPathXmlApplicationContext("resources/spring.xml");
StudentDAOImpl dao = (StudentDAOImpl) ap.getBean("dao");
int l = dao.save(new Student(2, "ravi", "ravi.ymail.com", "goa"));
System.out.println(l);
ap.close();
} catch (BeansException e) {
e.printStackTrace();
}
}
}
'''
spring.xml
'''
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="bds" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource">
<property name="driverClassName"
value="org.postgresql.Driver" />
<property name="url"
value="jdbc:postgresql://localhost:5432/postgres" />
<property name="username" value="postgres" />
<property name="password" value="74484" />
<property name="maxActive" value="15" />
<property name="minIdle" value="5" />
<property name="maxWait" value="5000" />
</bean>
<!-- Create SessionFactory -->
<bean id="sassionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="bds" />
<property name="hibernateProperties">
<props>
<prop key="dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hbm2ddl.auto">create</prop>
<prop key="show_sql">true</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>model.Student</value>
</list>
</property>
</bean>
<bean id="hibernateTemplate"
class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sassionFactory"></property>
</bean>
<bean id="dao" class="DAO.StudentDAOImpl">
<property name="ht" ref="hibernateTemplate"></property>
</bean>
</beans>
'''
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>
In the following code the entityManager is null. What am I doing wrong? I need the entityManager to be injected automatically.
My Object Model:
#Entity
#Table(name = "jlocalidades", catalog = "7jogos")
public class Jlocalidades implements java.io.Serializable {
private Integer id;
private String nome;
private String descricao;
public Jlocalidades() {
}
public Jlocalidades(String nome, String descricao) {
this.nome = nome;
this.descricao = descricao;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "Id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "Nome", nullable = false, length = 200)
public String getNome() {
return this.nome;
}
public void setNome(String nome) {
this.nome = nome;
}
#Column(name = "Descricao", nullable = false, length = 200)
public String getDescricao() {
return this.descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
}
My Servlet
<?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:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<context:component-scan base-package="com.dtr.oas" />
<context:annotation-config/>
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<!-- <resources mapping="/resources/**" location="/resources/" /> -->
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="mysqlDS"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://192.168.254.38:3306/7jogos" />
<property name="username" value="root" />
<property name="password" value="6+1Log.pt" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="mysqlDS"/>
<property name="persistenceProviderClass" value="org.hibernate.ejb.HibernatePersistence" />
</bean>
<tx:annotation-driven/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
</beans>
My Persistence
<?xml version="1.0" encoding="UTF-8" ?>
<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" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
<!-- shouldn't be valid for java SE per specification, but it works for EclipseLink ... -->
<class>com.dtr.oas.model.Jlocalidades</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://192.168.254.38:3306/7jogos" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="6+1Log.pt" />
<!-- EclipseLink should create the database schema automatically -->
<property name="eclipselink.ddl-generation" value="create-tables" />
<property name="eclipselink.ddl-generation.output-mode" value="database" />
<property name="eclipselink.logging.level" value="SEVERE"/>
</properties>
</persistence-unit>
My controller that gives the ERROR
package com.dtr.oas.model;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.setelog.model.Jcelulas;
public class JlocalidadesHome implements IJlocalidadesHome {
private static final Log log = LogFactory.getLog(JlocalidadesHome.class);
#Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
#PersistenceContext
private EntityManager entityManager;
public void persist(Jlocalidades transientInstance) {
log.debug("persisting Jlocalidades instance");
try {
EntityManager entityManager = Persistence.createEntityManagerFactory("persistenceUnit").createEntityManager();
entityManager.persist(transientInstance);
log.debug("persist successful");
} catch (RuntimeException re) {
log.error("persist failed", re);
throw re;
}
}
public void remove(Jlocalidades persistentInstance) {
log.debug("removing Jlocalidades instance");
try {
entityManager.remove(persistentInstance);
log.debug("remove successful");
} catch (RuntimeException re) {
log.error("remove failed", re);
throw re;
}
}
public Jlocalidades merge(Jlocalidades detachedInstance) {
log.debug("merging Jlocalidades instance");
try {
Jlocalidades result = entityManager.merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}
public Jlocalidades findById(Integer id) {
log.debug("getting Jlocalidades instance with id: " + id);
try {
Jlocalidades instance = entityManager.find(Jlocalidades.class, id);
log.debug("get successful");
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
#Transactional
public List<Jlocalidades> All (){
log.debug("getting all Jlocalidades");
try {
List<Jlocalidades> instance = entityManager.createQuery("SELECT * FROM jlocalidades").getResultList();
log.debug("get successful");
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
}
You need #Controller on your controller class in order for spring to inject the entityManager into it. Since you want Spring to inject the EntityManager, do not do:
EntityManager entityManager = Persistence.createEntityManagerFactory("persistenceUnit").createEntityManager();
Generally, you will only call Persistence.createEntityManagerFactory() when you are running without a container.
Bootstrap class that is used to obtain an EntityManagerFactory in Java
SE environments.
You can do without persistence.xml by changing your EntityManager configuration:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="mysqlDS"/>
<property name="packagesToScan" value="YOUR.ENTITY.PKG" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generatedDdl" value="true" />
<property name="databasePlatform" value="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</bean>
</property>
</bean>
How is the controller instantiated ? Its need to be a spring managed bean.
You have classpath scanning xml defined in your conf file. But JlocalidadesHome is not annoated with Controller/Component.
By the way, use a controller to take inputs from a request, it should then call service classes ... and the service classes interact with the data layer classes
I'm having really trouble with my configuration i think. Here's the problem. Ican open the the session like that :
#Test
public void testSessionFactory()
{
try {
Configuration configuration = new Configuration()
.addClass(com.mcfly.songme.pojo.Sysparameters.class)
.configure();
ServiceRegistryBuilder serviceRegistryBuilder = new ServiceRegistryBuilder().applySettings(configuration
.getProperties());
SessionFactory sessionFactory = configuration
.buildSessionFactory(serviceRegistryBuilder.buildServiceRegistry());
System.out.println("test");
Session session = sessionFactory.openSession();
System.out.println("Test connection with the database created successfuly.");
}catch (Throwable ex) {
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
}
But if i do that the session is never openned :
#Test
public void testFindAll()
{
try {
List<Sysparameters> sys = null;
System.out.println("test");
SysparametersDAO sysDao = new SysparametersDAO();
System.out.println("test");
sys = sysDao.findAll();
System.out.println(sys.size());
} catch (Throwable ex) {
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
}
My configuration.xml :
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.mcfly.songme.pojo" />
<!-- JDBC data source -->
<!-- <bean id="myDataSource" class="org.springframework.jdb.datasource.DriverManagerDataSource"> -->
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/songme"/>
<property name="maxActive" value="10"/>
<property name="minIdle" value="5"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
<property name="validationQuery" value="SELECT 1"/>
</bean>
<!-- hibernate session factory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="packagesToScan" value="com.mcfly.songme.pojo"/>
<property name="configLocation" value="classpath:com/mcfly/songme/pojo/hibernate.cfg.xml" />
</bean>
<!-- Hibernate transaction Manager -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Activates annotation based transaction management -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
My dao file :
package com.mcfly.songme.pojo;
import java.io.File;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
#Repository
#Component
public class SysparametersDAO
{
#Autowired(required=true)
#Qualifier("sessionFactory")
private SessionFactory sessionFactory;
private Session session = sessionFactory.getCurrentSession();
#Transactional
public List<Sysparameters> findAll()
{
try {
if(getSessionFactory()==null) {
System.out.println("NULL SESSION FACTORY");
}
session = getSessionFactory().getCurrentSession();
} catch (Exception e) {
e.printStackTrace();
}
#SuppressWarnings("unchecked")
List<Sysparameters> sys = (List<Sysparameters>) session.createQuery("from sysparameters").list();
return sys;
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
My entity file :
package com.mcfly.songme.pojo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
// Generated 8 oct. 2013 16:31:22 by Hibernate Tools 4.0.0
/**
* Sysparameters generated by hbm2java
*/
#Entity
#Table(name = "sysparameters")
public class Sysparameters implements java.io.Serializable {
#Id
private Integer id;
#Column(name = "name")
private String name;
#Column(name = "value")
private String value;
public Sysparameters() {
}
public Sysparameters(String name, String value) {
this.name = name;
this.value = value;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return this.value;
}
public void setValue(String value) {
this.value = value;
}
}
My test file configuration :
package com.mcfly.songme.pojo.test;
#ContextConfiguration("classpath:/files-servlet.xml")
#RunWith(SpringJUnit4ClassRunner.class)
public class SysparameterPOJOTest
{
I really can't understand what i am doing wrong. Thx for help if you got an idea.
Still having a session factory null
oct. 09, 2013 11:38:06 AM org.springframework.orm.hibernate4.HibernateTransactionManager afterPropertiesSet
INFO: Using DataSource [org.apache.commons.dbcp.BasicDataSource#102674b7] of Hibernate SessionFactory for HibernateTransactionManager
java.lang.NullPointerException
at com.mcfly.songme.pojo.test.SysparameterPOJOTest.testFindAll_(SysparameterPOJOTest.java:81)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
with that code like you said i tryed to get the session out of the object
#Test
public void testFindAll_()
{
Session session = null;
try {
Sysparameters sys = null;
SysparametersDAO sysDAO = new SysparametersDAO();
session = sysDAO.getSessionFactory().getCurrentSession();
// sys = new SysparametersHome().findById(1);
} catch (Throwable ex) {
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
} finally {
Assert.assertNotNull(session);
}
}
So my session factory seems to be still null :/
The first problem is this
#Autowired(required=true)
#Qualifier("sessionFactory")
private SessionFactory sessionFactory;
private Session session = sessionFactory.getCurrentSession();
Spring autowiring happens in two steps: first your bean is instantiated (calling default constructor in this case) and then the fields are set using reflection. In the case above, when the object is created, fields are also initialized, by default to null. So when
private Session session = sessionFactory.getCurrentSession();
tries to get a Session it calls getCurrentSession() on a null reference.
You shouldn't be getting the Session object at the instance level. You should be getting it inside each individual method call.
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