I'm getting this error:
java.lang.ClassNotFoundException: javax.persistence.Persistence
This is my project:
persistence.xml
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="Forum">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>Model.Section</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/Forum" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="root" />
</properties>
</persistence-unit>
</persistence>
NewSectionController.java
package Controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Model.Section;
public class NewSectionController extends HttpServlet {
private static final long serialVersionUID = 1L;
public NewSectionController() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher rs = request.getRequestDispatcher("newSection.jsp");
rs.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String title = request.getParameter("titulo");
String description = request.getParameter("descricao");
Section section = new Section();
section.insertNewSection(title, description);
}
}
Section.java
package Model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Persistence;
#Entity
public class Section {
#Id
#GeneratedValue
int idSection;
#Column
String titleSection;
#Column
String descriptionSection;
public void insertNewSection(String title, String description) {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("Forum");
EntityManager em = factory.createEntityManager();
Section section = new Section();
section.setTitleSection(title);
section.setDescriptionSection(description);
em.getTransaction().begin();
em.persist(section);
em.getTransaction().commit();
}
public int getIdSection() {
return idSection;
}
public void setIdSection(int idSection) {
this.idSection = idSection;
}
public String getTitleSection() {
return titleSection;
}
public void setTitleSection(String titleSection) {
this.titleSection = titleSection;
}
public String getDescriptionSection() {
return descriptionSection;
}
public void setDescriptionSection(String descriptionSection) {
this.descriptionSection = descriptionSection;
}
}
The files are organized this way:
src/Controller/NewSectionController.java
src/Model/Section.java
src/META-INF/persistence.xml
resources/log4j.properties
lib/
WebContent/
And I have imported and add to build path all these libs:
antlr-2.7.7.jar
c3p0-0.9.1.jar
dom4j-1.6.1.jar
ehcache-core-2.4.3.jar
hibernate-c3p0-4.2.2.Final.jar
hibernate-commons-annotations-4.0.2.Final.jar
hibernate-core-4.2.2.Final.jar
hibernate-ehcache-4.2.2.Final.jar
hibernate-entitymanager-4.2.2.Final.jar
hibernate-envers-4.2.2.Final.jar
hibernate-infinispan-4.2.2.Final-tests.jar
hibernate-infinispan-4.2.2.Final.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
hibernate-proxool-4.2.2.Final.jar
infinispan-core-5.2.0.Beta3.jar
javassist-3.15.0-GA.jar
jboss-logging-3.1.0.GA.jar
jboss-logging-3.1.1.GA.jar
jboss-marshalling-1.3.15.GA.jar
jboss-marshalling-river-1.3.15.GA.jar
jboss-transaction-api_1.1_spec-1.0.1.Final.jar
jgroups-3.2.0.CR1.jar
proxool-0.8.3.jar
rhq-pluginAnnotations-3.0.4.jar
slf4j-api-1.6.1.jar
stax2-api-3.1.1.jar
staxmapper-1.1.0.Final.jar
woodstox-core-asl-4.1.1.jar
And I'm still getting the java.lang.ClassNotFoundException: javax.persistence.Persistence error.
What should I do?
Related
I try to insert those values on the persistence class
but I can't and I don't know why
I've tried a lot of things and wasted a lot of hours with any results:'(
I'm noob in JPA JSF
ENTITY CLASS
package testes;
import entity.Automovel;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
public class PersistidorDeAutomovel {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.
createEntityManagerFactory("default");
EntityManager em = JPAUtil.getEntityManager();
Automovel auto = new Automovel();
auto.setAnoFabricacao(2010);
auto.setModelo("Ferrari");
auto.setObservacoes("Nunca foi batido");
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(auto);
tx.commit();
em.close();
emf.close();
}
}
JPAUtil CLASS
package testes;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class JPAUtil {
private static final EntityManagerFactory emf =
Persistence.createEntityManagerFactory("default");
public static EntityManager getEntityManager() {
return emf.createEntityManager();
}
}
PERSISTENCE TEST CLASS, JUST CREATED IT TO TEST IF I COULD INSERT DATA INTO THE DATABASE. I just don't understand why it isn't working
package testes;
import entity.Automovel;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
public class PersistidorDeAutomovel {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.
createEntityManagerFactory("default");
EntityManager em = JPAUtil.getEntityManager();
Automovel auto = new Automovel();
auto.setAnoFabricacao(2010);
auto.setModelo("Ferrari");
auto.setObservacoes("Nunca foi batido");
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(auto);
tx.commit();
em.close();
emf.close();
}
}
PERSISTENCE CLASS CONFIGURATIONS
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="default" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>entity.Automovel</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/automovel?zeroDateTimeBehavior=convertToNull"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.password" value="1q2w3e4r"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLInnoDBDialect" />
</properties>
</persistence-unit>
</persistence>
I am new in hibernate, My Code is working fine but I checked that on each call of Controller class, a new connection thread has been created in mysql which goes in sleep state. My Code is -
hibernate.cfg.xml file:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hib_db_netbean</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">system</property>
<property name="hibernate.dialect">org.hibernate.dialect.MariaDBDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="hibernate.c3p0.min_size">2</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<mapping class="com.hib.collection.UserDetails"/>
</session-factory>
</hibernate-configuration>
My Entity Class (UserDetails.java):
package com.hib.collection;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.Table;
#Entity
#Table(name = "USER_TABLE")
public class UserDetails {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int user_id;
#Column(name = "user_name")
private String username;
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
Controller class - CallHibernate.java
package com.hib.collection;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
#WebServlet(name = "CallHibernate", urlPatterns = {"/CallHibernate"})
public class CallHibernate extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
UserDetails user = new UserDetails();
SessionFactory sessionFactory;
Session session = null;
user.setUsername("User Name");
try (PrintWriter out = response.getWriter()) {
sessionFactory = new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession();
session.beginTransaction();
// Insert The Data In the Table
session.save(user);
session.getTransaction().commit();
session.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
} finally {
session.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
MySQL Workbench Connection Status:
Use singleton design pattern for it.
Follow singleton design pattern by below link:
http://www.onlinetutorialspoint.com/hibernate/singleton-hibernate-sessionfactory-example.html
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 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
Well, the code is working under the Test Enviroment, but not on the front context of the application. This is driving me crazy to be honest.
Here is the controller:
package org.admios.nuevoproyecto.controller;
import java.util.List;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.validation.BindingResult;
import org.admios.nuevoproyecto.dao.ProductDAO;
import org.admios.nuevoproyecto.model.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.PathVariable;
import static java.lang.System.out;
#Controller
#RequestMapping("/product")
public class ProductController {
private static Logger logger = Logger.getLogger(ProductController.class);
#Autowired
ProductDAO pdi;
#InitBinder
public void setAllowedFields(WebDataBinder dataBinder) {
dataBinder.setDisallowedFields("id");
}
#RequestMapping(value="/list")
public void listAllProducts() {
List<Product> products = pdi.getProducts();
for (Product product : products) {
System.out.println("Title: " + product.getTitle());
System.out.println("Description: " + product.getDescription());
System.out.println("Price: " + product.getPrice());
System.out.println("--------");
}
}
#RequestMapping(value="/add", method=RequestMethod.POST)
public String addProduct(#ModelAttribute Product product, BindingResult result) {
logger.info("Entrando en el metodo para agregar nuevo producto");
// Product newProduct = new Product();
// newProduct.setTitle("Titulo del producto2s");
// newProduct.setDescription("Descripcion del producto");
// newProduct.setPrice(220f);
System.out.println(product.getPrice());
Product savedProduct = pdi.saveProduct(product);
System.out.println(savedProduct.getId());
return "hello";
}
#RequestMapping(value="/form")
public String viewForm() {
out.println("entering viewForm()");
return "addproduct";
}
#RequestMapping(value="/view/{id}", method=RequestMethod.GET)
public void viewProduct(#PathVariable("id") Long id) {
System.out.println(id);
}
#ModelAttribute("product")
public Product getProductObject() {
out.println("entering getProductObject()");
return new Product();
}
}
The DAO implementation:
package org.admios.nuevoproyecto.dao;
import java.util.List;
import javax.persistence.EntityManagerFactory;
import org.admios.nuevoproyecto.model.Product;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.jpa.support.JpaDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
#Repository
public class ProductDaoImp extends JpaDaoSupport implements ProductDAO {
private static Logger log = Logger.getLogger(ProductDaoImp.class);
#Autowired
public ProductDaoImp(EntityManagerFactory entityManagerFactory) {
super.setEntityManagerFactory(entityManagerFactory);
}
#Override
public List<Product> getProducts() {
return getJpaTemplate().find("select p from Product p");
}
#Override
#Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public Product saveProduct(Product product) {
log.info("Trying to create a new product");
Product newProduct = getJpaTemplate().merge(product);
log.info(newProduct.getDescription());
log.info(newProduct.getTitle());
log.info(newProduct.getId());
log.info(newProduct.getPrice());
return newProduct;
}
#Override
public void removeProduct(Product product) {
getJpaTemplate().remove(product);
}
#Override
public Product getProductById(Integer id) {
return getJpaTemplate().find(Product.class, id);
}
}
The applicationContext looks like this:
http://pastie.org/1175350
1.Create transaction manager as follow :
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >
<property name="persistenceUnitName" value="persistanceUnit"/>
<property name="dataSource" ref="dataSource"/>
<property name="persistenceXmlLocation" value="classpath:persistence.xml"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="${db.orm.showsql}" />
<property name="generateDdl" value="${db.orm.generateDdl}" />
<property name="database" value="${db.type}"/>
<property name="databasePlatform" value="${db.orm.dialect}" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
2.use persistance.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="persistanceUnit" transaction-type="RESOURCE_LOCAL">
<description>Oracle db Persistence Unit</description>
<class>com.company.YourModelClass</class>
<properties/>
</persistence-unit>
</persistence>
3.Add following annotation in applicationContext.xml
<context:component-scan base-package="com.yourcompany.basepackage" />
4.annoatate your Entitymanager in service class like:
#PersistenceContext
private EntityManager em = null;
5.Inject TrasnsactionManager to :
private PlatformTransactionManager platformTransactionManager = null;
6.persist object like:
platformTransactionManager .persist(obj);
Have you tried with getJpaTemplate().persist(Object)?