---- Introductionary information and problem domain ----
Basicly I have 3 tables in a database: 'User', 'Item', 'ItemsPerUser'.
Table User:
username (PK);
password;
email
Table Item
name (PK)
Table ItemsPerUser
username (PK) (and FK);
item_name (PK) (and FK)
When I don't use cascading, I get an error: "Cannot add or update a child row: a foreign key constraint fails".
The mapping files are correct. I need some sort of cascading. It works when I add cascading in the set property of the many-to-many relationship to add non-existent data to User & Item, but it is overwriting data in ItemsPerUser. Whenever I save an object which contains one ore more items which was already entered in ItemsPerUser, it overwrites the row, even when the other part of the PK is not the same user. So basicly the previous user with that 'item' is overwritten by the new user with the same item.
It should always add a new row in the table ItemsPerUser if it is a new user, even with one or more item(s) whom is already entered by another User object.
---- Visual styled example ----
Assume I start with an empty database and I insert a new user Roger, who has two items: coffee and water. This is an example what happens (Hibernate handles this correct):
User ItemsPerUser Item
Roger Roger-coffee coffee
Roger-water water
Now when I insert a new user "Alfonzo" whom has the items coffee and soda, this happens:
User ItemsPerUser Item
Roger Alfonzo-coffee coffee
Alfonzo Roger-water water
Alfonzo-soda soda
---- Code example(s) ----
//Mapping for databag 'User' - !! NOTE: I have deleted the cascade rule in the XML
<hibernate-mapping>
<class name="databag.User" table="User" catalog="androiddb">
<id name="username" type="string">
<column name="username" length="45" />
<generator class="assigned" />
</id>
<property name="password" type="string">
<column name="password" length="45" not-null="true" />
</property>
<property name="email" type="string">
<column name="email" length="45" not-null="true" unique="true" />
</property>
<set name="items" inverse="false" table="itemsperuser">
<key>
<column name="username" length="45" not-null="true" />
</key>
<many-to-many entity-name="databag.Items">
<column name="item_name" length="45" not-null="true"/>
</many-to-many>
</set>
</class>
</hibernate-mapping>
//Mapping for Item
<hibernate-mapping>
<class name="databag.Item" table="item" catalog="androiddb">
<id name="name" type="string">
<column name="name" length="45" />
<generator class="assigned" />
</id>
<set name="users" inverse="false" table="itemsperuser">
<key>
<column name="item_naam" length="45" not-null="true" />
</key>
<many-to-many entity-name="databag.User">
<column name="username" length="45" not-null="true" />
</many-to-many>
</set>
</class>
</hibernate-mapping>
//Saving an object
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction trans = session.beginTransaction();
session.save((User)o);
trans.commit();
session.close();
Note: '(User)o' contains none, one or more items.
You can't set inverse="false" on both sides. Hibernate cannot persists both sets (users in Item and items in User) in the same table, unless one of them is called 'inverse', and can be savely ignored for writing. It will be filled up only when reading.
I'd set inverse="true" on the Item side.
Then you'd have to save items first, then adding them to a user, then saving the user.
Related
I have two tables: patient_data and patient_diagnosis
Patient_data contains personal data of patient like: pid (pkey), gender, birth_date
patient_diagnosis contains the diagnosis data of the registered patients. It has fields like: record_id (pkey), pid (fkey to patient_data(pid)), diagnosis_date and other related fields.
Now, I want to join these two tables on pid and have all these fields in a single type of object.
Here is the mapping file:
<hibernate-mapping>
<class catalog="emr" name="in.Models.Emr" table="patient_diagnosis">
<id name="recordid" type="long">
<column name="record_id"/>
</id>
<property name="diagnosisDate" type="timestamp">
<column length="19" name="diagnosis_date" not-null="true"/>
</property>
<property name="snomedTermPrimary" type="long">
<column name="snomed_term_primary" not-null="true" />
</property>
<property name="snomedTermSecondary" type="string">
<column name="snomed_term_secondary" />
</property>
<property name="episodeNo" type="long">
<column name="episode_no" not-null="true" />
</property>
<property name="pid" type="long">
<column name="pid" not-null="true" />
</property>
<join table="patient_data">
<key column="pid"/>
<property name="gender" type="string">
<column name="gender" not-null="true"/>
</property>
<property name="birthDate" type="timestamp">
<column length="19" name="birth_date" not-null="true"/>
</property>
</join>
</class>
</hibernate-mapping>
But, the join applies on patient_diagnosis.record_id = patient_data.pid instead of patient_diagnosis.pid = patient_data.pid i.e. HQL applies on primary key of first table with mentioned column from second table.
Please provide the solution so that join can be applied on mentioned column from first with mentioned column from second table. Or is there another way out?
Please note that in case I didn't create classes for patient_data or patient_diagnosis. But, just Emr class having combination of fields of these tables is created.
Try giving foreign key
<id name="pid" type="java.lang.Long">
<column name="pid" />
<generator class="foreign">
<param name="property">patient_data</param>
</generator>
</id>
I am not sure but maybe this should work.
And
<one-to-one name="patient_data" class="in.Models.Emr"
cascade="save-update"></one-to-one>
Similarly in Join class
<one-to-one name="patient_diagnosis" class="in.Models.Emr"
cascade="save-update"></one-to-one>
I hope this helps you.
I am using hibernate 4.1.9. I have Users, and the Users have a list of Accounts, and Accounts have list of Transactions. Here is my hbm.xml
<?xml version="1.0"?>
<class name="User" table="users">
<id name="userId" column="userid">
<generator class="increment"/>
</id>
<property name="username" column="username" not-null="true"/>
<property name="password" column="password" not-null="true"/>
<property name="registerDate" type="timestamp" column="register_date"/>
<list name="accounts" table="accounts" inverse="true" cascade="all">
<key column="userid" not-null="true"/>
<index column="accountid"/>
<one-to-many class="com.joe.data.Account"/>
</list>
</class>
<class name="Account" table="accounts">
<id name="accountId" column="accountid">
<generator class="increment"/>
</id>
<property name="balance" type="big_decimal" column="balance"/>
<property name="lastModified" type="timestamp" column="last_modified"/>
<list name="txns" table="transactions" inverse="true" cascade="all">
<key column="accountId" not-null="true"/>
<index column="transactionId"/>
<one-to-many class="com.joe.data.Transaction"/>
</list>
<many-to-one name="userId" class="User" column="userid" not-null="true"
unique="true" cascade="all"/>
<many-to-one name="accountType" class="AccountType" column="account_type"
not-null="true" cascade="all" unique="true" />
</class>
<class name="Transaction" table="transactions">
<id name="transactionId" column="transactionid">
<generator class="increment"/>
</id>
<property name="description" column="description"/>
<property name="amount" type="big_decimal" column="amount"/>
<property name="dateAdded" column="date_added"/>
<property name="reoccuring" type="numeric_boolean" column="reoccuring"/>
<many-to-one name="category" class="Category" column="category"
not-null="true" cascade="all" unique="true" />
</class>
<class name="Category" table="categories">
<id name="categoryId" column="categoryid"/>
<property name="categoryName" column="categoryname" not-null="true"/>
</class>
<class name="AccountType" table="account_types">
<id name="accountType" column="account_type"/>
<property name="accountName" column="name"/>
</class>
If I leave inverse="true" on the list of accounts (in the User) I get the ConstraintViolationException because the userid is not getting put in the insert query. If I take inverse="true" off of the list of accounts, I get org.hibernate.MappingException: Repeated column in mapping for entity: com.joe.data.Account column: accountid (should be mapped with insert="false" update="false")
To clarify lowercase names are database columns names, camel case are class variable names. I know Transaction class isn't working quite right yet, but if I could get the Accounts to insert I could do the same thing to get the Transactions to insert.
Edit: I added the many-to-one on the Account class and now I am getting another exception where hibernate is complaining about missing a getter for userId in com.joe.data.Account
In order to get inverse="true" work, you need to define many-to-one for User in Account and for Account in Transaction class and mappings.
I am looking into Hibernate's parent/child relationships.
I have 3 entities Employee Customers and Orders.
Their relationship is
Employee 1 <-> N Orders
Customer 1 <-> N Orders
I want to be able to save/update/delete Customer objects and Employees and Orders but I want to use some interface so that the calling code does not deal with any Hibernate or JPA stuff.
E.g. I tried something like the following:
class Utils{
public static void saveObject(Object o){
logger.debug(o.toString());
Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
session.save(o);
tx.commit();
session.close();
}
}
and in the calling code I do:
Employee employee = new Employee();
//set data on employee
Customer customer = new Customer();
//set data on customer
Order order = new Order();
//set data on order
employee.addOrder(order);//this adds order to its list, order gets a reference of employee as parent
customer.addOrder(order);//this adds order to its list, order gets a reference of customer as parent
Utils.saveObject(customer);
Utils.saveObject(employee);
Now I noticed that with this code, 2 records of employee are created instead of 1.
If I only do:
Utils.saveObject(customer);
Only 1 (correctly) record is created.
Why does this happen?
Does this happens because the same Order object is saved by both Customer and Employee? And the cascade="all" makes this side-effect?
Now if I do not use the DBUtils method and do directly:
Session session = DBUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
session.save(employee);
session.save(customer);
tx.commit();
session.close();
Again, it works as expected. I.e. only 1 employee record is created.
What am I doing something wrong here?
UPDATE:
Hibernate mappings:
<hibernate-mapping>
<class name="database.entities.Associate" table="EMPLOYEE">
<id name="assosiateId" type="java.lang.Long">
<column name="EMPLOYEEID" />
<generator class="identity" />
</id>
<property name="firstName" type="java.lang.String" not-null="true">
<column name="FIRSTNAME" />
</property>
<property name="lastName" type="java.lang.String" not-null="true">
<column name="LASTNAME" />
</property>
<property name="userName" type="java.lang.String" not-null="true">
<column name="USERNAME" />
</property>
<property name="password" type="java.lang.String" not-null="true">
<column name="PASSWORD" />
</property>
<set name="orders" table="ORDERS" inverse="true" cascade="all" lazy="true">
<key>
<column name="EMPLOYEEID" />
</key>
<one-to-many class="database.entities.Order" />
</set>
</class>
</hibernate-mapping>
<hibernate-mapping>
<class name="database.entities.Customer" table="CUSTOMER">
<id name="customerId" type="java.lang.Long">
<column name="CUSTOMERID" />
<generator class="identity" />
</id>
<property name="customerName" type="java.lang.String">
<column name="CUSTOMERNAME" />
</property>
<set name="orders" table="ORDERS" inverse="true" cascade="all" lazy="true">
<key>
<column name="CUSTOMERID" />
</key>
<one-to-many class="database.entities.Order" />
</set>
</class>
</hibernate-mapping>
<hibernate-mapping>
<class name="database.entities.Order" table="ORDERS">
<id name="orderId" type="java.lang.Long">
<column name="ORDERID" />
<generator class="identity" />
</id>
<property name="orderDate" type="java.util.Date">
<column name="ORDERDATE" />
</property>
<property name="quantity" type="java.lang.Integer">
<column name="QUANTITY" />
</property>
<property name="quantityMargin" type="java.lang.Long">
<column name="QUANTITYMARGIN" />
</property>
<property name="port" type="java.lang.String">
<column name="PORT" />
</property>
<property name="orderState" type="java.lang.String">
<column name="ORDERSTATE" />
</property>
<many-to-one name="customer" class="database.entities.Customer" cascade="all" fetch="join">
<column name="CUSTOMERID" />
</many-to-one>
<many-to-one name="associate" column="EMPLOYEEID" class="database.entities.Employee" cascade="all" fetch="join">
</many-to-one>
</class>
</hibernate-mapping>
UDATE 2:
class Employee{
//Various members
Set<Order> orders = new HashSet<Order>();
public void addOrder(Order order){
order.setEmployee(this);
orders.add(order);
}
}
Also:
class Customer{
//Various members
Set<Order> orders = new HashSet<Order>();
public void addOrder(Order order){
order.setCustomer(this);
orders.add(order);
}
}
It seems to me that in the DBUtils code, you are wrapping both saves in an outer transaction, whereas in the Utils code, you have them in two completely separate transactions without an outer one.
Depending on your cascading, Hibernate has to figure out which objects need to be saved. When you run the Utils code, with two separate transactions, it will save the Order first. Since you're cascading all, this means it will save the Order first, then the Customer. However, you've created the SAME Order for both the Customer and Employee. Therefore, the Employee also gets saved in the first transaction (due to cascading). The second transaction, since it is separate, will not be aware of this and save another Employee.
On the other hand, if you wrap them in an outer transaction, Hibernate can figure out the identities of all the objects and save them properly.
try saving only Order instead of saving Employee and Customer separately. With your existing cascade=all setting both parent object will get saved without creating any duplicates.
Problem #1:
I have three tables; User, UserRole, and UserRoleRelationships (join table). The UserRole table contain all the user roles which I want to associate with the user. When I insert a new user I want to add a new user and add a new association in the join table. Now, when I'm running the query for inserting a new user:
IWUser iwUser = new IWUser();
iwUser.setUsername("username");
iwUser.setFullName("fullName");
iwUser.setEmail("email");
iwUser.setPassword("password");
iwUser.setPrivatephone("55555");
iwUser.setWorkphone("777");
Set<IWUserRole> roleList = new HashSet<IWUserRole>();
IWUserRole iwUserRole = new IWUserRole();
iwUserRole.setRole("ROLE_USER");
roleList.add(iwUserRole);
iwUser.setUserRole(roleList);
iwUserManagementService.saveOrUpdate(iwUser);
hibernate is running the following queries:
Hibernate: insert into dbo.Users (Username, Password, Email, Workphone, Privatephone, FullName) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into dbo.UserRoles (Role) values (?)
Hibernate: insert into UserRoleRelationships (UserId, RoleId) values (?, ?)
My hibernate mapping looks like:
IWUser.hbm.xml:
<hibernate-mapping>
<class name="domain.IWUser" schema="dbo" table="Users">
<id name="userId" type="int">
<column name="UserId"/>
<generator class="native"/>
</id>
<property name="username" type="string">
<column name="Username" not-null="true"/>
</property>
<property name="password" type="string">
<column name="Password" not-null="true"/>
</property>
<property name="email" type="string">
<column name="Email" not-null="false"/>
</property>
<property name="workphone" type="string">
<column name="Workphone" not-null="false"/>
</property>
<property name="privatephone" type="string">
<column name="Privatephone" not-null="false"/>
</property>
<property name="fullName" type="string">
<column name="FullName" not-null="false"/>
</property>
<set cascade="all" inverse="false" name="userRole" table="UserRoleRelationships" lazy="true" >
<key>
<column name="UserId"/>
</key>
<many-to-many class="domain.IWUserRole" column="RoleId"/>
</set>
</class>
</hibernate-mapping>
IWUserRole.hbm.xml:
<hibernate-mapping>
<class name="domain.IWUserRole" schema="dbo" table="UserRoles">
<id name="roleId" type="int">
<column name="RoleId"/>
<generator class="native"/>
</id>
<property name="role" type="string">
<column name="Role" not-null="true"/>
</property>
<set cascade="all" inverse="false" name="user" table="UserRoleRelationships" lazy="true">
<key>
<column name="RoleId"/>
</key>
<many-to-many class="domain.IWUser" column="UserId"/>
</set>
</class>
</hibernate-mapping>
How can I get hibernate to save the new user with an existing user role in the join table?
Problem #2:
When I update the user, hibernate delete the relations in the join table. How can I avoid this?
How can I get hibernate to save the new user with an existing user role in the join table?
Retrieve the user role entity and put that into the list instead of always creating a new one.
I mean this part:
IWUserRole iwUserRole = new IWUserRole();
iwUserRole.setRole("ROLE_USER");
Instead, you'd issue a query like select r from IWUserRole where r.role = 'ROLE_USER'
I have three entities, in which i try to save only 1 entity right now. All the three entities are shown below :-
1. Student Entity
<class name="com.school.Student" table="TABLE_STUDENT">
<id name="id" type="long">
<column name="ST_ID" />
<generator class="native" />
</id>
<property name="name" type="string" column="ST_NAME"/>
<many-to-one name="studentSection" class="com.school.Section" fetch="select">
<column name="SECTION_ID" not-null="true" />
</many-to-one>
<many-to-one name="studentSportsTeam" class="com.school.SportsTeam" fetch="select">
<column name="SPORTS_TEAM" not-null="true" />
</many-to-one>
</class>
2. Section Entity
<class name="com.school.Section" table="TABLE_SECTION">
<id name="sectionId" type="string">
<column name="SECTION_ID" />
<generator class="assigned" />
</id>
<property name="floor" type="string" column="SEC_FLOOR"/>
<property name="capcacity" type="int" column="SEC_CAPACITY"/>
<set name="studentDetails" inverse="true" lazy="true" table="TABLE_STUDENT" fetch="select">
<key>
<column name="SECTION_ID" not-null="true" />
</key>
<one-to-many class="com.school.Student" />
</set>
</class>
3. SprotsTeam Entity :-
<class name="com.school.SportsTeam" table="TABLE_SPORTS">
<id name="sportsTeamId" type="string">
<column name="SPORTS_TEAM" />
<generator class="assigned" />
</id>
<property name="noOfPlayers" type="int" column="SPORTS_PLAYER_NUM"/>
<property name="captainName" type="string" column="SPORTS_CAPTAIN_NAME"/>
<set name="playerDetails" inverse="true" lazy="true" table="TABLE_STUDENT" fetch="select">
<key>
<column name="SPORTS_TEAM" not-null="true" />
</key>
<one-to-many class="com.school.Student" />
</set>
</class>
Now if i try to save Student Entity with proper Section and SportsTeam details, it takes a lot of time to persist it into the database. Currently i am running it for around 10000 students and this process (only persisting) takes around 15 mins. I added some loggers to calculate the complete time.
Now i need to reduce this time, as we will shorty move from 10,000 to 1 million records, and as calculated it takes very long time.. I need to reduce the time , how can i do that??
As Required, also the schema is as below :-
TABLE STUDENT :
ST_ID NUMBER,
ST_NAME VARCHAR(40),
SECTION_ID VARCHAR(10),
SPORTS_TEAM VARCHAR(10)
TABLE_SECTION :
SECTION_ID VARCHAR(10),
SEC_FLOOR VARCHAR(2),
SEC_CAPACITY NUMBER
TABLE_SPORTS :
SPORTS_TEAM VARCHAR(10),
SPORTS_PLAYER_NUM NUMBER,
SPORTS_CAPTAIN_NAME VARCHAR(40)
Please help
Consider batch inserts.
Moreover, if this batch inserts is just for once i.e. as a part of migration process, then IMO, you can consider dropping all primary keys -- and any other indices, on the tables, and then insert the records. After that re-create all those. Hopefully, you would notice a significant improvement.
I think you are trying to import the Student Entity with Section and SportsTeam. At this time if you set the values from the input data to the elements of the Entities and call save on Student entity then it would result into creation of a Student, Section and SportsTeam records in the data base. Which means if you save 10000 student entity then you are effectvely creating 10000 SportsTeam record and 10000 Section record.
Instead I would suggest you to follow these steps:
1. Read a line from the input data
2. query db (through hql) for the already exiting SportsTeam and Section
3. If no records found for SportsTeam and Section then create them
3. Create a new student record and set the SportsTeam and Section from step2.
4. Save the student record.
Also I would suggest you to optimize the creation and save of Students objects in a batch of say 1000 in a single transaction. Closing the hibernate transaction after a batch and releasing the objects would help increase the utilization of DB/Network as well as memory.
I would specify a length for string properties; otherwise they may be implemented as clobs