I built app with Spring+Hibernate+Spring Data JPA+PostgreSQL. I have Person class referenced to Marital class at two different resources.
Person has tx_person table at database pg_land.
Marital has tx_marital table at database pg_master.
I could retrieved each other when no relationships between Person and Marital. Problem occured when I built relationships (#ManyToOne and #OneToMany) between two classes.
Test Class
package id.co.p**g.sandbox;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.data.domain.Page;
import id.co.p**g.land.Person;
import id.co.p**g.service.land.PersonService;
public class PersonTest {
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:spring-data-app-context.xml");
ctx.load("classpath:datasource.xml");
ctx.refresh();
PersonService personService = ctx.getBean(
"springJpaPersonService", PersonService.class);
Page<Person> requests = personService.getPerson(1);
listSurveys(requests);
}
private static void listSurveys(Page<Person> requests) {
// TODO Auto-generated method stub
System.out.println("List of person");
for(Person request: requests) {
System.out.println(request);
}
}
}
Error Message
Exception in thread "main" org.springframework.data.mapping.PropertyReferenceException: No property no found for type id.co.palmagroup.land.Person
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:74)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:325)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:305)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:269)
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:240)
at org.springframework.data.jpa.repository.query.QueryUtils.toJpaOrder(QueryUtils.java:427)
at org.springframework.data.jpa.repository.query.QueryUtils.toOrders(QueryUtils.java:390)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.getQuery(SimpleJpaRepository.java:457)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.getQuery(SimpleJpaRepository.java:438)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:320)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:290)
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.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:358)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:343)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.jpa.repository.support.LockModeRepositoryPostProcessor$LockModePopulatingMethodIntercceptor.invoke(LockModeRepositoryPostProcessor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy35.findAll(Unknown Source)
at id.co.palmagroup.service.land.PersonImpl.getPerson(PersonImpl.java:63)
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.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy39.getPerson(Unknown Source)
at id.co.palmagroup.sandbox.PersonTest.main(PersonTest.java:20)
Person Class
package id.co.p**g.land;
import id.co.p**g.master.Marital;
import java.util.UUID;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;
import org.hibernate.validator.constraints.NotEmpty;
#Entity
#Table(name = "tx_person")
public class Person {
private UUID id;
private String name;
private Marital marital;
#Id
#GeneratedValue(generator = "system-uuid")
#GenericGenerator(name = "system-uuid", strategy = "uuid2")
#Type(type="pg-uuid")
#Column(name = "id")
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
#NotEmpty(message="{validation.formcode.NotEmpty.message}")
#Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#ManyToOne(targetEntity=Marital.class)
#JoinColumn(name="id_marital")
#Type(type="pg-uuid")
public Marital getMarital() {
return marital;
}
public void setMarital(Marital marital) {
this.marital = marital;
}
public String toString() {
return "Person ID: " + id
+ ". Name: " + name
+ ". Marital: " + marital;
}
}
Marital Class
package id.co.p**g.master;
import id.co.p**g.land.Person;
import java.util.Set;
import java.util.UUID;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;
#Entity
#Table(name = "m_marital")
public class Marital implements Serializable {
private UUID id;
private String name;
private String description;
private int no;
private Set<Person> persons;
#Id
#GeneratedValue(generator = "system-uuid")
#GenericGenerator(name = "system-uuid", strategy = "uuid2")
#Type(type="pg-uuid")
#Column(name = "id")
public UUID getId() {
return this.id;
}
public void setId(UUID id) {
this.id = id;
}
#Column(name = "name")
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "description")
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
#OneToMany(targetEntity=Person.class, mappedBy="marital")
public Set<Person> getPersons() {
return this.persons;
}
#Column(name="no")
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public void setPersons(Set<Person> persons) {
this.persons = persons;
}
public String toString() {
return + no + ". "
+ "Marital ID: " + id
+ " Name: " + name
+ ". Description: " + description;
}
}
Person Implementation Class
package id.co.p**g.service.land;
import java.util.List;
import java.util.UUID;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.google.common.collect.Lists;
import id.co.p**g.land.Person;
import id.co.p**g.repository.land.PersonRepository;
#Service("springJpaPersonService")
#Repository
#Transactional
public class PersonImpl implements PersonService {
// TODO PAGE_SIZE, rubah menjadi konfigurasi parameter.
private static final int PAGE_SIZE = 10;
#Autowired
private PersonRepository personRepository;
#PersistenceContext(unitName="landPersistence")
private EntityManager em;
#Transactional(readOnly=true)
public List<Person> findAll() {
return Lists.newArrayList(personRepository.findAll());
}
public Person save(Person person) {
return personRepository.save(person);
}
public void delete(Person person) {
personRepository.delete(person);
}
#Transactional(readOnly=true)
public Person findById(UUID id) {
return personRepository.findById(id);
}
#Transactional(readOnly=true)
public Page<Person> findAllByPage(Pageable pageable) {
return personRepository.findAll(pageable);
}
#Override
public Page<Person> getPerson(Integer pagenumber) {
PageRequest pagerequest = new PageRequest(pagenumber - 1, PAGE_SIZE, Sort.Direction.ASC, "no");
return personRepository.findAll(pagerequest);
}
}
Marital Implementation Class
package id.co.p**g.service.master;
import java.util.List;
import java.util.UUID;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.google.common.collect.Lists;
import id.co.p**g.master.Marital;
import id.co.p**g.repository.master.MaritalRepository;
#Service("springJpaMaritalService")
#Repository
#Transactional
public class MaritalImpl implements MaritalService {
// TODO PAGE_SIZE, rubah menjadi konfigurasi parameter.
private static final int PAGE_SIZE = 10;
#Autowired
private MaritalRepository maritalRepository;
#PersistenceContext(unitName="masterPersistence")
private EntityManager em;
#Transactional(readOnly=true)
public List<Marital> findAll() {
return Lists.newArrayList(maritalRepository.findAll());
}
#Transactional(readOnly=true)
public Marital findById(UUID id) {
return maritalRepository.findById(id);
}
#Transactional(readOnly=true)
public Page<Marital> findAllByPage(Pageable pageable) {
return maritalRepository.findAll(pageable);
}
#Override
public Page<Marital> getMarital(Integer pagenumber) {
PageRequest pagerequest = new PageRequest(pagenumber - 1, PAGE_SIZE, Sort.Direction.ASC, "name");
return maritalRepository.findAll(pagerequest);
}
}
Application Context
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
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/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<!-- LAND -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emf" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="emf"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="landPersistence"/>
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="packagesToScan" value="id.co.p**g.*" />
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.PostgreSQLDialect
</prop>
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="hibernate.jdbc.fetch_size">50</prop>
<prop key="hibernate.jdbc.batch_size">10</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- MASTER -->
<bean id="transactionManagerMaster" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emfMaster" />
</bean>
<tx:annotation-driven transaction-manager="transactionManagerMaster" />
<bean id="emfMaster"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="masterPersistence"/>
<property name="dataSource" ref="dataSourceMaster" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="packagesToScan" value="id.co.p**g.*" />
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.PostgreSQLDialect
</prop>
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="hibernate.jdbc.fetch_size">50</prop>
<prop key="hibernate.jdbc.batch_size">10</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<context:annotation-config />
<context:component-scan base-package="id.co.p**g.service.*" />
<jpa:repositories base-package="id.co.p**g.repository.land"
entity-manager-factory-ref="emf" transaction-manager-ref="transactionManager" />
<jpa:repositories base-package="id.co.p**g.repository.master"
entity-manager-factory-ref="emfMaster" transaction-manager-ref="transactionManagerMaster" />
</beans>
Data Source Configuration File
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
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/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/pg_land" />
<property name="username" value="sysland" />
<property name="password" value="password" />
</bean>
<bean id="dataSourceMaster"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/pg_master" />
<property name="username" value="usermaster" />
<property name="password" value="password" />
</bean>
</beans>
I use different associations in different database.
Mark the relationship with # transient and just put the id of the entity.
when you will need to refer to the id of the entity at the other database. just use a find
Related
Error Message
Please click for error message
I am looking for the solution of this error for the last 2 days but couldn't find. Please help me solve this. I also check other similar posts but unable to find a solution.
BEAN FILE
'''
package model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "student")
public class Student {
#Id
private int id;
private String name;
private String email;
private String address;
public Student(int id, String name, String address, String email) {
this.id = id;
this.name = name;
this.email = email;
this.address = address;
}
geter/seter
'''
DAO INTERFACE
'''
package DAO;
import java.util.List;
import model.Student;
public interface StudentDAO {
public int save(Student st);
public boolean update(Student st);
public boolean delete(Student st);
public Student findByPK(int pk);
public List<Student> findAllUsingHQL(Student st);
public List<Student> findAllUsingCriteria(Student st);
}
'''
DAO IMPLEMENTATION
'''
package DAO;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate3.HibernateTemplate;
import model.Student;
public class StudentDAOImpl implements StudentDAO {
private HibernateTemplate ht;
public HibernateTemplate getHt() {
return ht;
}
public void setHt(HibernateTemplate ht) {
this.ht = ht;
}
public int save(Student st) {
return (Integer) ht.save(st);
}
public boolean update(Student st) {
ht.update(st);
return true;
}
public boolean delete(Student st) {
ht.delete(st);
return false;
}
public Student findByPK(int pk) {
Student std = ht.get(Student.class, pk);
return std;
}
public List<Student> findAllUsingHQL(Student st) {
#SuppressWarnings("unchecked")
List<Student> list = (List<Student>) ht.find("from Student");
return list;
}
public List<Student> findAllUsingCriteria(Student st) {
DetachedCriteria dc = DetachedCriteria.forClass(Student.class);
List<Student> list = (List<Student>) ht.findByCriteria(dc);
return list;
}
}
'''
main method*
Currently only looking for save operation.
'''
package test;
import org.springframework.beans.BeansException;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import DAO.StudentDAOImpl;
import model.Student;
public class Client {
public static void main(String[] args) {
try {
ConfigurableApplicationContext ap = new ClassPathXmlApplicationContext("resources/spring.xml");
StudentDAOImpl dao = (StudentDAOImpl) ap.getBean("dao");
int l = dao.save(new Student(2, "ravi", "ravi.ymail.com", "goa"));
System.out.println(l);
ap.close();
} catch (BeansException e) {
e.printStackTrace();
}
}
}
'''
spring.xml
'''
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="bds" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource">
<property name="driverClassName"
value="org.postgresql.Driver" />
<property name="url"
value="jdbc:postgresql://localhost:5432/postgres" />
<property name="username" value="postgres" />
<property name="password" value="74484" />
<property name="maxActive" value="15" />
<property name="minIdle" value="5" />
<property name="maxWait" value="5000" />
</bean>
<!-- Create SessionFactory -->
<bean id="sassionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="bds" />
<property name="hibernateProperties">
<props>
<prop key="dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hbm2ddl.auto">create</prop>
<prop key="show_sql">true</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>model.Student</value>
</list>
</property>
</bean>
<bean id="hibernateTemplate"
class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sassionFactory"></property>
</bean>
<bean id="dao" class="DAO.StudentDAOImpl">
<property name="ht" ref="hibernateTemplate"></property>
</bean>
</beans>
'''
I am getting the exception below, and I am not sure what is the reason.
my controller
package com.attar.test.controller;
import static
org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.attar.test.entity.Patient;
import com.attar.test.service.Patientservice;
#org.springframework.stereotype.Controller
#RequestMapping("/user")
public class Controller {
#Autowired
private Patientservice patientservice;
#InitBinder
public void initbinderprocess(WebDataBinder databinder) {
StringTrimmerEditor trimedit = new StringTrimmerEditor(true);
databinder.registerCustomEditor(String.class, trimedit);
}
#RequestMapping("/frame")
public String datauser(Model model) {
Patient theuse = new Patient();
model.addAttribute("userr", theuse);
return "user-data";
}
#RequestMapping(value = "/userdata", method = RequestMethod.POST)
public String datashow(#Valid #ModelAttribute("userr") Patient thesuer, BindingResult bindresult) {
if (!bindresult.hasErrors()) {
patientservice.savepatient(thesuer);
return "show-data";
} else {
// return "redirect:/user/frame";
return "user-data";
}
}
}
PatientDaoimpl
package com.attar.test.dao;
import javax.validation.Valid;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.attar.test.entity.Patient;
#Repository
public class PatientDaoimpl implements PatientDao {
#Autowired
private SessionFactory sessionFactory;
#Override
public void savepatient(#Valid Patient thesuer) {
Session session = sessionFactory.openSession();
session.save(thesuer);
}
}
PatientServiceimpl
package com.attar.test.service;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.attar.test.dao.PatientDao;
import com.attar.test.entity.Patient;
#Service
public class PatientServiceimpl implements Patientservice {
#Autowired
private PatientDao patientdao;
#Override
#Transactional
public void savepatient(#Valid Patient thesuer) {
patientdao.savepatient(thesuer);
}
}
my patient-entity
package com.attar.test.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
#Entity
#Table(name = "patient")
public class Patient {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private int id;
#NotNull(message = "it is required")
#Column(name = "first_name")
private String first_name;
#Column(name = "last_name")
private String last_name;
#Column(name = "age")
private Integer age;
public Patient() {
}
public Patient(#NotNull(message = "it is required") String first_name, String last_name, int age) {
this.first_name = first_name;
this.last_name = last_name;
this.age = age;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
WebContent/WEB-INF/spring-mvc-demo-servlet.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"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
">
<!-- <aop:aspectj-autoproxy /> -->
<!-- Add support for component scanning -->
<context:component-scan base-package="com.attar.test" />
<!-- Add support for conversion, formatting and validation support -->
<mvc:annotation-driven />
<!-- Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Step 1: Define Database DataSource / connection pool -->
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl"
value="jdbc:mysql://localhost:3306/patients?useSSL=false" />
<property name="user" value="dbuser" />
<property name="password" value="dbpassword" />
<!-- these are connection pool properties for C3P0 -->
<property name="initialPoolSize" value="5" />
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="30000" />
</bean>
<!-- Step 2: Setup Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.luv2code.springdemo.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<!-- Step 3: Setup Hibernate transaction manager -->
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- Step 4: Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="myTransactionManager" />
<mvc:resources location="/resources/" mapping="/resources/**" />
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames" value="resources/messages" />
</bean>
</beans>
my error-exception
HTTP Status 500 – Internal Server Error
--------------------------------------------------------------------------------
Type Exception Report
Message Request processing failed; nested exception is org.hibernate.MappingException: Unknown entity: com.attar.test.entity.Patient
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.MappingException: Unknown entity: com.attar.test.entity.Patient
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Root Cause
org.hibernate.MappingException: Unknown entity: com.attar.test.entity.Patient
org.hibernate.metamodel.internal.MetamodelImpl.entityPersister(MetamodelImpl.java:620)
org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1634)
org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:104)
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:689)
org.hibernate.internal.SessionImpl.save(SessionImpl.java:681)
org.hibernate.internal.SessionImpl.save(SessionImpl.java:676)
com.attar.test.dao.PatientDaoimpl.savepatient(PatientDaoimpl.java:20)
com.attar.test.service.PatientServiceimpl.savepatient(PatientServiceimpl.java:20)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
com.sun.proxy.$Proxy89.savepatient(Unknown Source)
com.attar.test.controller.Controller.datashow(Controller.java:45)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Note The full stack trace of the root cause is available in the server logs.
--------------------------------------------------------------------------------
Apache Tomcat/8.5.20
I tried to put all lib for spring and hibernate. I don't know what is the cause of the problem.
You have to adopt the property "packageToScan" in your spring-mvc-demo-servlet.xml. It should specify your entity package (com.attar.test.entity).
I am new to spring. I was trying to integrate spring with hibernate but
I am not able to get my entity class Employee using packagesToScan, before this I tried annnotatedClasses as well that too didn't work, I also tried wildcards (com.sfb.**.*) with packagesToScan but no luck yet. FYI I am using javax.persistence.Entity so not an import issue too. Below are my spring.xml file and other along with stacktrace:
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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<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/sonoo"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="AnnotatedSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.sfb.model.*" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="employeeDao" class ="com.sfb.dao.EmployeeDaoImpl">
<property name="sessionFactory" ref="AnnotatedSessionFactory"/>
</bean>
<bean id="dateFormat" class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd" />
</bean>
<bean id="employee" class="com.sfb.model.Employee">
<property name="ename" value="Javed"/>
<property name="dob">
<bean factory-bean="dateFormat" factory-method="parse">
<constructor-arg value="2010-09-30" />
</bean>
</property>
<property name="address" ref="address"/>
</bean>
<bean id="address" class="com.sfb.model.Address">
<property name="streetno" value="23"/>
<property name="city" value="Bhilai"/>
</bean>
</beans>
TestEmp.java:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.sfb.dao.EmployeeDao;
import com.sfb.model.Address;
import com.sfb.model.Employee;
public class TestEmp {
public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationContext("spring.xml");
EmployeeDao empDao= (EmployeeDao)context.getBean(EmployeeDao.class);
Employee emp = (Employee)context.getBean(Employee.class);
Address addr = (Address)context.getBean(Address.class);
empDao.save(emp,addr);
}
}
Address.java:
package com.sfb.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Address {
#Id
#GeneratedValue
#Column(name="street_no")
private int streetno;
#Column(name="city")
private String city;
public int getStreetno() {
return streetno;
}
public void setStreetno(int streetno) {
this.streetno = streetno;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Employee.java:
package com.sfb.model;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity()
#Table(name="emp")
public class Employee {
#Column(name="e_name")
private String ename;
#Id
#GeneratedValue
#Column(name="e_id")
private int eid;
#Column(name="dob")
private Date dob;
#OneToOne(fetch = FetchType.LAZY, mappedBy = "address", cascade =
CascadeType.ALL)
private Address address;
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
EmployeeDao.java:
package com.sfb.dao;
import com.sfb.model.Address;
import com.sfb.model.Employee;
public interface EmployeeDao {
public void save(Employee emp , Address addr);
}
EmployeeDaoImpl.java
package com.sfb.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.sfb.dao.EmployeeDao;
import com.sfb.model.Address;
import com.sfb.model.Employee;
public class EmployeeDaoImpl implements EmployeeDao {
private SessionFactory sessionFactory;
#Override
public void save(Employee emp , Address addr) {
Session session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();
emp.setAddress(addr);
session.persist(emp);
tx.commit();
session.close();
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
Exception StackTrace:
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.sfb.model.Employee
at org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:548)
at org.hibernate.impl.SessionImpl.getEntityPersister(SessionImpl.java:1338)
at org.hibernate.engine.ForeignKeys.isTransient(ForeignKeys.java:180)
at org.hibernate.event.def.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:487)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:70)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:38)
at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:618)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:592)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:596)
at com.sfb.dao.EmployeeDaoImpl.save(EmployeeDaoImpl.java:20)
at com.sfb.mainemp.TestEmp.main(TestEmp.java:19)
Please help me thanks in advance
full StackTrace of NullpointerException:
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'AnnotatedSessionFactory' defined in class path resource [spring.xml]: Invocation of init method failed; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1403)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:545)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:871)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.sfb.mainemp.TestEmp.main(TestEmp.java:15)
Caused by: java.lang.NullPointerException
at org.hibernate.cfg.OneToOneSecondPass.doSecondPass(OneToOneSecondPass.java:135)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1127)
at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:296)
at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1112)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:717)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:188)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1460)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1400)
... 12 more
Here is an error (Employee.java):
#OneToOne(fetch = FetchType.LAZY, mappedBy = "address", cascade =
CascadeType.ALL)
private Address address;
mappedBy attribute should only used for inverse size of association, so it is not applicable here.
I guess you are trying to build simple unidirectional association.
It should look something like:
#OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name="ADDRESS_ID") /* this is the name of address id column in 'emp' table*/
private Address address;
Here is almost identical example from book.
I am going to be confused. I am trying to get Hibernate work with Spring, I can not get rid of a BeanCreationException. Please help me. I am new to Spring (and also Hibernate).
The problem is caused in a controller, having a private attribute userService which is annotated with #Autowired.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.aerts.service.UserService com.aerts.controller.TestController.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.aerts.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
I am really confused, please help me somebody.
Here is my root-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<tx:annotation-driven />
<context:component-scan base-package="com.aerts.controller">
</context:component-scan>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="classpath:application.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://....."/>
<property name="username" value="....."/>
<property name="password" value="....."/>
<property name="initialSize" value="5"/>
<property name="maxActive" value="20"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Here is my User.java
package com.aerts.domain;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="User")
public class User {
#Id
#GeneratedValue()
#Column(name="id")
int id;
#Column(name="gender")
private Gender gender;
#Column(name="birthdate")
private Date birthdate;
#Column(name="firstname")
private String firstname;
#Column(name="surname")
private String surname;
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public Date getBirthdate() {
return birthdate;
}
public void setBirthdate(Date age) {
this.birthdate = age;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname.trim();
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname.trim();
}
}
My UserDaoImpl:
package com.aerts.dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import com.aerts.domain.User;
#Service
public class UserDaoImpl implements UserDao{
#Autowired
private SessionFactory sessionFactory;
#Override
public void addUser(User user) {
sessionFactory.getCurrentSession().save(user);
}
#Override
public List<User> listUser() {
return sessionFactory.getCurrentSession().createQuery("from User")
.list();
}
#Override
public void removeUser(int id) {
User user = (User) sessionFactory.getCurrentSession().get(
User.class, id);
if (user != null) {
sessionFactory.getCurrentSession().delete(user);
}
}
#Override
public void updateUser(User user) {
sessionFactory.getCurrentSession().update(user);
}
}
And my UserServiceImpl:
package com.aerts.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.aerts.dao.UserDao;
import com.aerts.domain.User;
#Service
public class UserServiceImpl implements UserService {
#Autowired
private UserDao userDao;
#Override
#Transactional
public void addUser(User user) {
userDao.addUser(user);
}
#Override
#Transactional
public List<User> listUser() {
return userDao.listUser();
}
#Override
#Transactional
public void removeUser(int id) {
userDao.removeUser(id);
}
#Override
#Transactional
public void updateUser(User user) {
userDao.updateUser(user);
}
}
I would really appreciate it if somebody could help me, i am going to be desperate...
Add the service class package to the component-scan base-package list in the application context file
<context:component-scan
base-package="
com.aerts.controller
com.aerts.service">
</context:component-scan>
I'm not expertise in spring but I assume that you have a problem with your service, if you use an interface you should inject ut and not your class...
see this track...
Spring expected at least 1 bean which qualifies as autowire candidate for this dependency
Well, the code is working under the Test Enviroment, but not on the front context of the application. This is driving me crazy to be honest.
Here is the controller:
package org.admios.nuevoproyecto.controller;
import java.util.List;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.validation.BindingResult;
import org.admios.nuevoproyecto.dao.ProductDAO;
import org.admios.nuevoproyecto.model.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.PathVariable;
import static java.lang.System.out;
#Controller
#RequestMapping("/product")
public class ProductController {
private static Logger logger = Logger.getLogger(ProductController.class);
#Autowired
ProductDAO pdi;
#InitBinder
public void setAllowedFields(WebDataBinder dataBinder) {
dataBinder.setDisallowedFields("id");
}
#RequestMapping(value="/list")
public void listAllProducts() {
List<Product> products = pdi.getProducts();
for (Product product : products) {
System.out.println("Title: " + product.getTitle());
System.out.println("Description: " + product.getDescription());
System.out.println("Price: " + product.getPrice());
System.out.println("--------");
}
}
#RequestMapping(value="/add", method=RequestMethod.POST)
public String addProduct(#ModelAttribute Product product, BindingResult result) {
logger.info("Entrando en el metodo para agregar nuevo producto");
// Product newProduct = new Product();
// newProduct.setTitle("Titulo del producto2s");
// newProduct.setDescription("Descripcion del producto");
// newProduct.setPrice(220f);
System.out.println(product.getPrice());
Product savedProduct = pdi.saveProduct(product);
System.out.println(savedProduct.getId());
return "hello";
}
#RequestMapping(value="/form")
public String viewForm() {
out.println("entering viewForm()");
return "addproduct";
}
#RequestMapping(value="/view/{id}", method=RequestMethod.GET)
public void viewProduct(#PathVariable("id") Long id) {
System.out.println(id);
}
#ModelAttribute("product")
public Product getProductObject() {
out.println("entering getProductObject()");
return new Product();
}
}
The DAO implementation:
package org.admios.nuevoproyecto.dao;
import java.util.List;
import javax.persistence.EntityManagerFactory;
import org.admios.nuevoproyecto.model.Product;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.jpa.support.JpaDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
#Repository
public class ProductDaoImp extends JpaDaoSupport implements ProductDAO {
private static Logger log = Logger.getLogger(ProductDaoImp.class);
#Autowired
public ProductDaoImp(EntityManagerFactory entityManagerFactory) {
super.setEntityManagerFactory(entityManagerFactory);
}
#Override
public List<Product> getProducts() {
return getJpaTemplate().find("select p from Product p");
}
#Override
#Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public Product saveProduct(Product product) {
log.info("Trying to create a new product");
Product newProduct = getJpaTemplate().merge(product);
log.info(newProduct.getDescription());
log.info(newProduct.getTitle());
log.info(newProduct.getId());
log.info(newProduct.getPrice());
return newProduct;
}
#Override
public void removeProduct(Product product) {
getJpaTemplate().remove(product);
}
#Override
public Product getProductById(Integer id) {
return getJpaTemplate().find(Product.class, id);
}
}
The applicationContext looks like this:
http://pastie.org/1175350
1.Create transaction manager as follow :
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >
<property name="persistenceUnitName" value="persistanceUnit"/>
<property name="dataSource" ref="dataSource"/>
<property name="persistenceXmlLocation" value="classpath:persistence.xml"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="${db.orm.showsql}" />
<property name="generateDdl" value="${db.orm.generateDdl}" />
<property name="database" value="${db.type}"/>
<property name="databasePlatform" value="${db.orm.dialect}" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
2.use persistance.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="persistanceUnit" transaction-type="RESOURCE_LOCAL">
<description>Oracle db Persistence Unit</description>
<class>com.company.YourModelClass</class>
<properties/>
</persistence-unit>
</persistence>
3.Add following annotation in applicationContext.xml
<context:component-scan base-package="com.yourcompany.basepackage" />
4.annoatate your Entitymanager in service class like:
#PersistenceContext
private EntityManager em = null;
5.Inject TrasnsactionManager to :
private PlatformTransactionManager platformTransactionManager = null;
6.persist object like:
platformTransactionManager .persist(obj);
Have you tried with getJpaTemplate().persist(Object)?