Entity Manager NULL - Spring MVC JPA - java

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

Related

Error 406: JSON response could not be returned in spring 3.x

I'm trying to output Json response using spring mvc and hibernate. When i am trying to hit the url as per my controller design. I'm getting this error
HTTP Status 406
The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ().
I have added the jackson-mapper-asl in my pom.xml.
My Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>restApp</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
My dispatcher-servlet.xml(spring-servlet.xml)
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<context:component-scan base-package="model,controller,dao,service" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<!--
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="jspViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
-->
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="html" value="text/html"/>
<entry key="json" value="application/json"/>
<entry key="xml" value="application/xml"/>
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</list>
</property>
</bean>
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource"
id="dataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/world"></property>
<property name="username" value="root"></property>
<property name="password" value="Tpg#1234"></property>
</bean>
<bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
id="sessionFactory">
<property name="dataSource" ref="dataSource"></property>
<property name="annotatedClasses">
<list>
<value>model.Book</value>
<value>model.Chapter</value>
<value>model.Status</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean class="org.springframework.orm.hibernate4.HibernateTransactionManager"
id="hibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean id="BookDao" class="dao.BookDaoImpl"></bean>
<bean id="ChapterDao" class="dao.ChapterDaoImpl"></bean>
<bean id="Bookservice" class="service.BookServiceImpl"></bean>
<bean id="ChapterService" class="service.ChapterServiceImpl"></bean>
</beans>
This is my Controller.
#Controller
#RequestMapping(value="/book")
public class BookController {
#Autowired
BookService bookService;
#Autowired
BookDao bookDao;
static final Logger logger = Logger.getLogger(BookController.class);
#RequestMapping(value="/add", method = RequestMethod.POST,headers="Accept=*/*")
public #ResponseBody
Status addBook(#RequestBody Book book){
try{
bookService.addBook(book);
return new Status(1,"book added successfully");
}catch(Exception e){
return new Status(0, e.toString());
}
}
#RequestMapping(value="/{bookId}",method = RequestMethod.GET,headers="Accept=*/*")
public #ResponseBody
Book getBook(#PathVariable("bookId")Integer bookId){
Book book = null;
try{
book = bookService.getBookById(bookId);
}catch(Exception e){
e.printStackTrace();
}
System.out.println("book returned");
System.out.println(book);
return book;
}
#RequestMapping(value="/list",method=RequestMethod.GET,headers="Accept=*/*")
public #ResponseBody
List<Book> getBookList(){
List<Book> bookList = null;
try{
bookList = bookService.getBookList();
}catch(Exception e){
e.printStackTrace();
}
System.out.println("bookList returned");
System.out.println(bookList);
return bookList;
}
#RequestMapping(value = "/delete/{bookId}", method = RequestMethod.GET,headers="Accept=*/*")
public #ResponseBody
Status deleteEmployee(#PathVariable("bookId") long bookId) {
try {
bookService.deleteBook(bookId);;
return new Status(1, "Employee deleted Successfully !");
} catch (Exception e) {
return new Status(0, e.toString());
}
}
Now when i'm trying to hit the url it is giving the error "HTTP status 406".
The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ().
The Hibernate queries are running properly in the controller after hitting the url. It's only that I'm not getting the JSON response.
My POJO class(Book.java)
#Entity
#Table(name="book")
#JsonIgnoreProperties({"hibernateLazyInitializer","handler"})
public class Book implements Serializable{
#Id
#Column(name="bookId")
#GeneratedValue
private Integer bookId;
#Column(name="bookName")
private String bookName;
#OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
#JoinTable(
name="BookChapter",
joinColumns = #JoinColumn(name="BOOK_ID"),
inverseJoinColumns = #JoinColumn(name="CHAPTER_ID")
)
public Set<Chapter> chapter;
public Integer getBookId() {
return bookId;
}
public void setBookId(Integer bookId) {
this.bookId = bookId;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public Set<Chapter> getChapter() {
return chapter;
}
public void setChapter(Set<Chapter> chapter) {
this.chapter = chapter;
}
}

java persistence works with reading from database,fails to insert / update

hi guys i m new to Hibernate and JPA.
This is my VO class.
Product.java
package com.sample.myproduct.valueobject;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import com.sample.myproduct.constants.MyproductConstants;
#Entity
#Table(name = "product")
#NamedQuery(
name=MyproductConstants.PRODUCT_NAMED_QUERY,
query=MyproductConstants.SELECT_QUERY_PRODUCT
)
public class Product {
#Id
#Column(name="Product_id")
int productId;
#Column(name="Name")
String name;
#Column(name="Desc")
String desc;
#Column(name="Rating")
int rating;
#Column(name="stock")
int stock;
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public int getStock() {
return stock;
}
public void setStock(int stock) {
this.stock = stock;
}
}
Impl Class
package com.sample.myproduct.servicedao;
import java.util.List;
import java.util.Random;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.dao.DataAccessException;
import org.springframework.transaction.annotation.Transactional;
import com.sample.myproduct.constants.MyproductConstants;
import com.sample.myproduct.valueobject.Product;
#Transactional
public class ProductDAOImpl implements ProductDAO {
#PersistenceContext
private EntityManager entityManagerFactory;
public EntityManager getEntityManagerFactory() {
return entityManagerFactory;
}
public void setEntityManagerFactory(EntityManager entityManagerFactory) {
this.entityManagerFactory = entityManagerFactory;
}
public void save(Product product){
entityManagerFactory.persist(product);
}
public Product getProductById(int id) throws DataAccessException{
return entityManagerFactory.find(Product.class,id);
}
}
}
persistance.xml
<?xml version="1.0" encoding="UTF-8"?>
<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="JpaPersistenceUnit"
transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.sample.myproduct.servicedao.ProductDAOImpl</class>
</persistence-unit>
</persistence>
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-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.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- 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 -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.sample.myproduct" />
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost/testdb" p:username="root" p:password="" />
<beans:bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="packagesToScan" value="com.sample.myproduct" />
<beans:property name="jpaVendorAdapter">
<beans:bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</beans:property>
<beans:property name="jpaProperties">
<beans:props>
<beans:prop key="hibernate.hbm2ddl.auto">update</beans:prop>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
</beans:props>
</beans:property>
<beans:property name="persistenceUnitName" value="entityManager" />
</beans:bean>
<beans:bean class="org.springframework.orm.jpa.JpaTransactionManager"
id="transactionManager">
<beans:property name="entityManagerFactory" ref="entityManagerFactory" />
</beans:bean>
<tx:annotation-driven mode="aspectj"
transaction-manager="transactionManager" />
<context:spring-configured />
<context:annotation-config />
<beans:bean id="productService"
class="com.sample.myproduct.servicebo.ProductService">
</beans:bean>
<beans:bean id="productDAO" class="com.sample.myproduct.servicedao.ProductDAOImpl"></beans:bean>
</beans:beans>
I am able to read data from db but not able to insert data..its not giving any exception.when i added entityManager.flush() after persist function;.
its giving exception as no transaction is in progress
I am not able to find solution for this..
When using JpaTransactionManager, you should specify the dialect as well as below.
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
<property name="jpaDialect" ref="jpaDialect"/>
</bean>
Update:
No transaction is required to read data from database but active transaction is required to write data to database.
If you don't configure the transactionManager correctly, #Transaction annotation will be ignored silently and all your operation will run as if no transaction is available; therefore, your write operation will fail.

Getting java.lang.NullPointerException while getSession().save(entity);

I want to add object data and want to save in DB table, everything working fine but it gives me an error :
java.lang.NullPointerException
on line getSession().save(entity);
I have called this method in code :
#Service
public class AddCategoryProcessor implements ICommandProcessor<AddCategory> {
#Autowired
private IPatronCategoryRepository patronCategoryRepository = new PatronCategoryRepository();
#Override
#Transactional(propagation = Propagation.REQUIRED)
public void Process(AddCategory command){
PatronCategory entity = new PatronCategory();
entity.setCategoryName(command.getCategoryName());
try
{
patronCategoryRepository.save(entity);
}catch (Exception e){
e.printStackTrace();
}
}
}
following is my xml file :
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://localhost:5432/abc"/>
<property name="username" value="postgres"/>
<property name="password" value="pwd"/>
<property name="validationQuery" value="SELECT 1"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.ngl.domain"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.generate_statistics">true</prop>
</props>
</property>
</bean>
<!-- Transaction Manager -->
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
Here is a getSession() method :
#Override
public Session getSession() {
return getSessionFactory().getCurrentSession();
}
Here is a sessionFactory declaration :
protected SessionFactory sessionFactory;
Any guesses why it's NULLPOINTEREXCEPTION ??
UPDATE :
java.lang.NullPointerException
at com.ngl.commandprocessors.patroncategoryprocessor.AddCategoryProcessor.Process(AddCategoryProcessor.java:32)
at com.ngl.commandprocessors.patroncategoryprocessor.AddCategoryProcessor.Process(AddCategoryProcessor.java:16)
at com.ngl.controllerapis.BaseApiController.ProcessRequest(BaseApiController.java:29)
at com.ngl.controllerapis.PatronCategoryController.addCategory(PatronCategoryController.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:746)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:687)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:915)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:822)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2441)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2430)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
and xml for transaction manager
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
in repository
#Autowired
protected SessionFactory sessionFactory;
Your config is a bit incomplete. You should delegate session management completely to Spring
Add in you spring xml file:
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Then, in your PatronCategoryRepository class, extend HibernateDaoSupport and add this constructor:
public class PatronCategoryRepository extends HibernateDaoSupport implements IPatronCategoryRepository{
#Autowired
public PatronCategoryRepository(HibernateTemplate hibernateTemplate) {
super();
super.setHibernateTemplate(hibernateTemplate);
}
[...]
}
In AddCategoryProcessor, leave the definition of the repository like this:
#Autowired
private IPatronCategoryRepository patronCategoryRepository;
And finally your method:
#Override
#Transactional(propagation = Propagation.REQUIRED)
public void Process(AddCategory command){
PatronCategory entity = new PatronCategory();
entity.setCategoryName(command.getCategoryName());
try
{
getHibernateTemplate.save(entity);
}catch (Exception e){
e.printStackTrace();
}
}
In case you still need to access directy the SessionFactory, the only thing you have to do is inject it into PatronCategoryRepository:
#Repository
public class PatronCategoryRepository implements IPatronCategoryRepository{
#Autowired
protected SessionFactory sessionFactory;
public PatronCategoryRepository() {
}
public PatronCategory save(PatronCategory entity){
return getSession().save(entity);
}
private Session getSession() {
return sessionFactory.getCurrentSession();
}
}
And remember to remove the new clause from AddCategoryProcessor, leaving it like this:
#Autowired
private IPatronCategoryRepository patronCategoryRepository;
Employee.java
package com.javacodegeeks.snippets.enterprise.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "Employee1")
public class Employee implements Serializable {
#Id
#Column(name = "ID")
private int id;
#Column(name = "NAME")
private String name;
#Column(name = "AGE")
private int age;
public Employee() {
}
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 long getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
EmployeeDao.java
package com.javacodegeeks.snippets.enterprise.dao;
import com.javacodegeeks.snippets.enterprise.model.Employee;
public interface EmployeeDAO {
public void saveEmployee(Employee employee);
Employee findEmployeeById(int id);
void updateEmployee(Employee employee);
void deleteEmployee(Employee employee);
}
EmployeeDaoImpl.java
package com.javacodegeeks.snippets.enterprise.dao;
import java.io.Serializable;
import org.hibernate.SessionException;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.javacodegeeks.snippets.enterprise.model.Employee;
public class EmployeeDAOImpl implements EmployeeDAO {
private HibernateTemplate template;
private SessionFactory sessionFactory;
#Autowired
public void setTemplate(HibernateTemplate template) {
this.template = template;
// template.setSessionFactory(sessionFactory);
}
public void setSessionFactory(SessionFactory sessionFactory) {
new HibernateTemplate(sessionFactory);
}
/*
* public void saveEmployee(Employee employee) {
* sessionFactory.getCurrentSession().save(employee);
*
* }
*/
public Employee findEmployeeById(int id) {
return (Employee) sessionFactory.getCurrentSession().get(
Employee.class, id);
}
public void updateEmployee(Employee employee) {
sessionFactory.getCurrentSession().update(employee);
}
public void deleteEmployee(Employee employee) {
sessionFactory.getCurrentSession().delete(employee);
}
public void saveEmployee(Employee employee) {
sessionFactory.getCurrentSession().persist(employee);
template.saveOrUpdate(employee);
}
}
Application COntext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<context:component-scan base-package="com.javacodegeeks.snippets.enterprise.*" />
<!-- <tx:annotation-driven/> -->
<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://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>com.javacodegeeks.snippets.enterprise.model.Employee</value>
</list>
</property>
<!-- <property name="mappingResources">
<list>
<value>Employee.hbm.xml</value>
</list>
</property> -->
<property name="hibernateProperties">
<props>
<prop
key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean> -->
<bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="d" class="com.javacodegeeks.snippets.enterprise.dao.EmployeeDAOImpl">
<property name="template" ref="template"></property>
</bean>
</beans>
pleas ehelp me :-)

Hibernate doesn't update record in MySQL database

I am using PrimeFaces 3.5, JSF 2.2, Hibernate 4.1, Spring 3.2.3, MySQL in my application.
Function updateUser() is supposed to update record in the database for the selected user from the PrimeFaces dataTable component(values are correct) but for some unknown reason it doesn't. I have a class named AbstractDAO which implements CRUD operations via generics. Insertion, selection and deleting works perfectly, but update fails without showing any errors at all. Any clues what can be wrong in my code?
applicationContext.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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:sec="http://www.springframework.org/schema/security"
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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<!-- GLOABL SETTINGS -->
<context:component-scan base-package="com.infostroy.adminportal"/>
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
<!-- DATA SOURCE AND PERSISTENCE SETTINGS -->
<bean id="propertiesPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:db.properties</value>
</list>
</property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dmDataSource"/>
<property name="packagesToScan" value="com.infostroy.adminportal"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${db.dialect}</prop>
<prop key="hibernate.show_sql">${db.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${db.hbm2ddl_auto}</prop>
<prop key="connection.pool_size">${db.pool_size}</prop>
<prop key="current_session_context_class">${db.current_session_context_class}</prop>
<prop key="org.hibernate.FlushMode">${db.flush_mode}</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="dataSource" ref="dmDataSource" />
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="dmDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${db.driver}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
<property name="maxWait" value="5000" />
<property name="initialSize" value="2" />
<property name="maxActive" value="100"/>
<property name="maxIdle" value="50"/>
<property name="minIdle" value="0"/>
</bean>
</beans>
db.properties:
db.username=root
db.password=root
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost/adminportal
db.pool_size=0
db.dialect=org.hibernate.dialect.MySQLDialect
db.hbm2ddl_auto=validate
db.show_sql=true
db.current_session_context_class=thread
db.flush_mode=COMMIT
AbstractDAO:
public abstract class AbstractDAO<T extends Serializable> implements Serializable {
#Autowired
protected SessionFactory sessionFactory;
protected T object;
protected Class clazz;
public AbstractDAO(Class clazz) {
this.clazz = clazz;
}
//Executes before being removed from container
#PreDestroy
protected void destroy() {
sessionFactory.getCurrentSession().close();
}
public Session getHiberSession() {
return sessionFactory.openSession();
}
#Transactional
protected T getByID(int id) {
String queryString = "from " + clazz.getSimpleName() + " where id = :id";
Query query = getHiberSession().createQuery(queryString);
query.setInteger("id", id);
object = (T) query.uniqueResult();
return object;
}
#Transactional
protected int deleteByID(int id) {
String queryString = "delete " + clazz.getSimpleName() + " where id = :id";
Query query = getHiberSession().createQuery(queryString);
query.setInteger("id", id);
return query.executeUpdate();
}
#Transactional
protected boolean insert(T object) {
try {
getHiberSession().save(object);
return true;
} catch (HibernateException ex) {
return false;
}
}
#Transactional
protected boolean update(T object) {
try {
getHiberSession().saveOrUpdate(object);
return true;
} catch (HibernateException ex) {
return false;
}
}
#Transactional
protected List getAllRecords() {
String queryString = "from " + clazz.getSimpleName();
Query query = getHiberSession().createQuery(queryString);
return query.list();
}
}
UserDAO.java:
#Repository
public class UserDAO extends AbstractDAO<User> {
public UserDAO() {
super(User.class);
}
public User getUserById(int id) {
return super.getByID(id);
}
public int deleteUserById(int id) {
return super.deleteByID(id);
}
public boolean insertUser(User user) {
return super.insert(user);
}
public boolean updateUser(User user) {
return super.update(user);
}
public List<User> getAllUsers() {
return super.getAllRecords();
}
}
If you need any additional info or code - just tell me. Every answer is highly appreciated and responded immidiately.
Thank you.
I'm just starting with Hibernate, but I'm using sessionFactory.getCurrentSession() instead of openSession().
After saveOrUpdate() mehod just flush the session. Ex: session.flush();
For more details you can see my blog here:
http://www.onlinetutorialspoint.com/hibernate/hibernate-example.html

BeanCreationException encountered in using Spring + Hibernate/EntityManager

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

Categories