org.hibernate.MappingException: Could not determine typ - java

I'm getting this error.
org.hibernate.MappingException: Could not determine type for: dom.Whore, at table: Message, for columns: [org.hibernate.mapping.Column(receiver)]
This is the class that is being mapped into the table.
package dom;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.stereotype.Component;
#Component
#Entity
public class Message {
private Whore sender;
private Whore receiver;
private Date date = new Date();
private String messageText;
private Boolean read;
private long id;
public Message(){}
public Message(Whore sender, Whore receiver) {
this.sender = sender;
this.receiver = receiver;
}
public Whore getSender() {
return sender;
}
public void setSender(Whore sender) {
this.sender = sender;
}
public Whore getReceiver() {
return receiver;
}
public void setReceiver(Whore receiver) {
this.receiver = receiver;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getMessageText() {
return messageText;
}
public void setMessageText(String messageText) {
this.messageText = messageText;
}
public Boolean getRead() {
return read;
}
public void setRead(Boolean read) {
this.read = read;
}
#Id
#GeneratedValue(generator="increment")
#GenericGenerator(name="increment", strategy="increment")
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
This is the class that the type can't be determined for.
package dom;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.stereotype.Component;
#Component
#Entity
public class Whore {
private String username;
private String password;
private String email;
private List<Whore> friends = new ArrayList<Whore>();
private int reputation;
private long id;
private List<Message> messages = new ArrayList<Message>();
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getReputation() {
return reputation;
}
public void setReputation(int reputation) {
System.out.println("in set reputation : " + reputation);
this.reputation = this.reputation + reputation;
System.out.println("new repuration : " + this.reputation);
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Id
#GeneratedValue(generator="increment")
#GenericGenerator(name="increment", strategy="increment")
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
public List<Whore> getFriends() {
return friends;
}
public void setFriends(List<Whore> friends) {
this.friends = friends;
}
public void addFriend(Whore friend) {
getFriends().add(friend);
}
public void removeFriend(Whore friend) {
getFriends().remove(friend);
}
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
public List<Message> getMessages() {
return messages;
}
public void setMessages(List<Message> messages) {
this.messages = messages;
}
public void addMessage(Message message) {
getMessages().add(message);
}
}
I've read in a lot of posts that it's to do with not setting annotations on fields and getters at the same time. But as you can see that's not the cause here. I'm stumped.
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd">
<context:component-scan base-package="/dom" />
<context:component-scan base-package="/dao" />
<context:component-scan base-package="/controllers" />
<context:component-scan base-package="/services" />
<context:component-scan base-package="/security" />
<tx:annotation-driven />
<mvc:annotation-driven />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/culturewhore" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="/" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</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>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<util:list id="beanList">
<ref bean="mappingJacksonHttpMessageConverter" />
</util:list>
</property>
</bean>
<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:maxUploadSize="1000000" />
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
</beans>
Also I've just tried using #ManyToOne on the sender and receiver getters. But this didn't make any difference.

You haven't mapped the message to whore relationship inside message. Should be:
#ManyToOne
public Whore getSender() {
return sender;
}
#ManyToOne
public Whore getReceiver() {
return receiver;
}
Comment : You shouldn't annotate / use your entity as #Component

You should remove the leading slash ("/") character from your <context:component-scan> tags, and the packagesToScan property of your sessionFactory should be *, not /.

Related

hibernate and spring inegration problems

I am currently trying to integrate hibernate with spring.I am using the dao design pattern and mysql as database. i am trying to add the contacte entity in the db but it's not added and no error was displayed.By the way i can get the list of contact and get it by id but i can't update or insert.
this is my context 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mailmaneger" />
<property name="username" value="root" />
<property name="password" value="" />
<property name="defaultAutoCommit" value="false" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="mysessionFactory" />
</bean>
<bean id="mysessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="packagesToScan" value="biz.picosoft.entity"/>
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="template" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="mysessionFactory"></property>
<property name="checkWriteOperations" value="false"></property>
</bean>
<bean id="d" class="biz.picosoft.daoImpl.ContacteDaoImpl">
<property name="template" ref="template"></property>
</bean>
</beans>
generic dao file
package biz.picosoft.daoImpl;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;
import dao.GenericDao;
#Transactional(readOnly = false)
public class GenericDaoImp<T> implements GenericDao<T> {
HibernateTemplate template;
protected Class<T> daoType;
public GenericDaoImp() {
Type t = getClass().getGenericSuperclass();
ParameterizedType pt = (ParameterizedType) t;
daoType = (Class) pt.getActualTypeArguments()[0];
}
public HibernateTemplate getTemplate() {
return template;
}
public void setTemplate(HibernateTemplate template) {
this.template = template;
}
public void insert(T t) {
// TODO Auto-generated method stub
template.save(t);
}
public void update(T t) {
// TODO Auto-generated method stub
template.update(t);
}
public void delete(T t) {
// TODO Auto-generated method stub
template.delete(t);
}
public T findById(Class<T> t, String id) {
// TODO Auto-generated method stub
return template.get(t, id);
}
public List<T> findAll() {
// TODO Auto-generated method stub
return template.loadAll(daoType);
}
}
contacte dao file
package dao;
import biz.picosoft.entity.Contacte;
public interface ContacteDao extends GenericDao<Contacte> {
}
contactedaoimpl
package biz.picosoft.daoImpl;
import org.springframework.transaction.annotation.Transactional;
import biz.picosoft.entity.Contacte;
import dao.ContacteDao;
#Transactional(readOnly = false)
public class ContacteDaoImpl extends GenericDaoImp<Contacte> implements ContacteDao {
}
the entity
package biz.picosoft.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "Contacte")
public class Contacte implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "idContact")
int idContact;
#Column(name = "nom")
String nom;
#Column(name = "mail")
String mail;
#Column(name = "téléphone")
String téléphone;
#Column(name = "adresse")
String adresse;
public Contacte() {
super();
}
public Contacte(String nom, String mail, String téléphone, String adresse) {
super();
this.nom = nom;
this.mail = mail;
this.téléphone = téléphone;
this.adresse = adresse;
}
public long getIdContact() {
return idContact;
}
public void setIdContact(int idContact) {
this.idContact = idContact;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getTéléphone() {
return téléphone;
}
public void setTéléphone(String téléphone) {
this.téléphone = téléphone;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (idContact ^ (idContact >>> 32));
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Contacte other = (Contacte) obj;
if (idContact != other.idContact)
return false;
return true;
}
}
my main
package biz.picosoft.mains;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import biz.picosoft.daoImpl.ContacteDaoImpl;
import biz.picosoft.entity.Contacte;
public class TestHibernate {
public static void main(String[] args) {
// TODO Auto-generated method stub
Contacte contacte = new Contacte("fatma", "test2", "test", "test");
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
contacte.setIdContact(4);
ContacteDaoImpl contacteDaoImpl = (ContacteDaoImpl) context.getBean("d");
contacteDaoImpl.insert(contacte);
}
}
you don't need to add #Transactional annotation on all DAO implementation, if you already added #Transactional annotation on GenericDaoImp, and other thing put #Transactional(readOnly = false) annotation on method on which method you only fetch the data. That's only suggestion and you problem will resolved after only
replace <property name="defaultAutoCommit" value="false" />
with <property name="defaultAutoCommit" value="true" />
I have tried that and its working for me.
The problem may be that you need to enable annotation support as well as transactions. Try adding the following to your spring xml:
<context:annotation-config/>
<tx:annotation-driven />
FYI you should also check out: Why HibernateTemplate isn't recommended?

inserting entities issue in hibernate

I am currently trying to integrate hibernate with spring.I am using the dao design pattern and mysql as database. i am trying to add the contacte entity in the db but it's not added and no error was displayed.By the way i can get the list of contact and get it by id but i can't update or insert.
this is my context 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mailmaneger" />
<property name="username" value="root" />
<property name="password" value="" />
<property name="defaultAutoCommit" value="false" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="mysessionFactory" />
</bean>
<bean id="mysessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="packagesToScan" value="biz.picosoft.entity"/>
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="template" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="mysessionFactory"></property>
<property name="checkWriteOperations" value="false"></property>
</bean>
<bean id="d" class="biz.picosoft.daoImpl.ContacteDaoImpl">
<property name="template" ref="template"></property>
</bean>
</beans>
this is my generic dao impl
package biz.picosoft.daoImpl;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;
import dao.GenericDao;
#Transactional(readOnly=false)
public class GenericDaoImp<T> implements GenericDao<T> {
HibernateTemplate template;
protected Class<T> daoType;
public GenericDaoImp() {
Type t = getClass().getGenericSuperclass();
ParameterizedType pt = (ParameterizedType) t;
daoType = (Class) pt.getActualTypeArguments()[0];
}
public HibernateTemplate getTemplate() {
return template;
}
public void setTemplate(HibernateTemplate template) {
this.template = template;
}
public void insert(T t) {
// TODO Auto-generated method stub
template.save(t);
}
public void update(T t) {
// TODO Auto-generated method stub
template.update(t);
}
public void delete(T t) {
// TODO Auto-generated method stub
template.delete(t);
}
public T findById(Class<T> t, String id) {
// TODO Auto-generated method stub
return template.get(t, id);
}
public List<T> findAll() {
// TODO Auto-generated method stub
return template.loadAll(daoType);
}
}
this is my entity file
package biz.picosoft.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table( name = "Contacte")
public class Contacte implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "idContact")
int idContact;
#Column(name = "nom")
String nom;
#Column(name = "mail")
String mail;
#Column(name = "téléphone")
String téléphone;
#Column(name = "adresse")
String adresse;
public Contacte() {
super();
}
public Contacte( String nom, String mail, String téléphone, String adresse) {
super();
this.nom = nom;
this.mail = mail;
this.téléphone = téléphone;
this.adresse = adresse;
}
public long getIdContact() {
return idContact;
}
public void setIdContact(int idContact) {
this.idContact = idContact;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getTéléphone() {
return téléphone;
}
public void setTéléphone(String téléphone) {
this.téléphone = téléphone;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (idContact ^ (idContact >>> 32));
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Contacte other = (Contacte) obj;
if (idContact != other.idContact)
return false;
return true;
}
}
my contacteDaoImp file
package biz.picosoft.daoImpl;
import java.util.List;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;
import biz.picosoft.entity.Contacte;
#Transactional(readOnly=false)
public class ContacteDaoImpl extends GenericDaoImp<Contacte> implements ContacteDao{
}
my main
package biz.picosoft.mains;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import biz.picosoft.daoImpl.ContacteDaoImpl;
import biz.picosoft.entity.Contacte;
public class TestHibernate {
public static void main(String[] args) {
// TODO Auto-generated method stub
Contacte contacte=new Contacte("fatma", "test2", "test", "test");
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
contacte.setIdContact (4);
ContacteDaoImpl contacteDaoImpl=(ContacteDaoImpl) context.getBean("d");
System.out.println( contacteDaoImpl.findAll().size());
contacteDaoImpl.insert(contacte);
}
}
please add the following along with its namespace:
xmlns:tx="http://www.springframework.org/schema/tx"
and in schema location:
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
<!-- This tells Spring to activate annotation-driven transactions -->
<tx:annotation-driven/>
You can remove the (readOnly=false) because by default it is false
Reference:
http://springinpractice.com/2008/03/18/annotation-based-transactions-in-spring

org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL)

While Executing the program, I'm getting the particular error
**Exception in thread "main" org.springframework.dao.InvalidDataAccessApiUsageException:
Write operations are not allowed in read-only mode (FlushMode.MANUAL):
Turn your Session into FlushMode.
COMMIT/AUTO or remove 'readOnly' marker from transaction definition.**
every time. please someone help me. Here I am giving my codes which contains some error. In the Below code I have taken one employee data which will be stored in the employee table of MSSQL database. While working with only hibernate at that time i can able to persist my data. But, her i am unable to persist my data.
EmployeeHt.java
This is the entity class which is mapped to the employee table of MSSQL database
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="employee")
public class EmployeeHt {
#Id
#Column(name="id")
private int id;
#Column(name="name")
private String name;
#Column(name="salary")
private int salary;
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 int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
#Override
public String toString() {
return "EmployeeHt [id=" + id + ", name=" + name + ", salary=" + salary + "]";
}
}
EmployeeHtDao.java
This is the class which contains hibernate template
import org.springframework.orm.hibernate5.HibernateTemplate;
public class EmployeeHtDao {
private HibernateTemplate ht;
public void setHt(HibernateTemplate ht) {
this.ht = ht;
}
public void saveEmployee(EmployeeHt e){
ht.save(e);
}
}
EmployeeHtTest.java
**This is the main class**
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class EmployeeHtTest {
private static ApplicationContext context;
public static void main(String[] args) {
context = new ClassPathXmlApplicationContext("hibernateTemplate.xml");
EmployeeHtDao dao=(EmployeeHtDao) context.getBean("edao");
EmployeeHt e=new EmployeeHt();
e.setId(104);
e.setName("Prangyan");
e.setSalary(30000);
dao.saveEmployee(e);
}
}
hibernateTemplate.xml
**This is the spring-xml 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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="connpool" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="url" value="jdbc:sqlserver://localhost:1433;databaseName=ananta"/>
<property name="username" value="sa"/>
<property name="password" value="pass123"/>
</bean>
<bean id="mysessionfactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="connpool"/>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="mysessionfactory"/>
</bean>
<bean id="edao" class="com.sdrc.hibernatetemplate.EmployeeHtDao">
<property name="ht" ref="hibernateTemplate"/>
</bean>
</beans>
Check for #Transactional annotation in you DAO.
It should be
#Transactional(readOnly = false)

Spring + Oracle doesn't persists

I have a problem with Spring and Oracle, I can select objects, but I can't update and insert. (I usually use MySql)
Aplication 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:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
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/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- enabling annotation driven configuration /-->
<context:annotation-config/>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="classpath:jdbc.properties" />
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="{jdbc.username}"
p:password="${jdbc.password}" />
<bean class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"
c:dataSource-ref="dataSource" />
<bean id="jdbcTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource"/>
<tx:annotation-driven transaction-manager="jdbcTransactionManager"/>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource" p:jpaVendorAdapter-ref="jpaAdapter">
<property name="loadTimeWeaver">
<bean
class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
<property name="persistenceUnitName" value="namePU"></property>
</bean>
<bean id="jpaAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:database="${jpa.database}" p:showSql="${jpa.showSql}" />
<!-- Scans the classpath of this application for #Components to deploy as beans -->
<context:component-scan base-package="package.repository" />
<context:component-scan base-package="package.service" />
</beans>
jdbc.properties:
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:#172.172.10.83:1521:orcl
jdbc.username=User
jdbc.password=Password
hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
jpa.database = ORACLE
hibernate.generate_statistics = true
hibernate.show_sql = true
jpa.showSql = true
jpa.generateDdl = true
Usuario class
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "USUARIO")
public class Usuario implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "ID_USUARIO")
private String idUsuario;
#Column(name = "LOGIN")
private String login;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "ID_AMBITO")
private Ambito ambito;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "ID_ROL")
private Rol rol;
public String getIdUsuario() {
return idUsuario;
}
public void setIdUsuario(String idUsuario) {
this.idUsuario = idUsuario;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public Ambito getAmbito() {
return ambito;
}
public void setAmbito(Ambito ambito) {
this.ambito = ambito;
}
public Rol getRol() {
return rol;
}
public void setRol(Rol rol) {
this.rol = rol;
}
}
JPAUsuarioDao
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
#Repository(value = "usuarioDao")
public class JPAUsuarioDao implements UsuarioDao {
private EntityManager em = null;
#PersistenceContext
public void setEntityManager(EntityManager em) {
this.em = em;
}
#Override
#Transactional(readOnly = true)
public List<Usuario> getUsuariosList() {
TypedQuery<Usuario> query = em.createQuery("SELECT u FROM Usuario u",
Usuario.class);
return query.getResultList();
}
#Override
#Transactional(readOnly = true)
public Usuario getUsuario(String login) throws NoResultException {
TypedQuery<Usuario> query = em.createQuery("SELECT u FROM Usuario u WHERE u.login ='" + login + "'",
Usuario.class);
return query.getSingleResult() ;
}
#Override
#Transactional(readOnly = false)
public void addUsuario(Usuario usuario) {
em.merge(usuario);
}
}
This is the exception afer em.merge:
TRACE: org.hibernate.action.internal.UnresolvedEntityInsertActions - No unresolved entity inserts that depended on [[package.domain.Usuario#70675c9a-5eb4-4241-aa83-9cdea9211d18]]
TRACE: org.hibernate.action.internal.UnresolvedEntityInsertActions - No entity insert actions have non-nullable, transient entity dependencies.
Thank you

Spring Data JPA auditing feature is not working in my project

I am reading the book 'ProSpring3' and I am trying to use the Spring Data JPA feature in my project.
I am posting the relevant files here.
src/main/java/foo/bar/domain/ContactAudit.java :
package foo.bar.domain;
import org.hibernate.annotations.Type;
import org.joda.time.DateTime;
import org.springframework.data.domain.Auditable;
import javax.persistence.*;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import static javax.persistence.GenerationType.IDENTITY;
#Table(name = "CONTACT_AUDIT")
#Entity
public class ContactAudit implements Auditable<String, Long>{
private Long id;
private String firstName;
private String lastName;
private Date birthDate;
private int version;
private Set<Hobby> hobbies = new HashSet<Hobby>();
private Set<ContactTelDetail> contactTelDetails = new HashSet<ContactTelDetail>();
//Audit fields
private String createdBy;
private DateTime createdDate;
private String lastModifiedBy;
private DateTime lastModifiedDate;
//constructors
public ContactAudit() {
}
public ContactAudit(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public ContactAudit(String firstName, String lastName, Date birthDate, Set<Hobby> hobbies, Set<ContactTelDetail> contactTelDetails) {
this.firstName = firstName;
this.lastName = lastName;
this.birthDate = birthDate;
this.hobbies = hobbies;
this.contactTelDetails = contactTelDetails;
}
#Column(name = "ID")
#Id
#GeneratedValue(strategy = IDENTITY)
public Long getId() {
return id;
}
#Override
#Transient
public boolean isNew() {
if (id == null)
return true;
else
return false;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "FIRST_NAME")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "LAST_NAME")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Column(name = "BIRTH_DATE")
#Temporal(TemporalType.DATE)
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
#Column(name = "VERSION")
#Version
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
#ManyToMany
#JoinTable(name = "contact_hobby_detail",
joinColumns = #JoinColumn(name = "CONTACT_ID"),
inverseJoinColumns = #JoinColumn(name = "HOBBY_ID"))
public Set<Hobby> getHobbies() {
return hobbies;
}
public void setHobbies(Set<Hobby> hobbies) {
this.hobbies = hobbies;
}
#OneToMany(mappedBy = "contact", cascade = CascadeType.ALL, orphanRemoval = true)
public Set<ContactTelDetail> getContactTelDetails() {
return contactTelDetails;
}
public void setContactTelDetails(Set<ContactTelDetail> contactTelDetails) {
this.contactTelDetails = contactTelDetails;
}
#Column(name = "CREATED_BY")
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
#Column(name = "CREATED_DATE")
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
public DateTime getCreatedDate() {
return createdDate;
}
public void setCreatedDate(DateTime createdDate) {
this.createdDate = createdDate;
}
#Column(name = "LAST_MODIFIED_BY")
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
#Column(name = "LAST_MODIFIED_DATE")
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
public DateTime getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(DateTime lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
//other methods
public String toString()
{
return "Contact - Id: " + id + ", First name: " + firstName + ", Last name: " + lastName + ", Birthday: " + birthDate
+ ", Create by: " + createdBy + ", Create date: " + createdDate + ", Modified by: " + lastModifiedBy + ", Modifed date: " + lastModifiedDate;
}
}
src/main/java/foo/bar/repository/ContactAuditRepository.java :
package foo.bar.repository;
import foo.bar.domain.ContactAudit;
import org.springframework.data.repository.CrudRepository;
public interface ContactAuditRepository extends CrudRepository<ContactAudit, Long>{
}
src/main/java/foo/bar/service/ContactAuditService.java :
package foo.bar.service;
import foo.bar.domain.ContactAudit;
import java.util.List;
public interface ContactAuditService {
public List<ContactAudit> findAll();
public ContactAudit findById(Long id);
public ContactAudit save(ContactAudit contact);
}
src/main/java/foo/bar/service/springjpa/ContactAuditServiceImpl.java
package foo.bar.service.springjpa;
import com.google.common.collect.Lists;
import foo.bar.domain.ContactAudit;
import foo.bar.repository.ContactAuditRepository;
import foo.bar.service.ContactAuditService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
#Service("contactAuditService")
#Repository
#Transactional
public class ContactAuditServiceImpl implements ContactAuditService{
#Autowired
private ContactAuditRepository contactAuditRepository;
#Override
#Transactional(readOnly = true)
public List<ContactAudit> findAll() {
return Lists.newArrayList(contactAuditRepository.findAll());
}
#Override
#Transactional(readOnly = true)
public ContactAudit findById(Long id) {
return contactAuditRepository.findOne(id);
}
#Override
public ContactAudit save(ContactAudit contact) {
return contactAuditRepository.save(contact);
}
}
src/main/java/foo/bar/springjpa/auditor/AuditorAwareBean.java :
package foo.bar.springjpa.auditor;
import org.springframework.data.domain.AuditorAware;
public class AuditorAwareBean implements AuditorAware<String>{
#Override
public String getCurrentAuditor() {
return "prospring3";
}
}
src/main/resources/spring-config.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:jpa="http://www.springframework.org/schema/data/jpa"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<context:annotation-config />
<context:component-scan base-package="foo.bar.service.springjpa"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName">
<value>${jdbc.driverClassName}</value>
</property>
<property name="url">
<value>${jdbc.url}</value>
</property>
<property name="username">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
</bean>
<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="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="packagesToScan" value="foo.bar.domain"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</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:property-placeholder location="jdbc.properties"/>
<jpa:repositories base-package="foo.bar.repository"
entity-manager-factory-ref="emf"
transaction-manager-ref="transactionManager"/>
<jpa:auditing auditor-aware-ref="auditorAwareBean"/>
<bean id="auditorAwareBean" class="foo.bar.springjpa.auditor.AuditorAwareBean"/>
</beans>
src/main/java/META-INF/persistence.xml :
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="NewPersistenceUnit"/>
</persistence>
src/main/java/META-INF/orm.xml :
<?xml version="1.0" encoding="UTF-8" ?>
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_2_0.xsd"
version="2.0">
<description>JPA</description>
<persistence-unit-metadata>
<persistence-unit-defaults>
<entity-listeners>
<entity-listener class="org.springframework.data.jpa.domain.support.AuditingEntityListener"/>
</entity-listeners>
</persistence-unit-defaults>
</persistence-unit-metadata>
</entity-mappings>
--> And the starting point of the app
src/main/java/foo/bar/SpringJpaAuditSample.java :
package foo.bar;
import foo.bar.domain.ContactAudit;
import foo.bar.service.ContactAuditService;
import org.springframework.context.support.GenericXmlApplicationContext;
import java.util.Date;
import java.util.List;
public class SpringJpaAuditSample {
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("spring-config.xml");
ContactAuditService contactService = ctx.getBean("contactAuditService", ContactAuditService.class);
List<ContactAudit> contacts = contactService.findAll();
listContacts(contacts);
//Add new contact
System.out.println("Add new contact");
ContactAudit contact = new ContactAudit();
contact.setFirstName("Michael");
contact.setLastName("Jackson");
contact.setBirthDate(new Date());
contactService.save(contact);
contacts = contactService.findAll();
listContacts(contacts);
}
private static void listContacts(List<ContactAudit> contacts)
{
System.out.println("");
System.out.println("Listing contacts without details:");
for(ContactAudit contact: contacts)
{
System.out.println(contact);
System.out.println();
}
}
}
The findAll returns this :
Listing contacts without details:
Contact - Id: 4, First name: Michael, Last name: Jackson, Birthday: 2013-05-27, Create by: null, Create date: 2013-05-27T04:02:36.000+03:00, Modified by: null, Modifed date: 2013-05-27T04:02:36.000+03:00
Which means that I get null instead of the string 'prospring3'.
Any ideas?
Thank you.
The 'error' I had with this project created with IntelliJ Idea is that I let the IDE create the META-INF directory wherever it chose and I have not noticed that the author had placed it inside resources directory.
The motivation for this fix came out of this post ("No Persistence Unit Found" error).

Categories