JPA - using annotations in a model - java

My application runs on JPA/Hibernate, Spring and Wicket. I'm trying to convert our ORM from XML files to JPA annotations. The annotated model looks like this:
#Entity
#Table(name = "APP_USER")
public class User extends BaseObject {
private Long id;
private String firstName;
private String lastName;
private String email;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
#Column(name = "ID")
public Long getId() {
return id;
}
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="EMAIL")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
/**
* #return Returns firstName and lastName
*/
public String getFullName() {
return firstName + ' ' + lastName;
}
}
Originally, though, it was without annotation and the mapping was described in User.hbm.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.appfuse.model.User" table="app_user">
<id name="id" column="id" unsaved-value="null">
<generator class="increment"/>
</id>
<property name="firstName" column="first_name" not-null="true"/>
<property name="lastName" column="last_name" not-null="true"/>
<property name="email" column="email"/>
</class>
</hibernate-mapping>
When I delete the mapping file and try to use just the annotations, the entityManagerFactory doesn't get created, with the exception
org.hibernate.PropertyNotFoundException:
Could not find a setter for property
fullName in class
org.appfuse.model.User.
There's no mapping set for this property, because it's just a convenience method. What do I do wrong?

Mark the method as #Transient so Hibernate will ignore it:
/**
* #return Returns firstName and lastName
*/
#Transient
public String getFullName() {
return firstName + ' ' + lastName;
}
By default, everything that looks like a getter is mapped.

Related

Select and order list by other condition(Criteria inner join hibernate)

Supposing that we create 2 tables with below SQL :
create table Supplier (id int, name VARCHAR, count int);
create table Product (id int, name VARCHAR, description VARCHAR, price double, supplierId int);
Models:
public class Supplier {
private int id;
private String name;
private int count;
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 getCount() { return count;}
public void setCount(int count) { this.count = count;}
}
AND
public class Product {
private int id;
private String name;
private String description;
private Double price;
private Supplier supplier;
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 String getDescription() { return description;}
public void setDescription(String description) { this.description = description; }
public Double getPrice() {return price;}
public void setPrice(Double price) { this.price = price;}
#OneToOne(targetEntity=ProductAssignment.class, mappedBy = "supplierId", fetch = FetchType.LAZY)
public Supplier getSupplier() { return supplier;}
public void setSupplier(Supplier supplier) { this.supplier = supplier; }
}
If I want to select all products order by count in supplier I can use the below code :
Criteria crit = session.createCriteria(Product.class);
Criteria critSupplier = crit.createCriteria("supplier");
critSupplier.addOrder(Order.desc("count"));
But now, I want to select all suppliers order by price in Product table.
if I want to use MySQL, the below is the script:
select * from supplier s inner join product p ON s.id = p.supplierId order by p.price
Now I want to transfer this SQL into Hibernate Criteria query in java code?
Please help me in this case?
Here you have a bidirectional relationship between two models: Supplier and Product. It is a bidirectional relationship since you want both the models to be aware of each other, and recollect each other information, based on the link that joins them (supplierId). The relationship is also a one(Supplier)-toMany(Products)
So, first off, you are missing the fact that also Supplier must be aware of the existence of the relationship. You have to express this "awareness" by modifying the Supplier model and add to it the list products:
public class Supplier implements Serializable{
private int id;
private String name;
private int count;
private List<Product> products;
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 getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
#Override
public String toString() {
return "Supplier{" + "name=" + name + '}';
}
The second step is to communicate the ORM(in your case hibernate) the relationship between your two models. Online you can find plenty of documentation that explains this subtle "step" of hibernate. in your case, something like this should do.
Hibernate mapping of Supplier:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.xxx.stackoverflowdb.model.Supplier" table="Supplier">
<id column="id" name="id" type="int">
<generator class="assigned"/>
</id>
<property column="name" name="name" type="string"/>
<property column="count" name="count" type="int"/>
<bag name="products" table="product" inverse="true" lazy="false" fetch="select">
<key>
<column name="id"/>
</key>
<one-to-many class="com.xxx.stackoverflowdb.model.Product"/>
</bag>
</class>
</hibernate-mapping>
Hibernate mapping of Product:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.xxx.stackoverflowdb.model.Product" table="PRODUCT">
<id column="id" name="id" type="int">
<generator class="assigned"/>
</id>
<property column="name" name="name" type="string"/>
<property column="description" name="description" type="string"/>
<property column="price" name="price" type="double"/>
<many-to-one name="supplierId" class="com.xxx.stackoverflowdb.model.Supplier" column="supplierId" insert="false" update="false" lazy="false"/>
</class>
</hibernate-mapping>
As you can see, both mapping files declare the relationship. With this set, you can write the Criteria and have it do the job. Since it now hibernate knows about the relationship, it can help you. I've created a simple tester class that demonstrates it:
public class Tester {
public static void main(String[] args) {
//gets a session, assuming your cg file is in a folder called hibernate_dispatcher
//under classpath
SessionFactory sessionFactory = new Configuration().configure("/hibernate_dispatcher/hibernate.cfg.xml")
.buildSessionFactory();
Session session = sessionFactory.openSession();
//gets a session, assuming your cg file is in a folder called hibernate_dispatcher
//under classpath
//YOUR own query --> gets all products order by count in supplier
Criteria criteria1 = session.createCriteria(Product.class);
criteria1.createAlias("supplierId", "supp");
criteria1.addOrder(Order.desc("supp.count"));
for(Object p:criteria1.list()){
Product nthP=(Product)p;
System.out.println(nthP);
}
//YOUR own query --> gets all products order by count in supplier
//the query you've asked --> gets all products order by price in Product
Criteria criteria2 = session.createCriteria(Supplier.class);
criteria2.createAlias("products", "prod");
criteria2.addOrder(Order.desc("prod.price"));
for(Object s:criteria2.list()){
Supplier nthS=(Supplier)s;
System.out.println(nthS);
}
//the query you've asked --> gets all products order by price in Product
}
}

org.hibernate.TransientPropertyValueException

Please What did i wrong, and what should i do?
I have an org.hibernate.TransientPropertyValueException exeption during the compilation when i try to insert objects into my database:
Main class
public class Main {
public static void main(String[] args) {
SessionFactory sessionFactory = new HibernateUtil().getSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Role role = new Role();
role.setTitle("ex-president");
User user1 = new User(100,"Barack","Obama");
User user2 = new User(100,"Ronald","Reagan");
user1.setRole(role);
user2.setRole(role);
session.save(user1);
session.save(user2);
role.getUsers().add(user1);
role.getUsers().add(user2);
session.save(role);
session.getTransaction().commit();
session.close();
}}
HibernateUtil class
public class HibernateUtil {
private static SessionFactory sessionFactory;
static {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(ssrb.build());
}
public SessionFactory getSessionFactory(){
return sessionFactory;
}}
Role class
#Entity
public class Role {
private Long role_id;
private String title;
private Set<User> users = new HashSet<User>();
public Role(){}
public Set<User> getUsers() {
return users;
}
public void addUser(User user){
users.add(user);
}
public void setUsers(Set<User> users) {
this.users = users;
}
public Long getRole_id() {
return role_id;
}
public void setRole_id(Long id) {
this.role_id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}}
User class
#Entity
public class User {
private long user_id;
private int age;
private String firstname;
private String lastname;
private Role role;
public User(){
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public User(int age, String firstname, String lastname) {
this.age = age;
this.firstname = firstname;
this.lastname = lastname;
}
public long getUser_id() {
return user_id;
}
public void setUser_id(long id) {
this.user_id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}}
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<mapping resource="user.cfg.xml"/>
<mapping resource="role.cfg.xml"/>
</session-factory>
</hibernate-configuration>
role.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Role" table="role">
<id name="role_id" column="id">
<generator class="native"/>
</id>
<property name="title" column="TITLE"/>
<set name="users" cascade="all"
inverse="true" lazy="true" fetch="select">
<key column="id" not-null="true"/>
<one-to-many class="User"/>
</set>
</class>
</hibernate-mapping>
user.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="User" table="user">
<id name="user_id" column="user_id">
<generator class="native"/>
</id>
<property name="firstname" column="firstname"/>
<property name="lastname" column="lastname"/>
<property name="age" column="age"/>
<many-to-one name="role" class="Role" fetch="select">
<column name="id" not-null="true"/>
</many-to-one>
</class>
</hibernate-mapping>
Error information in log:
Your program maybe has many mistakes. At least these mistakes what I can point out:
Role role = new Role();
role.setTitle("ex-president");
User user1 = new User(100, "Barack", "Obama");
User user2 = new User(100, "Ronald", "Reagan");
user1.setRole(role);
user2.setRole(role);
session.save(user1);
session.save(user2);
role.getUsers().add(user1);
role.getUsers().add(user2);
session.save(role);
(1) Object role (an instance of class Role) hasn't role_id.
(2) Object user1, user2 hasn't role_id
(3) Must have few record of Role before save user1, user2, because these objects need foreign key (role_id).

could not initialize proxy - no Session (Spring-Hibernate-one to one)

I have two tabeles and I want to fetch on update data from database.
users table(columns):
user_id - username - password - role_id(Foreign Key) - email
user_roles table(columns):
role_id - role
I want to list users in users.jsp . lets see my codes:
User.java
package com.terafast.manager.model;
public class User {
private int id;
private String username;
private String password;
private String email;
private Role role;
public User() {
}
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
}
Role.java
package com.terafast.manager.model;
public class Role {
private int id;
private String role;
public Role() {
}
public Role(String role) {
this.role = role;
}
public long getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
User.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.terafast.manager.model">
<class name="User" table="users">
<id name="id" column="USER_ID">
<generator class="native" />
</id>
<property name="username" column="USERNAME" />
<property name="password" column="PASSWORD" />
<property name="email" column="EMAIL" />
<many-to-one name="Role" class="com.terafast.manager.model.Role"
unique="true" not-null="true" column="role_id" />
</class>
</hibernate-mapping>
Role.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.terafast.manager.model">
<class name="Role" table="user_roles">
<id name="id" column="role_id">
<generator class="native" />
</id>
<property name="role" />
</class>
</hibernate-mapping>
This part is from UserDAOImpl that create List of users:
#Override
#Transactional
public List<User> list() {
#SuppressWarnings("unchecked")
List<User> listUser = (List<User>) sessionFactory.getCurrentSession().createCriteria(User.class)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
return listUser;
}
I already declared public List list(); in UserDAO interface.
This is the part that I send List of users to users.jsp from my Controller:
#RequestMapping("/users/show")
public ModelAndView handleRequest() throws Exception {
List<User> listUsers = userDao.list();
ModelAndView model = new ModelAndView("panel/users");
model.addObject("userList", listUsers);
return model;
}
In jsp file I list Users like this:
<c:forEach var="user" items="${userList}" varStatus="status">
<tr>
<td>${status.index + 1}</td>
<td>${user.username}</td>
<td>${user.email}</td>
<td>${user.role}</td>
<td>Edit
Delete
</td>
</tr>
</c:forEach>
So when I run this project as server I got this output:
Hibernate: select this_.USER_ID as USER_ID1_1_0_, this_.USERNAME as USERNAME2_1_0_, this_.PASSWORD as PASSWORD3_1_0_, this_.EMAIL as EMAIL4_1_0_, this_.role_id as role_id5_1_0_ from users this_
and then this error:
Jul 20, 2015 3:32:06 PM org.apache.catalina.core.ApplicationDispatcher invoke
SEVERE: Servlet.service() for servlet jsp threw exception
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
Could someone explain what is wrong with my program? And how can if I want to add or edit user, what should I do exactly?
By default, all associations are lazy in Hibernate (as opposed to JPA where to-one associations are eager by default).
Either make the association between User and Role eager (lazy="false"):
<many-to-one name="Role" class="com.terafast.manager.model.Role"
lazy="false" unique="true" not-null="true" column="role_id" />
or explicitly initialize the lazy associations which you intend to use out of the session boundaries:
#SuppressWarnings("unchecked")
List<User> listUser = (List<User>) sessionFactory.getCurrentSession().createCriteria(User.class)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
for (User user : listUser) {
Hibernate.initialize(user.getRole());
}
Then in users.jsp, you should use ${user.role.role} to access the value.
Your exception totally depends on Lazy and Eager loading.
Set the <many-to-one> relation with property of lazy with false in your user.hbm.xml file.
try this:
<many-to-one name="Role" class="com.terafast.manager.model.Role"
lazy="false" fetch="select" unique="true" not-null="true" column="role_id" />
and follow #Dragan Bozanovic answer.

org.hibernate.PropertyNotFoundException: Could not find a getter for id in class model.Contact

I am trying to learn Hibernate and I am following this tutorial: http://www.visualcplusdotnet.com/javaopensource/javahibernateswingdesktopapp5.html except I am using my own sample database. I have reverse engineered the POJOs for my contact table which looks like this:
and Netbeans auto-generated a .java file that looked like this (Contact.java):
package model;
// Generated Mar 6, 2015 12:04:10 AM by Hibernate Tools 4.3.1
/**
* Contact generated by hbm2java
*/
public class Contact implements java.io.Serializable {
private Integer id;
private String firstname;
private String lastname;
private String email;
private String phone;
private boolean active;
public Contact() {
}
public Contact(String firstname, String lastname, boolean active) {
this.firstname = firstname;
this.lastname = lastname;
this.active = active;
}
public Contact(String firstname, String lastname, String email, String phone, boolean active) {
this.firstname = firstname;
this.lastname = lastname;
this.email = email;
this.phone = phone;
this.active = active;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstname() {
return this.firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return this.lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return this.phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public boolean isActive() {
return this.active;
}
public void setActive(boolean active) {
this.active = active;
}
}
and a .xml file that looks like this (Contact.hbm.xml)
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Mar 6, 2015 12:04:12 AM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="model.Contact" table="contact" catalog="crmtool" optimistic-lock="version">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="identity" />
</id>
<property name="firstname" type="string">
<column name="firstname" length="100" not-null="true" />
</property>
<property name="lastname" type="string">
<column name="lastname" length="100" not-null="true" />
</property>
<property name="email" type="string">
<column name="email" length="100" />
</property>
<property name="phone" type="string">
<column name="phone" length="10" />
</property>
<property name="active" type="boolean">
<column name="active" not-null="true" />
</property>
</class>
</hibernate-mapping>
After a clean and build, when I run this HQL Query:
from Contact
I get this error:
org.hibernate.PropertyNotFoundException: Could not find a getter for id in class model.Contact
at org.hibernate.property.BasicPropertyAccessor.createGetter(BasicPropertyAccessor.java:310)
at org.hibernate.property.BasicPropertyAccessor.getGetter(BasicPropertyAccessor.java:304)
at org.hibernate.tuple.PropertyFactory.getGetter(PropertyFactory.java:497)
at org.hibernate.tuple.PropertyFactory.buildIdentifierAttribute(PropertyFactory.java:87)
at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:163)
at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:520)
at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:148)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at org.hibernate.persister.internal.PersisterFactoryImpl.create(PersisterFactoryImpl.java:163)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:135)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:400)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1857)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928)
after reading the answers to these questions:
Hibernate - PropertyNotFoundException: Could not find a getter for
PropertyNotFoundException: Could not find a getter for lastMoveDate in class com.hib.objects.GameBoard
org.hibernate.PropertyNotFoundException: could not find getter for customerId in class Address
I figured the answer must be something wrong with the way id is being capitalized by the getter, so I tried:
public Integer getid() {
return this.id;
}
public int getId() {
return this.id;
}
public int getid() {
return this.id;
}
All kinds of things, but still nothing works.
Does anyone know why I'm receiving this error?
Here it is :
Your configuration looks correct. Can do a simple test just rename your id attribute to say contactId and create getters and setters,modify Contact.hbm.xml accordingly and see if hibernate complains of not being able to getter method for the new attribute. Getting this feeling there is some project cleaning up issue
Regards,
Don't try to solve. Change the name of id column to "cid" or "contact_id" or whatever you want.

Can we persist inner enums on Hibernate?

I created an inner enum "UserType" inside my class "User", which is used to determine if an instance of a User is a BASIC, a DEPARTMENT_EXCLUSIVE, or a SUPERUSER. Here's a snippet of the code:
public class User {
private String id, lastName, firstName, middleName, password;
private UserType userType;
public void setId(String id) {
this.id = id;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public void setPassword(String password) {
this.password = Encryption.encrypt(password);
}
public void setUserType(UserType userType) {
this.userType = userType;
}
public String getId() {
return id;
}
public String getLastName() {
return lastName;
}
public String getFirstName() {
return firstName;
}
public String getMiddleName() {
return middleName;
}
public String getPassword() {
return password;
}
public UserType getUserType() {
return userType;
}
public enum UserType {
BASIC, DEPARTMENT_HEAD, SUPERUSER;
}
}
Now, I want to save the instantiated object to my MySQL database using an ORM. I'm using Hibernate. Here's my Hibernate mapping file snippet inside the class tag:
<id name="id" type="string" column="id"/>
<property name="lastName" column="lastName" type="string" not-null="true"/>
<property name="firstName" column="firstName" type="string"/>
<property name="middleName" column="middleName" type="string"/>
<property name="password" column="password" type="string" not-null="true"/>
<property name="userType" column="userType" not-null="true">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">com.fileManagement.dataDesign.User.UserType</param>
<param name="type">12</param>
<param name="useNamed">true</param>
</type>
</property>
I ran some tests and an exception was throw, telling that the enum couldn't be found. Here's the test code:
SessionFactory f = HibernateUtil.getSessionFactory();
Session s = f.openSession();
Transaction t = s.beginTransaction();
User user = new User();
user.setId("0090713");
user.setLastName("Nocos");
user.setFirstName("Warren");
user.setMiddleName("Manlangit");
user.setPassword("wang1234");
user.setUserType(UserType.DEPARTMENT_HEAD);
s.save(user);
t.commit();
s.close();
f.close();
And here's the snippet of the exception stack trace :
Caused by: org.hibernate.HibernateException: Enum class not found
at org.hibernate.type.EnumType.setParameterValues(EnumType.java:244)
at org.hibernate.type.TypeFactory.injectParameters(TypeFactory.java:131)
at org.hibernate.type.TypeFactory.custom(TypeFactory.java:214)
... 12 more
Caused by: java.lang.ClassNotFoundException: com.fileManagement.dataDesign.User.UserType
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:340)
at org.hibernate.internal.util.ReflectHelper.classForName(ReflectHelper.java:171)
at org.hibernate.type.EnumType.setParameterValues(EnumType.java:241)
... 14 more
I tried making the enum as an outer one and it worked well, but I really want to place this inside the "User" class as an inner one due to a design choice, since it's only usable on that class. Is it possible to do that way? If yes, how?
As mentioned in my comments, try declaring the enum class in mapping file as:
com.fileManagement.dataDesign.User$UserType
Generally if we want to access any inner classes in Hibernate then we need to use the $ symbol.

Categories

Resources