Hibernate mapping map two columns with other table - java

I have 2 table one is Order and other is OrderList.
Order table is having following fields
customerId : foreign key to customer table
applicationId : foreing key to application table
OrderedAt
OrderedOn
OrderList table has to refer order table using applicationId and customerId and having fields:
customerId: foreing key to Order table\
applicationId: foreing key to Order table
OrderItem
Orderprice
I want to map these two in hibernate.xml file
I am not making a seperate file for OrderList.hibernate.xml:
but using below code in Order.hibernate.xml itself
<list name="orders" table="Order_List" cascade="all" access="field">
<key column="applicationId" not-null="true"/>
<key column="customerId" not-null="true"/>
<list-index column="OrderListIndex" />
<composite-element class="OrderList">
<property name="OrderItem" />
<property name="OrderPrice" />
</composite-element>
</list>
Am I using the right way ?

Looks good to me, though you should switch to using JPA annotations as hbm.xml mappings are deprecated in the latest Hibernate versions and will go away at some point. Also, a lot more people can help you with the annotation model, so you would get answers faster.

Related

Not null key while doing insert using hibernate

I am new to Hibernate and was writing some test program.
I am wondering if its a must to have a table , one column of which will be updated using some kind of sequence.
For ex. I created a table
create table course(course_name varchar2(20));
and when I am defining Course.hbm.xml in the following way
<class name="Course" table="COURSE" >
<property name="course">
<column name="course"/>
</property>
</class>
I am getting an error in the XML file saying a declaration of "id" or something similar is expected. I can give the whole error message if required.
You need an ID column so hibernate can identify that row in the table. I'm not fluent in that oldschool hibernate xml mapping but it should look roughly like that:
create table course(id integer primary key, course_name varchar2(20));
<class name="Course" table="COURSE" >
<id name="id">
<!-- uses sequence, auto increment or whatever your DBMS uses for id generation -->
<generator class="native"/>
</id>
<property name="course">
<column name="course"/>
</property>
</class>
As a side note: mapping your entities with annotations is a bit more common nowadays. Makes it easier, especially for starters.

Storing a common value for the 'employee code' while employing inheritance

There are 3 pojo namely EmployeeMaster (the parent class), Hr and Personal (the child class of EmployeeMaster).
Then I have 3 separate tables for each pojo, constructed as :
create table emp_master(emp_code integer,emp_name text,emp_desig text,
emp_dept text,primary key(emp_code));
create table hr(emp_code integer,salary integer,hra integer,da integer,
taxes integer,grade text,foreign key(emp_code) references emp_master(emp_code));
create table personal(emp_code integer,address text,married bool,
foreign key(emp_code) references emp_master(emp_code));
emp_code is the primary key for emp_master and it is the foreign key for both hr and personal table.
I constructed 3 separate jsp forms to take in the data.
Following is the hibernate mapping file :
<hibernate-mapping>
<class name="pojo.EmployeeMaster" table="emp_master">
<id name="emp_code">
<generator class="assigned" />
</id>
<property name="emp_dept" />
<property name="emp_desig" />
<property name="emp_name" />
<joined-subclass name="pojo.Hr" table="hr">
<key column="emp_code" />
<property name="da" />
<property name="grade" />
<property name="hra" />
<property name="salary" />
<property name="taxes" />
</joined-subclass>
<joined-subclass name="pojo.Personal" table="personal">
<key column="emp_code" />
<property name="address" />
<property name="married" />
</joined-subclass>
</class>
</hibernate-mapping>
Now the problem is,I do not want any null row and want to submit data for the same emp_code into other tables namely hr and personal.
But as I try to submit data into the hr table for emp_code 101, that already exists in the master table I get an error saying Duplicate entry '101' for key 'PRIMARY'.
If I change the generator class to increment in the mapping xml, I get a row with null values,for the data inserted from the child class.What I want is an entry into the three tables with the same employee code. How do I do this ?
Your hibernate mapping suggests that you EmployeeMaster, HR and personal forms a hierarchy, i.e. EmployeeMaster is parent class, while HR and Personal are child classes.
There is something wrong in what you want to achieve and what your mapping suggesting. In above mapping, an ID can be mapped to either HR or to Personal and not both.
You should consider changing the mapping from INHERITANCE to ASSOCIATION.
As per your mapping xml, your java classes should be defined as follows:
public class EmployeeMaster {}
public class HR extends EmployeeMaster{}
public class Personal extends EmployeeMaster{}
Now, you have to device how you can fit your requirements into above model. If that is not the case, then you have no choice but to change the model (xml mapping as well)

Combining delete-orphan with a where condition

Hibernate mapping question where the behavior is ambiguous and/or dangerous. I have a one-to-many relationship that has a cascade-delete-orphan condition AND a where condition to limit the items in the collection. Mapping here -
<hibernate-mapping>
<class name="User" table="user" >
<!-- properties and id ... -->
<set table="email" inverse="true" cascade="all,delete-orphan" where="deleted!=true">
<key column="user_id">
<one-to-many class="Email"/>
</set>
</class>
</hibernate-mapping>
Now suppose that that I have a User object which is associated to one or more Email objects, at least one of which has a 'true' value for the deleted property. Which of the following two will happen when I call session.delete() on the User object?
The User and all the Email objects, including those with deleted=true, are deleted
The User and the Email objects that are deleted!=null are deleted.
On one hand, scenario 1) ignores the where condition, which may not be correct according to the domain model. BUT in scenario 2) if the parent is deleted, and there's a foreign key constraint on the child (email) table's join key, then the delete command will fail. Which happens and why? Is this just another example of how Hibernate's features can be ambiguous?
I didn't test the mapping but in my opinion, the correct (default) behavior should be to ignore the where condition and to delete all the child records (that's the only option to avoid FK constraints violations when deleting the parent). That's maybe not "correct" from a business point of view but the other option is not "correct" either as it just doesn't work.
To sum up, the mapping itself looks incoherent. You should either not cascade the delete operation (and handle the deletion of the child Email manually).
Or, and I think that this might be the most correct behavior, you should implement a soft delete of both the User and associated Email. Something like this:
<hibernate-mapping>
<class name="User" table="user" where="deleted<>'1'">
<!-- properties and id ... -->
<set table="email" inverse="true" cascade="all,delete-orphan" where="deleted<>'1'">
<key column="user_id">
<one-to-many class="Email"/>
</set>
<sql-delete>UPDATE user SET deleted = '1' WHERE id = ?</sql-delete>
</class>
<class name="Email" table="email" where="deleted<>'1'">
<!-- properties and id ... -->
<sql-delete>UPDATE email SET deleted = '1' WHERE id = ?</sql-delete>
</class>
</hibernate-mapping>
What is done here:
We override the default delete using sql-delete to update a flag instead of a real delete (the soft delete).
We filter the entities and the association(s) using the where to only fetch entities that haven't been soft deleted.
This is inspired by Soft deletes using Hibernate annotations. Not tested though.
References
5.1.3. Class
6.2. Collection mappings
16.3. Custom SQL for create, update and delete

Persisting Users using Hibernate

I've created a UserObject and RoleObject to represent users in my application. I'm trying to use hibernate for CRUD instead of raw JDBC. I've successfully retrieved the information from the data base, but I can not create new users. I get the following error.
org.springframework.web.util.NestedServletException: Request processing failed; nested
exception is org.springframework.dao.DataIntegrityViolationException: could not insert:
[com.dc.data.UserRole]; nested exception is
org.hibernate.exception.ConstraintViolationException: could not insert:
[com.dc.data.UserRole]
My data base is defined as follows:
Users Table, Authority Table and Authorities table. Authorities table is a join of users and authority.
My hibernate mapping for UserObjec is as follows:
...
<set name="roles" table="authorities" cascade="save-update" lazy="false" >
<key column="userId" />
<one-to-many class="com.dc.data.UserRole"/>
<many-to-many class="com.dc.data.UserRole" column="authId" />
</set>
</class>
...
UserRole is mapped as follows:
<class name="com.dc.data.UserRole" table="authority">
<id name="id" column="authId">
<generator class="native" />
</id>
<property name="roleName">
<column name="authority" length="60" not-null="true" />
</property>
</class>
How do I need to change my mapping or Object structure to be able to persist new users?
You are defining two different relationships inside of your "set" element. What you probably want is just the many-to-many element.
If this still doesn't work, try saving the UserRole itself to see if you can persist it on its own. If you can, then the ConstraintViolationException is being thrown while trying to persist User.
Last tip, you probably don't want to cascade save/update on the "roles" Set. In all likelihood your UserRoles will already be in the DB and simply be attached to the Users as they get created.
The contraint violation on UserRole might be a cause of trying to insert a row with a duplicate key. Maybe experiment with using other types of generators, such as "sequence".

Hibernate Save strange behaviour

I have a user object that has a one-to-many relationship with String types. I believe they are simple mappings. The types table hold the associated user_id and variable type names, with a primary key 'id' that is basically a counter.
<class name="Users" table="users">
<id column="id" name="id" />
...
<set name="types" table="types" cascade="save-update">
<key column="id" />
<one-to-many class="Types" />
</set>
</class>
<class name="Types" table="types">
<id column="id" name="id" />
<property column="user_id" name="user_id" type="integer" />
<property column="type" name="type" type="string" />
</class>
This is the java I used for adding to the database:
User u = new User();
u.setId(user_id);
...
Collection<Types> t = new HashSet<Types>();
t.add(new Type(auto_incremented_id, user_id, type_name));
u.setTypes(t);
getHibernateTemplate().saveOrUpdate(u);
When I run it, it gives this error:
61468 [http-8080-3] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 1062, SQLState: 23000
61468 [http-8080-3] ERROR org.hibernate.util.JDBCExceptionReporter - Duplicate entry '6' for key 'PRIMARY'
61468 [http-8080-3] ERROR org.hibernate.event.def.AbstractFlushingEventListener - Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
When I check the sql, it shows:
Hibernate: insert into users (name, id) values (?, ?)
Hibernate: insert into types (user_id, type, id) values (?, ?, ?)
Hibernate: update types set id=? where id=?
Why does Hibernate try to update the types' id?
The error says: Duplicate entry '6' for key 'PRIMARY', but there really isn't? I made sure the ids are incremented each time. And the users and types are added into the database correctly.
I logged the information going in, and the types added has an id of 7 and a user id of 6. Could it be that Hibernate takes the user_id of 6 and tried to update types and set id=6 where id=7? Therefore the duplicate primary key error?
But why would it do something so strange? Is there a way to stop it from updating?
Should I set the id manually? If not, then how should I add the types? It gives other errors when I add a type object that only has a type string in it and no ids.
Thanks guys. Been mulling over it for days...
Your biggest problem is incorrect column in the <key> mapping - it should be "user_id", not "id". That said, your whole mapping seems a bit strange to me.
First of all, if you want IDs auto generated you should really let Hibernate take care of that by specifying appropriate generator:
<id column="id" name="id">
<generator class="native"/>
</id>
Read Hibernate Documentation on generators for various available options.
Secondly, if all you need is a set of string types, consider re-mapping them into a collection of elements rather than one-to-many relationship:
<set name="types" table="types">
<key column="user_id"/>
<element column="type" type="string"/>
</set>
That way you won't need explicit "Types" class or mapping for it. Even if you do want to have additional attributes on "Types", you can still map it as component rather than entity.
Finally, if "Types" must be an entity due to some requirement you have not described, the relationship between "Users" and "Types" is bi-directional and needs to be mapped as such:
<set name="types" table="types" inverse="true">
<key column="user_id"/>
<one-to-many class="Types"/>
</set>
...
in Types mapping:
<many-to-one name="user" column="user_id" not-null="true"/>
In the latter case "Types" would have to have a "user" property of type "Users".
Here is a detailed example.
The solution that worked for me was to separately save the two parts (without adding type to user):
getHibernateTemplate().save(user);
getHibernateTemplate().save(new Type(user.id, type_name));
And with the < generator class="native" /> on only the types id.
Bad practice?
Had mapped it as a collection of elements, but it was somewhat wrongly adding the user_id to the types id column which causes duplicate error sometimes; since types id is the only primary key column. Weird! I sort of remember there was some other column error, but forgot about it, because I immediately reverted back to one-to-many. Couldn't grasp the strange workings of Hibernate...
I will try the bi-directional solution sometime... Thanks a lot for all the help :)

Categories