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.
Related
I am learning to establish connection to oracle database from Spring MVC . so here is what i have done so far
spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
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">
<context:annotation-config/>
<context:component-scan base-package="org.springdemo" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:#192.168.0.8:1521:xe"/>
<property name="username" value="sys as sysdba"/>
<property name="password" value="7299"/>
</bean>
</beans>
Circle.java
package org.springdemo.model;
public class Circle {
private int id;
private String name;
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 Circle(int id , String name){
setId(id);
setName(name);
}
}
JdbcDaoImpl.java
package org.springdemo.dao;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
#Component
public class JdbcDaoImpl {
#Autowired
private DataSource dataSource;
private JdbcTemplate jdbcTemplate = new JdbcTemplate();
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void getCircle(){
String sql = "SELECT COUNT(*) FROM circle";
jdbcTemplate.setDataSource(getDataSource());
int count = jdbcTemplate.queryForObject(sql,Integer.class);
System.out.println("count is"+count);
}
public void delete(int id) {
JdbcTemplate delete = new JdbcTemplate(dataSource);
delete.update("DELETE from CIRCLE where ID= ?",
new Object[] {id});
System.out.println("deleted successfully");
}
}
JdbcDemo.java
package org.springdemo;
import org.springdemo.dao.JdbcDaoImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class JdbcDemo {
public static void main(String[] args) {
ApplicationContext ctxt = new ClassPathXmlApplicationContext("spring.xml");
JdbcDaoImpl circleDao =(JdbcDaoImpl) ctxt.getBean("jdbcDaoImpl", JdbcDaoImpl.class);
circleDao.getCircle();
circleDao.delete(2);
}
}
Everything seems to be working fine without any errors and i am getting following output.
but in database i have 3 rows and my table is not getting updated .
when i tried to query for a non existing table to confirm whether i am connected to DB , i am getting exception indicating that i am connected to database only . Can someone explain me what would be the possible reason for my changes not reflecting in database.
Let's Spring instantiate your jdbctemplate
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
#Autowired
private JdbcTemplate jdbcTemplate
Don't use Obect[] but only id.
What is returned by the method delete.update ?
I've gone through every post on this topic but I still can't find what's wrong. When I try to run the server I get this exception:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'administratorDAO': Unsatisfied
dependency expressed through method 'setDao' parameter 0: No
qualifying bean of type [com.project.dataAccessLayer.DataAccessObject]
found for dependency [com.project.dataAccessLayer.DataAccessObject]:
expected at least 1 bean which qualifies as autowire candidate for
this dependency. Dependency annotations: {}; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type [com.project.dataAccessLayer.DataAccessObject]
found for dependency [com.project.dataAccessLayer.DataAccessObject]:
expected at least 1 bean which qualifies as autowire candidate for
this dependency. Dependency annotations: {}
It says that I have no bean for DataAccessObject even if it's annotated with #Repository or also defined in servlet-context.xml
I have a CustomerDAO and an AdministratorDAO which extends CustomerDAO. I'll post only the customer part as I think that if I can make that work, the administrator part will follow.
DataAccessObject class
package com.project.dataAccessLayer;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import com.project.model.Account;
import com.project.model.ModelEntity;
import com.project.model.Product;
#Repository("dao")
public class DataAccessObject {
private SessionFactory sessionFactory;
private Session session;
#Autowired
#Qualifier("sessionFactory")
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public ModelEntity save(ModelEntity modelEntity) {
Integer id = null;
try {
session = sessionFactory.openSession();
session.beginTransaction();
id = (Integer) session.save(modelEntity);
if (id != null) {
modelEntity.setId(id);
}
session.getTransaction().commit();
session.close();
} catch (Exception e) {
this.update(modelEntity);
}
return modelEntity;
}
public void update(ModelEntity modelEntity) {
try {
session = sessionFactory.openSession();
session.beginTransaction();
session.update(modelEntity);
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
}
#SuppressWarnings("unchecked")
public List<Product> getProducts() {
List<Product> list = null;
try {
session = sessionFactory.openSession();
session.beginTransaction();
list = session.createCriteria(Product.class).list();
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
return list;
}
#SuppressWarnings("unchecked")
public List<Account> getAccounts() {
List<Account> list = null;
try {
session = sessionFactory.openSession();
session.beginTransaction();
list = session.createCriteria(Account.class).list();
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
return list;
}
#SuppressWarnings("unchecked")
public List<Product> getProductByName(String brand, String model) {
List<Product> list = null;
try {
session = sessionFactory.openSession();
session.beginTransaction();
list = session.createCriteria(Product.class).add(Restrictions.eq("brand", brand))
.add(Restrictions.eq("model", model)).list();
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
return list;
}
#SuppressWarnings("unchecked")
public List<Account> getAccountByUsername(String username) {
List<Account> list = null;
try {
session = sessionFactory.openSession();
session.beginTransaction();
list = session.createCriteria(Account.class).add(Restrictions.eq("username", username)).list();
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
return list;
}
public void delete(ModelEntity modelEntity) {
try {
session = sessionFactory.openSession();
session.beginTransaction();
session.delete(modelEntity);
session.getTransaction().commit();
session.clear();
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
}
CustomerDAO class
package com.project.dataAccessLayer;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import com.project.model.Account;
import com.project.model.Permission;
import com.project.model.Product;
#Repository("customerDAO")
public class CustomerDAO implements ICustomerDAO {
DataAccessObject dao;
#Autowired
#Qualifier("custDAO")
public void setDao(DataAccessObject dao) {
this.dao = dao;
}
public DataAccessObject getDao() {
return dao;
}
public Account signUp(String fullName, String username, String password, String email, String address,
Permission permission) throws Exception {
List<Account> allAccounts = dao.getAccounts();
for (Account it : allAccounts) {
if (it.getUsername().equals(username)) {
throw new Exception("The username already exists");
}
}
Account newAccount = new Account(fullName, username, password, email, address, permission);
Account savedAccount = (Account) dao.save(newAccount);
return savedAccount;
}
public int logIn(String username, String password) throws Exception {
List<Account> allAccounts = dao.getAccounts();
for (Account it : allAccounts) {
if (it.getUsername().equals(username)) {
{
if (it.getPassword().equals(password)) {
if (it.isOnline() == false) {
it.setOnline(true);
dao.update(it);
return 200;
} else {
throw new Exception("You are already logged in");
}
} else {
throw new Exception("Invalid password");
}
}
}
}
// The username was not found in the database
return 404;
}
public int logOut(int accountId) throws Exception {
List<Account> allAccounts = dao.getAccounts();
for (Account it : allAccounts) {
if (it.getId() == accountId) {
{
if (it.isOnline()) {
it.setOnline(false);
dao.update(it);
return 200;
} else {
throw new Exception("You are not logged in");
}
}
}
}
return 400;
}
public Account changePassword(String username, String oldPassword, String newPassword) throws Exception {
List<Account> allAccounts = dao.getAccounts();
for (Account it : allAccounts) {
if (it.getUsername().equals(username)) {
{
if (it.getPassword().equals(oldPassword)) {
if (it.isOnline()) {
it.setPassword(newPassword);
dao.update(it);
return it;
} else {
throw new Exception("You must be logged in in order to change password");
}
} else {
throw new Exception("Invalid password");
}
}
}
}
return null;
}
public List<Product> showAllProducts() {
return dao.getProducts();
}
public List<Product> getProductByName(String brand, String model) {
return dao.getProductByName(brand, model);
}
}
CustomerService class
package com.project.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.project.dataAccessLayer.CustomerDAO;
import com.project.model.Account;
import com.project.model.Permission;
import com.project.model.Product;
#Service("customerService")
#Transactional
public class CustomerService implements ICustomerService {
private CustomerDAO cDAO;
public CustomerDAO getcDAO() {
return cDAO;
}
#Autowired
public void setcDAO(CustomerDAO cDAO) {
this.cDAO = cDAO;
}
#Transactional
public Account signUp(String fullName, String username, String password, String email, String address,
Permission permission) throws Exception {
if (username.equals("") || password.length() < 3 || permission == null) {
throw new Exception("You must provide a username and a minimum 3 character long password");
} else {
return cDAO.signUp(fullName, username, password, email, address, permission);
}
}
#Transactional
public boolean logIn(String username, String password) throws Exception {
if (cDAO.logIn(username, password) == 200)
return true;
return false;
}
#Transactional
public boolean logOut(int accountId) throws Exception {
if (cDAO.logOut(accountId) == 200)
return true;
return false;
}
#Transactional
public Account changePassword(String username, String oldPassword, String newPassword) throws Exception {
if (newPassword.length() < 3) {
throw new Exception("Password must have minimum 3 characters");
}
return cDAO.changePassword(username, oldPassword, newPassword);
}
#Transactional
public List<Product> showAllProducts() {
return cDAO.showAllProducts();
}
#Transactional
public Product getProductByName(String brand, String model) throws Exception {
List<Product> pList = cDAO.getProductByName(brand, model);
if (pList.isEmpty()) {
throw new Exception(brand + " " + model + " does not exist");
} else {
return pList.get(0);
}
}
}
CustomerController class
package com.project.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.project.model.Account;
import com.project.model.Product;
import com.project.services.CustomerService;
import com.project.services.ICustomerService;
#Controller("customerCOntroller")
#RequestMapping("/")
public class CustomerController {
ICustomerService customerService;
#Autowired(required = true)
#Qualifier(value="customerService")
public void setCustomerService(CustomerService cs){
this.customerService = cs;
}
#RequestMapping(value = "/account", method = RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView("account", "account", new Account());
}
#RequestMapping(value = "/signUp", method = RequestMethod.POST)
public String signUp(#ModelAttribute("account") Account acc) throws Exception {
this.customerService.signUp(acc.getFullName(), acc.getUsername(), acc.getPassword(), acc.geteMail(),
acc.getAddress(), acc.getPermission());
return "redirect:/logIn";
}
#RequestMapping(value = "/logIn", method = RequestMethod.POST)
public String logIn(#ModelAttribute("account") Account acc) throws Exception {
this.customerService.logIn(acc.getUsername(), acc.getPassword());
return "redirect:/products";
}
#RequestMapping(value = "/logOut", method = RequestMethod.POST)
public String logOut(#ModelAttribute("account") Account acc) throws Exception {
this.customerService.logOut(acc.getId());
return "redirect:/logIn";
}
#RequestMapping(value="/changePassword/{newPassword}", method = RequestMethod.POST)
public String changePassword(#ModelAttribute("account") Account acc,
#PathVariable("newPassword") String newPassword) throws Exception {
this.customerService.changePassword(acc.getUsername(), acc.getPassword(), newPassword);
return "redirect:/logIn";
}
#RequestMapping(value = "/products", method = RequestMethod.GET)
public ModelAndView showProducts() {
List<Product> productList = this.customerService.showAllProducts();
return new ModelAndView("products", "productList", productList);
}
}
web.xml
<....>``
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/root-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
root-context.xml (empty)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
</beans>
servlet-context.xml
<?xml ....">
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/jsp/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.project" />
<!-- 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/" />
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url"
value="jdbc:mysql://localhost:3306/guitarshop" />
<beans:property name="username" value="root" />
<beans:property name="password" value="" />
</beans:bean>
<beans:bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<beans:property name="annotatedClasses">
<beans:list>
<beans:value>com.project.model.Account</beans:value>
<beans:value>com.project.model.Product</beans:value>
</beans:list>
</beans:property>
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
<beans:prop key="hibernate.enable_lazy_load_no_trans">true</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<!-- <beans:bean id="dao" -->
<!-- class="com.project.dataAccessLayer.DataAccessObject"> -->
<!-- <beans:property name="sessionFactory" ref="sessionFactory" /> -->
<!-- </beans:bean> -->
<!-- <beans:bean id="customerDAO" class="com.project.dataAccessLayer.CustomerDAO"> -->
<!-- <beans:property name="dao" ref="dao" /> -->
<!-- </beans:bean> -->
<!-- <beans:bean id="administratorDAO" -->
<!-- class="com.project.dataAccessLayer.AdministratorDAO"> -->
<!-- <beans:property name="dao" ref="dao" /> -->
<!-- </beans:bean> -->
<!-- <beans:bean id="customerService" class="com.project.services.CustomerService"> -->
<!-- <beans:property name="customerDAO" ref="customerDAO"></beans:property> -->
<!-- </beans:bean> -->
<!-- <beans:bean id="administratorService" class="com.project.services.AdministratorService"> -->
<!-- <beans:property name="administratorDAO" ref="administratorDAO"></beans:property> -->
<!-- </beans:bean> -->
<tx:annotation-driven transaction-manager="transactionManager" />
<beans:bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<beans:property name="sessionFactory"
ref="sessionFactory" />
</beans:bean>
</beans:beans>
I commented the DAO and Service beans because i understood that #Repository, #Component and #Service annotations will create the beans.
I have to use DataAccessObject in both CustomerDAO and AdministratorDAO.
You are expecting a dependency DataAccessObject bean with #Qualifier("custDAO") inside your CustomerDAO, but there are NO DataAccessObject beans available with #Qualifier("custDAO")
In other words, the issue is because of the #Qualifier("custDAO") i.e., Spring container could NOT inject the DataAccessObject bean into the CustomerDAO (as there are NO beans available with the expected #Qualifier), so you need to change your DataAccessObject as shown below:
#Repository
#Qualifier("custDAO")
public class DataAccessObject {
//current code
}
You can look here for more on #Qualifier
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 using myeclipse IDE
After executing my code i'm getting the below Exception
log4j:WARN No appenders could be found for logger
(org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.MappingException: Unknown entity:info.inetsolv.Emp
at org.hibernate.impl.SessionFactoryImpl.getEntityPersister
(SessionFactoryImpl.java:628)
at org.hibernate.impl.SessionImpl.getEntityPersister
(SessionImpl.java:1366)
at org.hibernate.engine.ForeignKeys.isTransient(ForeignKeys.java:203)
at org.hibernate.event.def.AbstractSaveEventListener.getEntityState
(AbstractSaveEventListener.java:535)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist
(DefaultPersistEventListener.java:93)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist
(DefaultPersistEventListener.java:61)
at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:646)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:620)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:624)
at info.inetsolv.InsertEmprecord.main(InsertEmprecord.java:22)
POJO CLASS
package info.inetsolv;
#SuppressWarnings("serial")
public class Emp implements java.io.Serializable {
// Fields
private Integer eno;
private String name;
private Double salary;
// Constructors
/** default constructor */
public Emp() {
}
/** minimal constructor */
public Emp(Integer eno) {
this.eno = eno;
}
/** full constructor */
public Emp(Integer eno, String name, Double salary) {
this.eno = eno;
this.name = name;
this.salary = salary;
}
// Property accessors
public Integer getEno() {
return this.eno;
}
public void setEno(Integer eno) {
this.eno = eno;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Double getSalary() {
return this.salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
}
HibernateSessionFactory.java
package info.inetsolv;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
public class HibernateSessionFactory {
private static final ThreadLocal<Session> threadLocal = new
ThreadLocal<Session>();
private static org.hibernate.SessionFactory sessionFactory;
private static Configuration configuration = new Configuration();
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static String configFile = CONFIG_FILE_LOCATION;
static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession(): null;
threadLocal.set(session);
}
return session;
}
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}
public static Configuration getConfiguration() {
return configuration;
}
}
client program to insert record into DB
InsertEmprecord.java
package info.inetsolv;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class InsertEmprecord {
public static void main(String[] args) {
Configuration cfg = new Configuration();
cfg.configure();
SessionFactory sf = cfg.buildSessionFactory();
Session hsession = sf.openSession();
Transaction tx = hsession.beginTransaction();
Emp e = new Emp();
e.setEno(6);
e.setName("six");
e.setSalary(1234d);
hsession.persist(e);
tx.commit();
hsession.close();
sf.close();
}
}
And below is my hibernate mapping file
Emp.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD
3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="info.inetsolv.Emp" table="EMP" schema="HIB">
<id name="eno" type="java.lang.Integer">
<column name="ENO" precision="5" scale="0" />
<generator class="assigned" />
</id>
<property name="name" type="java.lang.String">
<column name="NAME" length="10" />
</property>
<property name="salary" type="java.lang.Double">
<column name="SALARY" precision="10" />
</property>
</class>
</hibernate-mapping>
AND below is my hibernate configuration file
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="dialect">
org.hibernate.dialect.Oracle9Dialect
</property>
<property name="connection.url">
jdbc:oracle:thin:#localhost:1521:xe
</property>
<property name="connection.username">hib</property>
<property name="connection.password">abc</property>
<property name="connection.driver_class">
oracle.jdbc.driver.OracleDriver
</property>
<property name="myeclipse.connection.profile">
my oracle drive
</property>
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>
You didn't configure mapping for the object Emp. The configuration file hibernate.cfg.xml should contain the mapping to the resource Emp.hbm.xml.
<mapping resource="info/inetsolv/Emp.hbm.xml"/>
I had similar problem for a simple Console application trying to use Hibernate. The solution I arrived to make the add the "packagesToScan" property explicitly for LocalSessionFactoryBean.
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.mg.learning.spring.orm"/> <--- this SOLVED!
<property name="hibernateProperties">
<props>
<prop key="dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
</props>
</property>
</bean>
#Sandhu Santakumar , answer is absolutely right.
Just adding the reason behind this.
By default the JBoss hibernate reverse engineering tool maps class inside the mapping tab but resource attribute is the required attribute that hibernate.cfg.xml should have.
class attribute is optional.
e.g. if your mapping is like this
resource is mandatory attribute and class is optional attribute.
Hope this additional information helps.
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