• Home
  • RSS Feed
  • Log in

Let Hibernate Connect Your World!
Posted by Maarten Winkels in the early morning: February 5th, 2007

At my current project we have to parse a large CSV-file with related data. Each line contains an "entity" or "object" and most lines are related through some references to other lines. The data needs to be send to the server, but some validations and manipulations have to be performed beforehand. Files could become so large, that holding all objects in memory at the client machine could be a problem. We decided to use a Database to temporarily hold the data and to search for related lines. The lines are not necessarily ordered, so we need to wait for the last line to be parsed before validating and manipulating the data. We would like the data to be captured in a nice object oriented model. We used Hibernate and Apache Derby for our implementation and it turned out to be quite convenient!

Schema generation

Hibernate allows for runtime schema generation. This feature is mostly used for tests, but in this case it is very usefull. We don't need the database after the data has been sent, so we create the schema when we setup the Hibernate SessionFactory and drop the schema just before closing it. This will also keep the disk usage after running the application at a minimum.
Apache Derby is a fairly mature database that can be run in process. It will use the disk for storage. We tried using HSQLDB, but searching a large database proved to be very slow.

Inserting data

Now let's say we have lines like these:
10;hospitalId;...
20;hospitalId;patientId;...
30;hospitalId;patientId;treatmentId;...
30;hospitalId;patientId;treatmentId;...
20;hospitalId;patientId;...
30;hospitalId;patientId;treatmentId;...
10;hospitalId;...
20;hospitalId;patientId;...
30;hospitalId;patientId;treatmentId;...
...

We first want to parse this into objects like these:

 
class Hospital {
  int hospitalId;
  String location;
  ...
}
class Patient {
  int hospitalId;
  int patientId;
  String name;
  ...
}
class Treatment {
  int hospitalId;
  int patientId;
  int treatmentId;
  int numberOfDays;
  ...
}
 

Each line represents an object. The first part of the line identified the type of the object. The hospitalId uniquely identifies an Hospital, but the patientId might not be unique across hospitals. The same holds for the treatmentId across patients. Since we cannot ensure that the rows will actually be in order, we cannot make the associations between Hospitals, Patients and Treatments on a line-by-lnie basis. Each Treatment thus has to hold on to it's hospitalId, to enable making the association later on.
The Hibernate mapping to insert this data is rather simple:

 
<hibernate-mapping default-access="field">
	<class name="Hospital">
		<id type="int" column="ID">
			<generator class="native"/>
		</id>
<property name="hospitalId"/>
<property name="location"/>
	</class>
	<class name="Patient">
		<id type="int" column="ID">
			<generator class="native"/>
		</id>
<property name="hospitalId"/>
<property name="patientId"/>
<property name="name"/>
	</class>
	<class name="Hospital">
		<id type="int" column="ID">
			<generator class="native"/>
		</id>
<property name="hospitalId"/>
<property name="patientId"/>
<property name="treatmentId"/>
<property name="numberOfDays"/>
	</class>
</hibernate-mapping>
 

We do not worry about column names, since we will only access the database through Hibernate. Notice furthermore the absence of the name property on the id tag. This means that Hibernate will worry about the ids and that out code does not have to handle them, so there is no id field in any of the classes. This has some far reaching consequences, that make it only usefull in a small number of cases, but our case happens to be one of them (later on in the project we might have to introduce the field nonetheless...).

Reading data

Now, when reading data we would like to use object associations between Patient objects and Hospitals objects and Treatment objects and Patient objects. Actually, a Treatment has to know it's Hospital intimitally too, since the Patient data might be corrupted. The classes need to be adapted like this:

 
class Hospital {
  int hospitalId;
  String location;
  ...
}
class Patient {
  int hospitalId;
  int patientId;
 
  Hospital hospital;
 
  String name;
  ...
}
class Treatment {
  int hospitalId;
  int patientId;
  int treatmentId;
 
  Hospital hospital;
  Patient patient;
 
  int numberOfDays;
  ...
}
 

Now we would like Hibernate to fill in those fields with the related objects. Let's first look at the Patient mapping. We need some sort of many-to-one association in the mapping:

 
...
	<class name="Patient">
		<id type="int" column="ID">
			<generator class="native"/>
		</id>
 
		<many-to-one name="Hospital" column="hospitalId" property-ref="hospitalId" update="false" insert="false" foreign-key="none">
<property name="hospitalId"/>
<property name="patientId"/>
<property name="name"/>
	</class>
...
 

The association mapping is quite intricate:

  1. The column attribute indicates that the association is mapped on the Patient.hospitalId column.
  2. The property-ref attribute indicates that the other end of the association is mapped on the Hospital.hospitalId column. This is not the id property of the Hospital entity!
  3. The hospitalId property is already mapped. Hibernate will complain if you map a column twice unless the mapping is attributed with update="false" insert="false"
  4. The foreign-key attribute set to "none" will prohibit Hibernate generating a foreign key constraint between the columns. Since the order in which the rows will be inserted is uncertain, the constraint would be violated when the Client record is inserted first. Furthermore, corruptions in the data would prevent records from being inserted, while we want to validate the data after it has been inserted in the database.

Pff, there's quite a lot going on in that single line of mapping!

Now let's take a look at the Treatment mapping. Treatment maps onto Patient, but the reference is on two columns. We need to specify these columns as a special construct in the Client mapping.

 
	<class name="Patient">
		<id type="int" column="ID">
			<generator class="native"/>
		</id>
 
		<many-to-one name="hospital" column="hospitalId" property-ref="hospitalId" update="false" insert="false" foreign-key="none"/>
<properties name="reference">
<property name="hospitalId" index="IDX_PATIENT_REFERENCE"/>
<property name="patientId" index="IDX_PATIENT_REFERENCE"/>
		</properties>
<property name="name"/>
	</class>
	<class name="Hospital">
		<id type="int" column="ID">
			<generator class="native"/>
		</id>
 
		<many-to-one name="hospital" column="hospitalId" property-ref="hospitalId" update="false" insert="false" foreign-key="none"/>
		<many-to-one name="patient" property-ref="reference" update="false" insert="false" foreign-key="none">
<column name="hospitalId"/>
<column name="patientId"/>
		</many-to-one>
<property name="hospitalId"/>
<property name="patientId"/>
<property name="treatmentId"/>
<property name="numberOfDays"/>
	</class>
 

In essence, the mapping is the same. The only difference is the property-ref is pointing to a properties construct in the Patient mapping. This construct groups a number of properties. The many-to-one mapping needs the same number of columns as subelements in the same order. Adding the same index name to the properties in the Patient mapping will ensure fast lookup.

Your world is now connected!

So now, we can insert non related objects into the database using Hibernate, but when we fetch them from the database using Hibernate... BAM!... Your world is connected! All data manipulation logic can now safely assume that the associated entities are present. That is of course after validating that the references exist. There is one slight problem: We are not yet protected against duplicates. When hibernate tries to load a Treatment object and it finds that there are two Patient objects that fullfill the reference, it will throw an exception. This cannot be avoided: Hibernate cannot decide which row to use to read the Patient object. In our case we ignore the errors, since there is a validation that checks the uniqueness of patientId. The validation will register an error and further processing of the records is useless. In other cases it might be more intricate.

  • Share/Bookmark

Filed under Hibernate | 2 Comments »



2 Responses to “Let Hibernate Connect Your World!”



    ioannis cherouvim » Blog Archive » Disable foreign key generation in hbm2ddl Says:
    Posted at: August 13, 2007 at 12:47 pm

    [...] Later on, I found another blog mentioning this behavior: http://blog.xebia.com/2007/02/05/let-hibernate-connect-your-world/ [...]



    Cricdigs Says:
    Posted at: February 21, 2008 at 7:58 pm

    This post saved my day! I went ahead and added a reply in the hibernate forums as well! Here is the link to the hibernate forum where people need the same thing: http://forum.hibernate.org/viewtopic.php?t=983300&start=0&postdays=0&postorder=asc&highlight=

    Thanks much!



Leave a Reply

Click here to cancel reply.

Deployment automation for Java application running on Websphere, WebLogic and JBoss

Archives

  • January 2010
  • December 2009
  • November 2009
  • October 2009
  • September 2009
  • August 2009
  • July 2009
  • June 2009
  • May 2009
  • April 2009
  • March 2009
  • February 2009

Xebia Sites

  • Xebia Corporate
  • Xebia France
  • Xebia India

Categories

  • Java (279)
  • Agile (109)
  • General (50)
  • Testing (42)
  • Performance (42)
  • Hibernate (36)
  • Scrum (33)
  • Podcast (31)
  • Architecture (31)
  • Spring (28)
  • SOA (24)
  • Maven (22)
  • Project Management (22)
  • Flex (17)
  • JPA (17)
    • JPA implementation patterns (13)
  • Eclipse (15)
  • Quality Assurance (14)
  • Middleware (19)
  • Frameworks (13)

Tag Cloud

    Introduction to Agile IntelliJ Ajax Semantic Web Closures product owner Seam Hibernate Performance Java Maven Scrum Groovy JavaOne fitnesse Lean Spring XML Functional Programming esb Agile Agile Awareness Workshop SOA Architecture Poppendieck Scala qcon Testing Xebia Grails
medicin depression buy phentermine without a perscription aricept generic hair loss help how do you prevent bone loss urinary tract infection symptoms viagra sex domination cialis viagra cures for throat infection buy sumycin acne care new medication for cancer treatment help for sleeping problems on-line pharmacies cure snoring medications to help clot blood what is aspirin buy zestoretic bronchitis vs pneumonia back pain muscle acne face medication muscle women pain behind knee fat blocker man health arthritis natural cure woman health women insomnia cheap phentermine online cats and irritable bowel syndrome buy cialis generic online nutritional diet for osteoporosis abnormal blood clots treatments for hair loss what is zyprexa dental whitening products impotence herbs drugs for diabetes allergy prevention buy canada levitra Mentax adhd in children hair loss in woman medicines for blood clot online imitrex viagra buy free dog products clindamycin drug how to stop hair loss chloramphenicol discount drug viagra what valium does permanent hair loss heart failure medicine avapro 150mg ordering viagra online food allergies order viagra online online viagra prescription carisoprodol mg improve your skin discount erectile dysfunction medication buy xanax online buy order viagra scabies teatments information allegra vitamine b1 diazepam breast cancer support free stop smoking cipro side effects ultram cheapest treatment attention deficit disorder discount vitamins supplements how to get viagra online synthroid buy cheapest cialis zyrtec online how to clear acne preventive osteoporosis immune stimulants what is hoodia On Line Viagra getting over the pain diflucan dosage health asthma online stores hair loss products blood clot drugs colon parasites hair loss products discount medicine pravastatin buy griseofulvin tablets order indomethacin dog health products how to take a beta-blocker diazapan is valium treating cold sores chronic pain drug what is osteoporosis stress drug tooth whitening lowering cholesterol naturally legality of buying cialis online order levitra treatment for insomnia cheapest cialis index depakote overdose alprazolam condom sales treatment of yeast infection xanax sales taking viagra after cialis how to control pain new birth control chest pain health prozac prescription blood clots viagra in mexico chlamydia pill cancer drugs cold flu drugs how do i order viagra online super viagra acyclovir medicine benadryl dosage erythromycin pregnancy buy contoured condom chronic muscle pain pet health dogs treatment attention deficit disorder dental teeth whitening asthma medicine free prescription drugs herpes drug diabetes treatment buy tooth whitening gel cheap fast valium generic levitra buy cheapest viagra online lopressor drug pharmacy drug prices ultram dosing treatments for bipolar disorder neurontin withdrawal parasite medication chlamydia tips for increasing breast size ways to enhance breast what is valium used for metformin tablet order birth control hair loss for men how does xanax work treatment hepatitis c rythmol cheap acai antioxidants nexium generic blood pressure pills levitra online no prescription Levitra Online medications on line motion sickness drugs bactrim online order roxithromycin nicotine where can i order viagra immune supplements buy erexin v bph prostate allopurinol xanax for depression drug new smoking stop cheap impotence drug generic cialis delivery new treatment for depression antibiotics for cat viagra china alternative medicine cholesterol viagra dose anxiety disorder treatment severe muscle pain treatment of cancer calcium carbonate penis enlargement without pill valium maximum dosage reasons for high blood pressure energy product breast enlargement info cheap effexor building your body wrinkle cream aricept dosage alpha blocker increasing female sex drive valium depression new pain meds no rx xanax drug trileptal mg imitrex avapro 150mg medicine drugs contraception female claritin pill medication for acne med orders buy viagra internet levitra effect treatment for blood clots order sominex buy creatine buy precose cheap viagra overnight lopressor drug body building info health drugs general health and medical what is diazepam eye infections in dogs online prescription pills diclofenac tablet new medication anxiety buy citalopram medication male enhancement enhancement fat blocker medicine for throat infection order cardizem about soma health remedies for dogs generic xanax cheap zyrtec for depression medicine viagra sex domination buy acne skin care product hypnosis help study cure vaginal yeast infection weight loss supplement program muscle pain in leg how to increase erection buy viagra what is cla augmentin doses gaining muscle mass health med online heart rate treatments lopressor drug dog ear canal phentermine without prescription viagra order online weight loss glipizide diabetes astelin generic fat blocker buy gel tooth whitening cheap wellbutrin online weight loss program buy antiox anti-biotics acne skin treatmen tramadole vpxl pill drugs affecting levitra immune system support augmentin hypothyroidism medication buy erexin v uy prescription medication without a prescription buy discount order osteo arthritis online buy pilocarpine cheapest place to buy phentermine parasite treatment impotence help body fat loss viagra herb alternative constipation supplements treatment dementia adhd and medications muscle spasm relief viagra online cheap relieve upper back pain stop hair loss discount viagra online menstrual cycle problems antifungal shampoo side effects ativan gabapentin medication where can i buy viagra diazepam buy soma online clonidine dosage viagra gel top hair loss fast antibiotics cure chlamydia skin fungal infections drug zofran give up smoking alternative medicine cholesterol sleeping help best online viagra scams prednisone 10mg viagra sex domination lotensin easy weight loss pain meds without prescription over the counter drugs new high blood pressure medic generic compazine cetirizine drug order phentermine best fat blockers woman enhancement supplement drug zofran buy precose new drug treatment for cancer how to increase fertility viagra in australia benadryl dosing buy alcoholism medications order l arginine buy diazepam generic for ativan ativan prescription drugs weight loss treatment for chest pain woman health where can i buy phentermine online skin fungal infection give up smoking viagra on line hoodia information how does osteoporosis occur buy viagra online buy alcoholism medications depakote overdose klonopin pill tetracycline capsules what is high blood pressure bladder control for dogs generic for lipitor glucophage online pharmacy gabapentin dosage treating yeast infections dog health info cymbalta anxiety cheap tramadol without prescription hydrea drugs used for cancer cure for high blood pressure alcohol and valium relief from constipation liver infection treatment cialis soft zantac medication help sleep problems all natural antibiotics order medication without prescription sleep problems free hypnotherapy gaining muscle mass cheap viagra order online natural help for pain how to buy viagra drug price celebrex information otc diuretic levitra 10 mg buy medicine online pets products relief foot pain cialis without prescription med care cheapest generic cialis rapid hair loss pain medications generic side effects meds without prescriptions cat anxiety buy simplicef natural cure arthritis effects of high blood pressure lowest price generic viagra how to get birth control new breast cancer drug buy topamax blood pressure meds when are beta blockers prescribed how to get pain meds order fosamax online viagra name order viagra viagra cialis cat's eye health how to relieve lower back pain treating ear infections diazapan is valium online pain doctors high blood pressure in elderly medication to stop smoking wellbutrin dosages diabetes blood sugar levels weight loss diet pill side effects of prescribed pain pills drug list high blood pressure buy cialis online in usa ultram cost how to help osteoporosis how to use clomid discount brand viagra wellbutrin cymbalta buy pills without a prescription buy pain medicine online tab tramadol depression symptoms treatment how levitra work hypertension medications beta blockers prevent premature ejaculation xanax interactions with other medicines purchase medicine on line does alli work xenical mexico prescriptions buy sumycin uy prescription medication without a prescription ambien cost methocarbamol effects cheap beta blockers cats bladder reduce cholesterol naturally metformin tablet scabies medicine breast enhancer pills body building over 50 order viagra cheap zestril medication how to buy prescription medications online pharma kamagra drugs depression ear infection symptoms big muscle controlling blood pressure pain meds and pregnancy buy diazepam without prescription skin allergies antibiotic zoloft buy weight loss nutrition program Buy Cialis breast increase meds without prescriptions blood clots medical edema treatment for flu best hangover remedy diabetes drugs