org.hibernate.AnnotationException: #OneToOne or #ManyToOne on ........ references unknown entity: - mysql

I am new to Spring-Hibernate technology facing issue while integrating Spring MVC with Hibernate for relationship of two classes. Below are the code:
The User class:
package com.MVCHibernate.Model;
import java.util.List;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "EMP_USERS")
public class UserModel {
#Id
#GeneratedValue
private int id;
private String username;
private String password;
private String role;
#OneToMany(mappedBy="emp_users")
private List<PermanentEmployeeModel> permanentEmployeeModel;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public List<PermanentEmployeeModel> getPermanentEmployeeModel() {
return permanentEmployeeModel;
}
public void setPermanentEmployeeModel(List<PermanentEmployeeModel> permanentEmployeeModel) {
this.permanentEmployeeModel = permanentEmployeeModel;
}
}
The PermanentEmployeeModel class:
package com.MVCHibernate.Model;
import javax.persistence.*;
#Entity
#Table(name = "EMP_PERMANENT")
public class PermanentEmployeeModel{
#Id
#GeneratedValue
private int eid;
private int fname;
private int lname;
private int salary;
private String grade;
private int date;
// ManyToOne relationship
#ManyToOne
#JoinColumn(name = "id")
private UserModel emp_user;
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public int getFname() {
return fname;
}
public void setFname(int fname) {
this.fname = fname;
}
public int getLname() {
return lname;
}
public void setLname(int lname) {
this.lname = lname;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public int getDate() {
return date;
}
public void setDate(int date) {
this.date = date;
}
public UserModel getEmp_user() {
return emp_user;
}
public void setEmp_user(UserModel emp_user) {
this.emp_user = emp_user;
}
}
employee-servlet.xml:
<context:component-scan base-package="com.MVCHibernate" />
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/Files/" />
<property name="suffix" value=".jsp" />
</bean>
<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/EmployeeMVCHibernate" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.MVCHibernate.Model.UserModel</value>
</list>
</property>
<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>
<!-- PERMANENT EMPLOYEE -->
<bean id="sessionFactory1"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.MVCHibernate.Model.PermanentEmployeeModel</value>
</list>
</property>
<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="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- USER BEANS -->
<!-- <bean id="userDAOImpl" class="com.MVCHibernate.DAO.UserDAOImpl" /> -->
<bean id="userDAOImpl" class="com.MVCHibernate.DAO.UserDAOImpl">
<property name="sessionFactory" ref = "sessionFactory"></property>
</bean>
<bean id="userServiceImpl" class="com.MVCHibernate.Service.UserServiceImpl" />
<!-- EMPLOYEE BEANS -->
<!-- <bean id="pempDAOImpl" class="com.MVCHibernate.DAO.PermanentEmployeeDAOImpl" /> -->
<bean id="pempDAOImpl" class="com.MVCHibernate.DAO.PermanentEmployeeDAOImpl">
<property name="sessionFactory" ref = "sessionFactory1"></property>
</bean>
<bean id="pempServiceImpl" class="com.MVCHibernate.Service.PermanentEmployeeServiceImpl" />
While executing the code it shows the following error :
org.hibernate.AnnotationException: #OneToOne or #ManyToOne on ........
references unknown entity:......
No other solutions on stackoverflow worked for me so far.
Any idea whoat am i doing wrong?

This is working now.
Need to include the mapping resource into the employee-servlet.xml file
**<import resource="classpath*:hibernate.cfg.xml"/>**
hibernate.cfg.xml:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class="com.MVCHibernate.Model.UserModel"></mapping>
<mapping class="com.MVCHibernate.Model.PermanentEmployeeModel"></mapping>
</session-factory>
</hibernate-configuration>

Related

Hibernate #OneToOne gets a NullPointer Exception

I am reviewing my Java skills and your support to the community is amazing, your tips have helped me a lot.
I am stuck in a Hibernate #OneToOne configuration, it is a very simple design and code but I can´t find the error. I´d really appreciate your help.
This is the user.java code, the user_id is generated by an autoincrement column at MySQL. I have omitted hash() and equals() code for simplicity. Hibernate understands the User class but something is missing to get to the Address class that is at the other side of the relationship.
Any help would be very appreciated.
Thank you
1) This is the user.java:
package myPackage;
import java.io.Serializable;
import java.util.Arrays;
import javax.persistence.*;
#Entity
#Table(name="user1")
public class User implements Serializable {
private static final long serialVersionUID = 3271213543123246487L;
#Id
#GeneratedValue
#Column(name="user_id")
private Integer user_id;
#Column(name="user_name", length=100, nullable=false)
private String user_name;
#OneToOne (cascade= CascadeType.ALL)
#PrimaryKeyJoinColumn(name="user_id")
private Address myAddress;
public Integer getUser_id() {
return user_id;
}
public void setUser_id(Integer user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public Address getMyAddress() {
return myAddress;
}
public void setMyAddress(Address myAddress) {
this.myAddress = myAddress;
}
}
2) This is the Address.java code:
package myPackage;
import java.io.Serializable;
import javax.persistence.*;
import org.hibernate.annotations.Parameter;
#Entity
#Table(name="address1")
public class Address implements Serializable {
private static final long serialVersionUID = 3605176021936036836L;
#Id
#GeneratedValue(generator="address_ibfk_2")
#org.hibernate.annotations.GenericGenerator(name="address_ibfk_2",
strategy="foreign",parameters =#Parameter(name="property",value="user1"))
#Column(name="user_id")
private Integer user_id;
#Column(name="address_line1", length=100, nullable=false)
private String address_line1;
public String getAddress_line1() {
return address_line1;
}
public void setAddress_line1(String address_line1) {
this.address_line1 = address_line1;
}
}
3) This is the very simple TestUser class
public class TestUser {
public static void main(String[] args) {
Session mySession = HibernateUtil.getSessionFactory().openSession();
System.out.println("Connection status"+mySession.isConnected());
System.out.println("Session status"+mySession.isOpen());
Transaction myTransaction = mySession.beginTransaction();
try {
User myUser = new User();
Address myAddress = new Address();
myUser.setUser_name("TesteO2O");
myAddress.setAddress_line1("Rua A");
myUser.setMyAddress(myAddress);
mySession.save(myUser);
myTransaction.commit();
System.out.println("myUser saved sucessfully");
} catch (Exception e) {
e.printStackTrace();
myTransaction.rollback();
} finally {
mySession.close();
}
}
}
4) This is the hibernate.cfg.xml config file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!--MySQL Config-->
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/p2pl_dev?serverTimezone=UTC</property>
<property name="connection.username">xyz</property>
<property name="connection.password">blabla</property>
<property name="current_session_context_class">thread</property>
<!--Connection Pool Config: max_statements cached, idle time in seconds-->
<property name="c3po.min_size">2</property>
<property name="c3po.max_size">3</property>
<property name="c3po.timeout">300</property>
<property name="c3po.max_stamentes">50</property>
<property name="c3po.idle_test_period">3000</property>
<!--Debug Config, show_sql=console, format_sql=legible -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="generate_statistics">true</property>
<property name="use_sql_comments">true</property>
<!-- Classes -->
<mapping class="myPackage.User"/>
<mapping class="myPackage.Address"/>
</session-factory>
</hibernate-configuration>
5) Finally the error trace
Hibernate:
/* insert myPackage.User
*/ insert
into
user1
(user_name)
values
(?)
java.lang.NullPointerException
at org.hibernate.tuple.entity.AbstractEntityTuplizer.getPropertyValue(AbstractEntityTuplizer.java:650)
at org.hibernate.persister.entity.AbstractEntityPersister.getPropertyValue(AbstractEntityPersister.java:4736)
at org.hibernate.id.ForeignGenerator.generate(ForeignGenerator.java:96)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:117)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:114)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:684)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:676)
at org.hibernate.engine.spi.CascadingActions$5.cascade(CascadingActions.java:235)
at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:350)
at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:293)
at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:161)
at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:118)
at org.hibernate.event.internal.AbstractSaveEventListener.cascadeAfterSave(AbstractSaveEventListener.java:460)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:294)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
at myPackage.TestUser.main(TestUser.java:26)

Hibernate cannot create table when the entity annotation?

My web project ,spring spring-mvc and hibernate,when the tomcat start there is no tables created in mysql db. why? and no error info
the sessionFactory
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.woodcoder.bean</value>
</list>
</property>
</bean>
the properties
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=false
and I tried hibernate.hbm2ddl.auto=create, it's the same.
Why hibernate doesn't create a table?
The Entity
#Entity
#Table(name="user_bean")
public class UserBean extends BaseBean {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
the baseEntity
#MappedSuperclass
public class BaseBean implements Serializable{
/**
* ID
*/
#Id
#Column(name="id",length = 32, nullable = true)
#GeneratedValue(generator = "uuid")
#GenericGenerator(name = "uuid", strategy = "uuid")
private String id;
#Column(updatable = false)
private Date createDate;
private Date modifyDate;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
yes,i got the problem.
in the hibernate config there are some space in the end of each line,although i cant see them.i delete these space,the table was created.
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=false

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory'

I am getting this error message:
Exception in thread "main"
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [spring-config.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: [Lorg/hibernate/engine/FilterDefinition;
I have one Employee entity class
#Entity
#Table(name = "employee")
public class Employee {
private int id;
private String name;
private float 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 float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
}
In my spring-config.xml file I am not getting the class path in the value attribute in the annotationsession factory bean.
<?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-2.5.xsd">
<bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/srikanth" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>Employee</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
</value>
</property>
</bean>
<bean id="employeeDao" class="EmployeeDao">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
</beans>
This is my main:
public class InsertTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
EmployeeDao employeeDao = (EmployeeDao) context.getBean("employeeDao");
Employee e = new Employee();
e.setId(114);
e.setName("varun");
e.setSalary(50000);
employeeDao.saveEmployee(e);
}
}
Try writing hibernate properties like this:
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
And instead of:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
use:
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
That should work.

Hibernate fail to create Foreign key

I have three class with onetomany and manytoone annotated. Below
Category.java
#Entity
public class Category implements Serializable {
#Id
#GeneratedValue
int id;
String cat;
#OneToMany(cascade= CascadeType.ALL)
#JoinColumn(name="cat_id")
private Collection<Subject> subjects = new ArrayList<Subject>();
#OneToMany(cascade= CascadeType.ALL)
#JoinColumn(name="cat_id")
private Collection<Classes> classes = new ArrayList<Classes>();
#OneToMany(cascade= CascadeType.ALL)
#JoinColumn(name="cat_id")
private Collection<Exam> exam = new ArrayList<Exam>();
public Collection<Subject> getSubjects() {
return subjects;
}
public void setSubjects(Collection<Subject> subjects) {
this.subjects = subjects;
}
public Collection<Classes> getClasses() {
return classes;
}
public void setClasses(Collection<Classes> classes) {
this.classes = classes;
}
public Collection<Exam> getExam() {
return exam;
}
public void setExam(Collection<Exam> exam) {
this.exam = exam;
}
public Category() {
}
public Category(String cat) {
this.cat = cat;
}
//getters/setters}
Classes.java
#Entity
public class Classes implements Serializable {
#Id
#GeneratedValue
int id;
String name;
#Column(name="cat_id")
short cat_id;
short yr;
#ManyToOne
#JoinColumn(name="cat_id", updatable=false,insertable=false)
private Category cat;
public Category getCat() {
return cat;
}
public void setCat(Category cat) {
this.cat = cat;
}
public Classes() {
}
public Classes(String name, short cat_id, short yr) {
this.name = name;
this.cat_id = cat_id;
this.yr = yr;
}
//setters&getters
}
Exam.java
#Entity
public class Exam {
#Id
#GeneratedValue
int id;
String name;
short yr;
#Column(name="cat_id")
short cat_id;
short total;
#Temporal(TemporalType.TIMESTAMP)
Date date_time;
#ManyToOne
#JoinColumn(name="cat_id", updatable=false,insertable=false)
private Category cat;
public Category getCat() {
return cat;
}
public void setCat(Category cat) {
this.cat = cat;
}
public Exam() {
}
public Exam(String name, short yr, short cat_id, short total, Date date_time) {
this.name = name;
this.yr = yr;
this.cat_id = cat_id;
this.total = total;
this.date_time = date_time;
}
getter setter
}
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:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd>
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<mvc:annotation-driven />
<context:annotation-config />
<context:component-scan base-package="org.app.nebula." />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:resources/messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jndiName"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:resources/hibernate.cfg.xml</value>
</property>
<property name="packagesToScan" value="org.app.nebula.domain" />
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
</beans>
now when i run this project, the tables are created but it fails to alter and add a forign key and giving this error
[DEBUG] 33:01(SchemaUpdate.java:execute:203) alter table Classes add
index FK9619D00659EAC034 (cat_id), add constraint FK9619D00659EAC034
foreign key (cat_id) references Category (id)
[ERROR] 33:01(SchemaUpdate.java:execute:212) Unsuccessful: alter
table Classes add index FK9619D00659EAC034 (cat_id), add constraint
FK9619D00659EAC034 foreign key (cat_id) references Category (id)
[ERROR] 33:01(SchemaUpdate.java:execute:213) Can't create table
'nebula.#sql-83c_e3' (errno: 150)
[DEBUG] 33:01(SchemaUpdate.java:execute:203) alter table Exam add
index FK212C3F59EAC034 (cat_id), add constraint FK212C3F59EAC034
foreign key (cat_id) references Category (id)
[ERROR] 33:01(SchemaUpdate.java:execute:212) Unsuccessful: alter
table Exam add index FK212C3F59EAC034 (cat_id), add constraint
FK212C3F59EAC034 foreign key (cat_id) references Category (id)
[ERROR] 33:01(SchemaUpdate.java:execute:213) Can't create table
'nebula.#sql-83c_e3' (errno: 150)
Any help is appreciated.
Thanks & Regards
The Java type of the foreign key should be the same as the type you're referencing to.
You should always use Long values for generated numerical IDs.
Change your Category class as follows:
#Entity public class Category implements Serializable {
#Id
#GeneratedValue
Long id;
[...]
}
BTW: It uncommon to use the Java type short (if you do not have to access legacy C interfaces via JNI for instance).

Spring MVC 3 + JSON

I'm trying to use Spring MVC with JSON. It works great when a return an object from the controller, but when I try to make an AJAX call passing a custom object as parameter I'm getting HTTP 415 error.
My spring-servlet.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
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.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<tx:annotation-driven />
<context:annotation-config/>
<context:component-scan
base-package="com.sommer.controller" />
<tx:annotation-driven transaction-manager="transactionManager"/>
<context:component-scan base-package="com.sommer.service" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8"/>
</bean>
<!-- ========= [ADDED FOR JSON SUPPORT] ========= -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonConverter" />
</list>
</property>
</bean>
<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes" value="application/json" />
</bean>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="es"/>
</bean>
<bean id="handlerMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<ref bean="localeChangeInterceptor" />
</property>
</bean>
<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/sommer"/>
<property name="username" value="root"/>
<property name="password" value="master"/>
</bean>
<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="sommerPersistenceUnit"></property>
</bean>
<bean id="jpaAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:database="MYSQL"
p:showSql="true"
p:generateDdl="true"/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
My controller:
#RequestMapping(value="/editJSON2",headers={"content-type=application/json,application/xml,application/x-www-form-urlencoded"})
public #ResponseBody ActionResult editJSON2(#RequestBody CustomerTO toEdit){
return new ActionResult(toEdit);
}
Classes:
public class ActionResult {
private Boolean success;
private String message;
private Object object;
public ActionResult(){
this.success = true;
this.object = null;
this.message = null;
}
public ActionResult(Boolean isSuccess,Object obj, String message){
this.success = isSuccess;
this.object = obj;
this.message = message;
}
public ActionResult(Object obj){
this.success = true;
this.object = obj;
this.message = "";
}
public ActionResult(String message){
this.success = false;
this.object = null;
this.message = message;
}
public void setError(String msg){
this.success = false;
this.message = msg;
}
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
}
public class CustomerTO {
private Long id;
private String name;
private String email;
private TestObject[] items;
public TestObject[] getItems() {
return items;
}
public void setItems(TestObject[] items) {
this.items = items;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public DocumentType getDocumentType() {
return documentType;
}
public void setDocumentType(DocumentType documentType) {
this.documentType = documentType;
}
public String getDocumentNumber() {
return documentNumber;
}
public void setDocumentNumber(String documentNumber) {
this.documentNumber = documentNumber;
}
private String surname;
private String sex;
private DocumentType documentType;
private String documentNumber;
public CustomerTO() {
}
public CustomerTO(Customer customer) {
this.id = customer.getId();
this.documentNumber = customer.getDocumentNumber();
this.documentType = customer.getDocumentType();
this.name = customer.getName();
this.surname = customer.getSurname();
this.sex = Sex.MALE.equals(customer.getSex())?"M":"F";
this.email = customer.getEmail();
this.items = new TestObject[1];
TestObject tio = new TestObject();
tio.setText("ITEM !");
this.items[0] = tio;
}
My ajax call:
var currentCustomer = {
'id': $('#id').val()
,'name' :$('#name').val()
,'surname' :$('#surname').val()
,'documentType' :$('#documentType').val()
,'documentNumber' :$('#documentNumber').val()
,'sex' :$('#sex').val()
,'email' :$('#email').val()
};
// Send the request
$.post('editJSON2.html', {toEdit:currentCustomer}, function(response) {
alert('OK');
}, 'json');
The problem I think is here:
public #ResponseBody ActionResult editJSON2(#RequestBody CustomerTO toEdit)
I think #ResquestBody is not working for me. I also have
#RequestMapping("/editJSON")
public #ResponseBody ActionResult editJSON(#RequestParam(required=false) Long customerId){
CustomerTO toEdit = customerId!=null ? new CustomerTO(customerService.getById(customerId)):new CustomerTO();
return new ActionResult(toEdit);
}
And when I call it I have no problem.
This is information I collected from firebug:
Parámetrosapplication/x-www-form-urlencoded
toEdit[documentNumber] 36466
toEdit[documentType] DNI
toEdit[email] jpruizmdq#hotmail.com
toEdit[id] 2
toEdit[name] John
toEdit[surname] Doe
Código fuente
toEdit%5Bid%5D=2&toEdit%5Bname%5D=John&toEdit%5Bsurname%5D=Doe&toEdit%5BdocumentType%5D=DNI&toEdit%5BdocumentNumber%5D=36466&toEdit%5Bemail%5D=jpruizmdq%40hotmail.com
It's no tot working because content type of your request is application/x-www-form-urlencoded
and it supposed to be application/json
try to send it with Jquery the following way:
$.ajax({
type: "POST",
url: "someurl",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{id: '" + someId + "'}",
success: function(json) {
}};
Thanks! Problem solved. Here is the code
#RequestMapping(value="/editJSON2")
public #ResponseBody ActionResult editJSON2(#RequestBody CustomerTO toEdit){
return new ActionResult(toEdit);
}
ajaxCall('editJSON2.html',JSON.stringify(currentCustomer),function(valor){
alert('OK');
});
function ajaxCall(url,data,callback,onError){
jQuery.ajax({
url:url
,dataType: 'json'
,data:data
,type: "POST"
,contentType: "application/json; charset=utf-8"
,success:function(actionResult){
-----------
}
,error:function(jqXHR, textStatus, errorThrown){
---
}
});
}
It was simple! I added contentType: "application/json; charset=utf-8" and i used JSON.stringify(currentCustomer). With that it worked