It is a short time that I'm studying Spring,I'm a student
I have problems with dependency injection. In this project I have this error code in the method acquista.Why? Acquista in english is translated in "buy".If my Carrello (cart) is composed by more than one Articolo(Article) , in ArticoliOrdine(ArticlesOrder) I have only the first of them.Why?How can I solve it?
Error code:
Grave: Servlet.service() for servlet [applicationContext] in context with path [/SpringStore] threw exception [Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: bean.Ordine] with root cause
org.hibernate.PersistentObjectException: detached entity passed to persist: bean.Ordine
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:139)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:811)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1181)
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.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:289)
at com.sun.proxy.$Proxy37.persist(Unknown Source)
at daoJPA.CarrelloDAOImpl.acquista(CarrelloDAOImpl.java:130)
CarrelloDAOImpl.java
#Transactional
public class CarrelloDAOImpl implements CarrelloDAO {
#PersistenceContext
private EntityManager em;
#Autowired
Carrello carrello;
#Autowired
private ArticoliOrdine articoliOrdine;
#Autowired
private Ordine ordine;
public void acquista(Cliente c){
ordine.setIdCliente(c);
ordine.setData(new Date(System.currentTimeMillis()));
ordine.setStato("In lavorazione");
em.persist(ordine);
Set<String> lista_articoli=carrello.getMappa_Articoli().keySet();
synchronized(lista_articoli){
Iterator<String> it=lista_articoli.iterator();
while(it.hasNext()){
String codice=it.next();
System.out.println("codice: "+codice);
Query q=em.createQuery("SELECT a FROM Articolo a WHERE a.codice =:codice");
q.setParameter("codice", codice);
Articolo a =(Articolo)q.getSingleResult();
ArticoliOrdinePK pk=articoliOrdine.getArticoliordinePK();
pk.setIdArticolo(a.getId());
pk.setIdOrdine(ordine.getId());
articoliOrdine.setArticolo(a);
articoliOrdine.setQuantita(carrello.getMappa_Articoli().get(codice));
em.persist(articoliOrdine);
//aggiorno la quantita' dell'articolo
Articolo articolo_update=em.find(Articolo.class,a.getId());
articolo_update.setQuantita(articolo_update.getQuantita()- articoliOrdine.getQuantita());
}//while
}//syncronized
}//acquista
}//CarrelloDAOImpl
Ordine.java
#Table(name="ordine")
#Entity
public class Ordine implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private Integer id;
#Temporal(TemporalType.TIMESTAMP)
#Column(name="data")
private Date data;
#Column(name="stato")
private String stato;
#ManyToOne(optional=false)
#JoinColumn(name="idCliente",referencedColumnName="id")
private Cliente idCliente;
#OneToMany(mappedBy="ordine",cascade=CascadeType.ALL,fetch=FetchType.LAZY)
Collection<ArticoliOrdine> articoliordineCollection;
public Ordine() {
}
public Ordine(Integer id) {
this.id = id;
}
public Ordine(Integer id, Date data, String stato) {
this.id = id;
this.data = data;
this.stato = stato;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getData() {
return data;
}
public void setData(Date data) {
this.data = data;
}
public String getStato() {
return stato;
}
public void setStato(String stato) {
this.stato = stato;
}
public Cliente getIdCliente() {
return idCliente;
}
public void setIdCliente(Cliente idCliente) {
this.idCliente = idCliente;
}
public Collection<ArticoliOrdine> getArticoliordineCollection() {
return articoliordineCollection;
}
public void setArticoliordineCollection(
Collection<ArticoliOrdine> articoliordineCollection) {
this.articoliordineCollection = articoliordineCollection;
}
#Override
public boolean equals(Object o){
if(! (o instanceof Ordine) )
return false;
Ordine ordine=(Ordine)o;
return ordine.id==this.id;
}//equals
public String toString(){
return id+" cliente:"+idCliente.getId();
}//toString
}//Ordine
CarrelloController.java
#Controller
public class CarrelloController {
#Autowired
CarrelloDAO carrelloDAO;
#Autowired
Carrello carrello;
...
#RequestMapping(value="/acquista",method=RequestMethod.POST)
public String acquista(HttpServletRequest request,ModelMap model){
HttpSession session=request.getSession();
Cliente cliente=(Cliente)session.getAttribute("cliente");
carrelloDAO.acquista(cliente);
carrello.svuotaCarrello();
model.addAttribute("num_articoli",carrello.contaArticoliCarrello());
model.addAttribute("totale_carrello",carrello.getTotale());
return "redirect:/";
}//checkOut
}//CarrelloController
ApplicationContext.xml
<bean class="daoJPA.ClienteDAOImpl" id="clienteDAO"/>
<bean class="daoJPA.ArticoloDAOImpl" id="articoloDAO"/>
<bean class="bean.Carrello" id="carrello" scope="session">
<aop:scoped-proxy/>
</bean>
<bean class="daoJPA.CarrelloDAOImpl" id="carrelloDAO"/>
<bean class="bean.ArticoliOrdine" id="articoliOrdine" scope="prototype">
<property name="articoliordinePK">
<bean class="bean.ArticoliOrdinePK" id="articoliOrdinePK" scope="prototype"/>
</property>
</bean>
<bean class="bean.Ordine" id="ordine" scope="prototype"/>
You are not approaching this the right way. Your entities shouldn't be treated as Spring Beans.
#Autowired
private ArticoliOrdine articoliOrdine;
...
em.persist(articoliOrdine);
For long conversations you should either use:
Extended persistence context
detached objects saved in your Http Session
And detached entities shouldn't be passed to persist. You should merge them instead.
Persist is only meant for moving an entity state from TRANSIENT to PERSISTED. For DETACHED -> PERSISTED transitions you should always use EntityManager#merge() or Hibernate specific saveOrUpdate.
Related
In the code below if I don't clear current session, just the number of girls is returned from the method even if I want to return number of all children of this parent.
It's clearly seen that parent with id 1 has three children (2 girls and 1 boy), but just the girls are returned because of the previous retrieve method which returns parents with girls only. When I clear the session to avoid returning from cache, it returns 3 as expected. Can anybody help me understand why it is like this and how can I avoid this without clearing current session?
#Service
public class ExampleServiceImpl implements ExampleService {
#Autowired
private ExampleRepository exampleRepository;
#Autowired
private SessionFactory sessionFactory;
#Override
#Transactional(readOnly = true)
public int getNumberOfChildren() {
List<Parent> parentList = exampleRepository.retrieveParentsWithGirls();
//sessionFactory.getCurrentSession().clear();
Parent parent = exampleRepository.retrieveParentWithId(1);
System.out.println(parent.getChildSet().size());
return parent.getChildSet().size();
}
}
Let me share all the code I have as well as database scripts to make it more clear.
Repository:
#Repository
public class ExampleRepositoryImpl implements ExampleRepository {
#Autowired
private SessionFactory sessionFactory;
#Override
public List<Parent> retrieveParentsWithGirls() {
CriteriaBuilder builder = sessionFactory.getCriteriaBuilder();
CriteriaQuery<Parent> criteria = builder.createQuery(Parent.class);
Root<Parent> parentRoot = criteria.from(Parent.class);
Fetch<Parent, Child> fetchChildren = parentRoot.fetch("childSet", JoinType.LEFT);
Join<Parent, Child> joinChildren = (Join<Parent, Child>) fetchChildren;
criteria.where(builder.equal(joinChildren.get("sex"), "girl"));
criteria.distinct(true);
return sessionFactory.getCurrentSession().createQuery(criteria).getResultList();
}
#Override
public Parent retrieveParentWithId(int id) {
CriteriaBuilder builder = sessionFactory.getCriteriaBuilder();
CriteriaQuery<Parent> criteria = builder.createQuery(Parent.class);
Root<Parent> parentRoot = criteria.from(Parent.class);
parentRoot.fetch("childSet", JoinType.LEFT);
criteria.where(builder.equal(parentRoot.get("id"), id));
return sessionFactory.getCurrentSession().createQuery(criteria).getSingleResult();
}
}
Entities:
#Entity
#Table(name = "child")
public class Child {
#Id
#Column(name = "id", unique = true, nullable = false)
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#Column(name = "sex")
private String sex;
#JoinColumn(name = "parent_id", referencedColumnName = "id")
#ManyToOne(fetch = FetchType.LAZY)
private Parent parent;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Parent getParent() {
return parent;
}
public void setParent(Parent parent) {
this.parent = parent;
}
}
#Entity
#Table(name = "parent")
public class Parent {
#Id
#Column(name = "id", unique = true, nullable = false)
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "parent")
private Set<Child> childSet;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Set<Child> getChildSet() {
return childSet;
}
public void setChildSet(Set<Child> childSet) {
this.childSet = childSet;
}
}
DatabaseConfiguration:
#EnableTransactionManagement
#Configuration
#Conditional(DatabaseRequiredCondition.class)
public class DatabaseConfiguration {
#Value("${jdbc.driverClassName}")
private String DB_DRIVER;
#Value("${jdbc.pwd}")
private String DB_PASSWORD;
#Value("${jdbc.url}")
private String DB_URL;
#Value("${jdbc.username}")
private String DB_USERNAME;
#Value("${hibernate.dialect}")
private String HIBERNATE_DIALECT;
#Value("${hibernate.showSql}")
private String HIBERNATE_SHOW_SQL;
#Value("${hibernate.packagesScan}")
private String ENTITYMANAGER_PACKAGES_TO_SCAN;
#Value("${hibernate.tx_timeout}")
private Integer TIMEOUT_AS_SECONDS;
#Bean
#Primary
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(DB_DRIVER);
dataSource.setUrl(DB_URL);
dataSource.setUsername(DB_USERNAME);
dataSource.setPassword(DB_PASSWORD);
return dataSource;
}
#Bean
#Primary
public LocalSessionFactoryBean sessionFactory() throws IOException {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);
Properties hibernateProperties = new Properties();
hibernateProperties.put("hibernate.dialect", HIBERNATE_DIALECT);
hibernateProperties.put("hibernate.show_sql", HIBERNATE_SHOW_SQL);
hibernateProperties.put("hibernate.format_sql", true);
sessionFactoryBean.setHibernateProperties(hibernateProperties);
return sessionFactoryBean;
}
#Bean(name="transactionManager")
#Primary
public HibernateTransactionManager transactionManager() throws IOException {
HibernateTransactionManager transactionManager =
new HibernateTransactionManager(sessionFactory().getObject());
transactionManager.setDefaultTimeout(TIMEOUT_AS_SECONDS);
return transactionManager;
}
}
Scripts:
create table parent (id serial);
create table child (id serial, parent_id integer not null, sex character varying(10));
INSERT INTO public.parent values(default);
INSERT INTO public.parent values(default);
INSERT INTO public.child
(parent_id, sex)
VALUES(1, 'girl');
INSERT INTO public.child
(parent_id, sex)
VALUES(1, 'girl');
INSERT INTO public.child
(parent_id, sex)
VALUES(1, 'boy');
Generated Scripts When I run the code:
Hibernate:
select
parent0_.id as id1_23_0_,
childset1_.id as id1_5_1_,
childset1_.parent_id as parent_i3_5_1_,
childset1_.sex as sex2_5_1_,
childset1_.parent_id as parent_i3_5_0__,
childset1_.id as id1_5_0__
from
parent parent0_
left outer join
child childset1_
on parent0_.id=childset1_.parent_id
where
childset1_.sex=?
Hibernate:
select
parent0_.id as id1_23_0_,
childset1_.id as id1_5_1_,
childset1_.parent_id as parent_i3_5_1_,
childset1_.sex as sex2_5_1_,
childset1_.parent_id as parent_i3_5_0__,
childset1_.id as id1_5_0__
from
parent parent0_
left outer join
child childset1_
on parent0_.id=childset1_.parent_id
where
parent0_.id=1
Hibernate version: 5.4.5.Final
I can't seem to add values to my table. There is no error but the values aren't inserting in my database. After submitting the form, no errors would show up.
Upon looking at the console, this shows:
Hibernate:
insert
into
referral
(address, doctor_contact_no, doctor_name, facility_contact_no, facility_type, referral_no, referring_from, referring_to)
values
(?, ?, ?, ?, ?, ?, ?, ?)
I already tried logging, just in case my controller can't read the form i'm submitting.
Code Snippet of the Entity/Model i am saving
#Entity
#Table(name="referral")
public class Referrals {
#Id
#Column
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
#Column
private String referral_no;
#Column
private String facility_contact_no;
#Column
private String referring_from;
#Column
private String referring_to;
#Column
private String facility_type;
#Column
private String address;
#Column
private String doctor_name;
#Column
private String doctor_contact_no;'
Code Snippet of my Services Class
#Service
#Transactional
public class ReferralServicesImpl implements ReferralServices{
#Autowired
private ReferralDao referralDao;
public List<Referrals> list(){
return referralDao.list();
}
public boolean saveReferral(Referrals referral){
if(referralDao.saveReferral(referral))
return true;
else
return false;
}
}
Code Snippet of the Controller Methods
#RequestMapping(value = "/teleaudiology/referral", method = RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView("referrals", "referrals", new Referrals());
}
#RequestMapping(value = "/teleaudiology/referrals", method = RequestMethod.POST)
public String submit(#Valid #ModelAttribute("referrals")Referrals referral,
BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return "error";
}
System.out.println("referral: "+referral.getDoctor_name());
if(referralServices.saveReferral(referral))
return "redirect:../teleaudiology";
else
return "redirect:../teleaudiology";
}
Here is the ReferralDao Class
public interface ReferralDao {
public boolean saveReferral(Referrals referral);
public List<Referrals> list();
}
ReferralDao impl
#Repository
#Transactional
public class ReferralDaoImpl implements ReferralDao {
#Autowired
SessionFactory session;
Transaction trans;
public boolean saveReferral(Referrals referral) {
// TODO Auto-generated method stub
//System.out.println("Saving..."+referral.getReferring_to_address());
trans=session.getCurrentSession().beginTransaction();
session.getCurrentSession().saveOrUpdate(referral);
return true;
}
public List<Referrals> list() {
// TODO Auto-generated method stub
return session.getCurrentSession().createQuery("from Referrals").list();
}
}
i tried using
trans=session.getCurrentSession().getTransaction();
but resulted to this error
`saveOrUpdate is not valid without active transaction`
Snippet from servlet-context.xml
<tx:annotation-driven transaction-manager="transactionManager" />
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="sessionFactory" />
</beans:bean>
try using below code
Session s = sessionFactory.getCurrentSession();
s.save(object);
I am working on a test project to learn hibernate, unfortunately I am getting this error and have looked at other similar errors, but following them didn't solve my problem. I am still getting this error.
Can someone check what is going wrong, I would really appreciate to know what is my mistake.
The my model classes:
#Entity
#Table(name="survey")
public class Survey implements java.io.Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
#Column(name = "survey_id")
private Long _id;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "survey")
private List<Question> _questions ;
#Column(name="name")
private String _name;
public Survey() {
super();
}
public Survey(Long id, List<Question> questions, String name) {
super();
_id = id;
_questions = questions;
_name = name;
Assert.notNull(_id, "_id cannot be null");
Assert.notNull(_questions, "_questions cannot be null");
Assert.notNull(_name, "_name cannot be null");
}
public Long getId() {
return _id;
}
public void setId(Long id) {
_id = id;
}
public List<Question> getQuestions() {
return _questions;
}
public void setQuestions(List<Question> questions) {
_questions = questions;
}
public String getName() {
return _name;
}
public void setName(String name) {
_name = name;
}
#Override
public String toString() {
return "Survey [_id=" + _id + ", _questions=" + _questions + ", _name="
+ _name + "]";
}
}
This is the second model class:
#Entity
#Table(name="question")
public class Question implements java.io.Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
#Column(name = "id")
private Long _id;
#Column(name = "label")
private String _label;
#Column(name="type")
private QuestionType _type;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name="survey_id")
private Survey _survey;
public Question() {
}
public Question(final Long id, final String label, final QuestionType type, final Survey survey,final Long surveyId) {
_id = id;
_label = label;
_type = type;
_survey = survey;
Assert.notNull(_id, "_id cannot be null");
Assert.notNull(_label, "_label cannot be null");
Assert.notNull(_type, "_type cannot be null");
Assert.notNull(_survey, "_survey cannot be null");
}
public Long getId() {
return _id;
}
public void setId(Long id) {
_id = id;
}
public String getLabel() {
return _label;
}
public void setLabel(String label) {
_label = label;
}
public QuestionType getType() {
return _type;
}
public void setType(QuestionType type) {
_type = type;
}
public Survey getSurvey() {
return _survey;
}
public void setSurvey(Survey survey) {
_survey = survey;
}
#Override
public String toString() {
return "Question [_id=" + _id + ", _label=" + _label + ", _type="
+ _type + "]";
}
}
This is my main:
public class Application {
public static void main(String[] args) {
System.out.println("Hibernate one to many (Annotation)");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Survey survey = new Survey();
survey.setName("Ice Cream final");
session.save(survey);
Question question1 = new Question();
question1.setLabel("Whats your favorite Ice Cream");
question1.setType(QuestionType.TEXT);
question1.setSurvey(survey);
survey.getQuestions().add(question1);
session.save(question1);
session.getTransaction().commit();
System.out.println("Done");
}
This is my hibernate util class:
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
This is my config file:
<?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">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/survey</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping class="xxxxx.Survey" />
<mapping class="xxxxx.Question" />
</session-factory>
Error:
Initial SessionFactory creation failed.org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: xxxx.model.Question.Survey in xxxx.model.Survey._questions
Exception in thread "main" java.lang.ExceptionInInitializerError
at xxxx.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:16)
at xxxx.util.HibernateUtil.<clinit>(HibernateUtil.java:7)
at xxxx.Application.main(Application.java:25)
Caused by: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: xxxx.model.Question.SurveyModel in xxxx.model.Survey._questions
at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:655)
at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:619)
at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:66)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1221)
at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:383)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1377)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:954)
at xxxx.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:12)
... 2 more
#OneToMany(fetch = FetchType.LAZY, mappedBy = "survey")
private List<Question> _questions ;
So you're telling Hibernate: go look at the Question.survey field to know how this association is mapped.
Is there a field named survey in Question? No there isn't. The field is named _survey.
Please please please, make your code readable and your life easier, and respect the Java naming conventions. Variables don't start with underscores. You really really don't want every JPQL/HQL query of your app to have underscores everywhere.
Mapped By must be getter name of child class.
#OneToMany(fetch = FetchType.LAZY, mappedBy = "survey")
private List<Question> _questions ;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name="survey_id")
private Survey survey;
In Question Entity class you must use the same name for field you use in mappedBy in Survey class.So:
#OneToMany(fetch = FetchType.LAZY, mappedBy = "survey")
private List<Question> _questions ;
#JoinColumn(name="survey_id")
private Survey survey;
I am new to Hibernate. Recently, I was trying simple example to connect my UI with Database using Spring and Hibernate.
I am able to successfully call a method to fetch the data through my controller, service etc using REST.
But I am encountering below error,whenever I run the application.
Here "Feedback" is the name of Table in Database as well as the same name of my Pojo Java class.
Note : Giving different names to table and Java class also results in same error.
org.springframework.orm.hibernate3.HibernateQueryException: Feedback
is not mapped [from Feedback]; nested exception is
org.hibernate.hql.ast.QuerySyntaxException: Feedback is not mapped
[from Feedback]
Java Pojo:-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="Feedback")
public class Feedback {
private int id;
private String title;
private String content;
private String name;
#Id
#GeneratedValue
#Column(name="id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name="title", nullable=false)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Column(name="content", nullable=false)
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
#Column(name="name", nullable=false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Feedback [id=" + id + ", title=" + title + ", content="
+ content + ", name=" + name + "]";
}
}
FeedbackDAO :-
#Repository
public class FeedbackDAO implements IFeedbackDAO {
private HibernateTemplate hibernateTemplate;
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
#Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
hibernateTemplate = new HibernateTemplate(sessionFactory);
}
#SuppressWarnings("unchecked")
public List<Feedback> getFeedbackList() {
// This line causes that error.
return hibernateTemplate.find("from Feedback");
}
...
...
}
Configuration made in db-config.xml
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory"><ref local="sessionFactory"/></property>
</bean>
What could be causing this ?
Do am I missing something here ?
Thanks
You might have missed a thing in sessionFactory definition.
<bean id="sessionFactory" ...>
...
<property name="annotatedClasses">
<list>
<value><java package name here>.Feedback</value>
</list>
</property>
...
</bean>
i am getting exception while the server starts. (Server is started using Intelij IDE).
i have no idea how to fix it. i am new to hibernate and spring. thanks in advance.
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authenticationMgr' defined in URL [jar:file:/C:/Program%20Files%20(x86)/Apache%20Software%20Foundation/Tomcat%207.0/webapps/ROOT/WEB-INF/lib/dbservice-1.0-SNAPSHOT.jar!/ApplicationContext-Service.xml]: Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'authenticationDao' threw exception; nested exception is org.springframework.orm.hibernate3.HibernateSystemException: Unknown entity: com.jsi.core.dbservice.model.Authentication; nested exception is org.hibernate.MappingException: Unknown entity: com.jsi.core.dbservice.model.Authentication
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1361)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:871)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4681)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5184)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5179)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
at java.lang.Thread.run(Thread.java:619)
Caused by: org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'authenticationDao' threw exception; nested exception is org.springframework.orm.hibernate3.HibernateSystemException: Unknown entity: com.jsi.core.dbservice.model.Authentication; nested exception is org.hibernate.MappingException: Unknown entity: com.jsi.core.dbservice.model.Authentication
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:102)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:58)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1358)
... 21 more
Authentication entity
/**
* Authentication Entity - Representation of the db table
*/
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
#Entity
#Table(name = "t_authentication")
public class Authentication extends LongBaseEntity implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "auth_id")
private Long mAuthId;
#Column(name = "authentication_id")
private Long mAuthenticationId;
#Column(name = "tcn")
private Long mTcn;
#Column(name = "audit_comment")
private String mAuditComment;
#Column(name = "last_timestamp")
private Date mLastTimeStamp;
#Column(name = "user_id")
private Long mUserId;
#Column(name = "authentication_date")
private Date mAuthenticationDate;
#Column(name = "hostname")
private String mHostname;
#Column(name = "ip_address")
private String mIpAddress;
#Column(name = "referrer_url")
private String mReferrerURL;
#Column(name = "session_id")
private String mSessionId;
public Long getAuthId() {
return mAuthId;
}
public void setAuthId(Long pAuthId) {
this.mAuthId = pAuthId;
mId = pAuthId;
}
public Long getAuthenticationId() {
return mAuthenticationId;
}
public void setAuthenticationId(Long pAuthenticationId) {
this.mAuthenticationId = pAuthenticationId;
}
public Long getTcn() {
return mTcn;
}
public void setTcn(Long pTcn) {
this.mTcn = pTcn;
}
public String getAuditComment() {
return mAuditComment;
}
public void setAuditComment(String pAuditComment) {
this.mAuditComment = pAuditComment;
}
public Date getLastTimeStamp() {
return mLastTimeStamp;
}
public void setLastTimeStamp(Date pLastTimeStamp) {
this.mLastTimeStamp = pLastTimeStamp;
}
public Long getUserId() {
return mUserId;
}
public void setUserId(Long pUserId) {
this.mUserId = pUserId;
}
public Date getAuthenticationDate() {
return mAuthenticationDate;
}
public void setAuthenticationDate(Date pAuthenticationDate) {
this.mAuthenticationDate = pAuthenticationDate;
}
public String getHostname() {
return mHostname;
}
public void setHostname(String pHostname) {
this.mHostname = pHostname;
}
public String getIpAddress() {
return mIpAddress;
}
public void setIpAddress(String pIpAddress) {
this.mIpAddress = pIpAddress;
}
public String getReferrerURL() {
return mReferrerURL;
}
public void setReferrerURL(String pReferrerURL) {
this.mReferrerURL = pReferrerURL;
}
public String getSessionId() {
return mSessionId;
}
public void setSessionId(String pSessionId) {
this.mSessionId = pSessionId;
}
public String toString() {
return "Payment{" +
"mId=" + getId() +
", mIpaddress=" + mIpAddress +
'}';
}
}
DAO class:
/**
* Implementation for AuthenticationMgr DAO layer.
*
*/
import com.jsi.core.dbservice.model.Authentication;
import com.jsi.core.dbservice.model.JSIException;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import java.sql.SQLException;
import java.util.List;
public class AuthenticationDao extends HibernateDaoSupport implements IAuthenticationDao {
#Override
public List<Authentication> list() {
final String query = "Select a from Authentication a order by a.id desc";
return (List<Authentication>) getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
return session.createQuery(query).list();
}
});
}
#Override
public void save(Authentication authentication) throws JSIException {
getHibernateTemplate().save(authentication);
}
#Override
public Authentication load(Long id) {
return getHibernateTemplate().load(Authentication.class, id);
}
#Override
public void update(Authentication authentication) throws JSIException {
getHibernateTemplate().update(authentication);
}
#Override
public void delete(Long id) {
getHibernateTemplate().delete(load(id));
}
}
If you are happened to use HibernateUtil to manipulate the data, you need to add annotated class to your configuration.
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new AnnotationConfiguration().addAnnotatedClass(Authentication.class)
.configure()
.buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
http://docs.jboss.org/hibernate/stable/annotations/reference/en/html/ch01.html
thanks everyone for your reply. i managed to solve it. it was my mistake. i forgot to add the mapping tag in xml.
<hibernate-configuration>
<session-factory>
<mapping class="com.model.Authentication"/> // i missed this line. after i added it. it worked fine.
</session-factory>
</hibernate-configuration>
thanks again.