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).
Related
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)
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>
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.
I just started to user hibernate and i allways get this Error:
ERROR: HHH000388: Unsuccessful: create table User (id bigint not null auto_increment, mail varchar(255), passwort varchar(255), primary key (id))
ERROR: Got error -1 from storage engine
This is my mapped class:
package Entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class User
{
private long id;
private String mail;
private String passwort;
#Id
#GeneratedValue
#Column(name="id")
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
#Column(name="mail")
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
#Column(name="passwort")
public String getPasswort() {
return passwort;
}
public void setPasswort(String passwort) {
this.passwort = passwort;
}
}
It is because "User" is a reserved keyword. You should change your table name.
The annotation below is the solution for this issue.
#Table(name = "users")
Here is the hibernate config:
<?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.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="connection.pool_size">1</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
</session-factory>
</hibernate-configuration>
I don't know why but I had same issue. Then I just change the name for table with #Table(name="Users") annotation and it started to work.
So try changing this
#Entity
public class User
{
}
to This:
#Entity
#Table(name="Users")
public class User
{
}
Wrong
#Entity /* It will map POJO class with DB Table i,e. Hibernate mapping */
#Table() /* Create Table in DB */
public class User {
}
Right
#Entity /* It will map POJO class with DB Table i,e. Hibernate mapping */
#Table(name="F2CUSER") /* Create Table in DB */
public class User {
}
Here I have use #Table(name="F2CUSER") and it works for me
I'm trying to test my ejb session bean
myFacadeBean = new MyFacadeBean();
MyEntity myEntity = myFacadeBean .getMyData("Hello");
I m trying to test a method in my session bean. I have created EntityManager using
entityManager = Persistence.createEntityManagerFactory("Test").createEntityManager();
I am testing these ejb's outside container. so i configured my persistence.xml as follows:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="Test" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>test.entity.MyEntity</class>
<properties>
<property name="eclipselink.target-database" value="Oracle" />
<property name="eclipselink.jdbc.driver" value="oracle.jdbc.OracleDriver" />
<property name="eclipselink.jdbc.url"
value="jdbc:oracle:thin:#127.0.0.1:1521:orcl" />
<property name="eclipselink.jdbc.user" value="user" />
<property name="eclipselink.jdbc.password" value="pass" />
</properties>
</persistence-unit>
</persistence>
How can i create a SessionContext in this scneario as myFacadeBean is making use of sessionContext to access callerPrincipal().getName();
I dont want to use anything like Ejb3unit
The TestFun-JEE allows you to mock the SessionContext so you could decide what is returned by callerPrincipal().getName().
#Local
public interface UserEjb {
String getCurrentUser();
}
#Stateless
public class UserEjbImpl implements UserEjb{
#Resource
private SessionContext sessionContext;
#Override
public String getCurrentUser() {
return sessionContext.getCallerPrincipal().getName();
}
}
#RunWith(EjbWithMockitoRunner.class)
public class MockSessionContextTest {
#Mock
private SessionContext sessionContext;
#EJB
private UserEjb userEjb;
#Test
public void testSessionContextMock() {
when(sessionContext.getCallerPrincipal()).thenReturn(new Principal() {
#Override
public String getName() {
return "kuki";
}
});
assertEquals("kuki", userEjb.getCurrentUser());
}
}