Solutions to IT problems

Solutions I found when learning new IT stuff

Posts Tagged ‘Spring

Creating a Framework for Chemical Structure Search – Part 4

leave a comment »

Series Overview

This is Part 4 – Component Selection of the “Creating a Framework for Chemical Structure Search“-Series.

Previous posts:



Finally I will start with the actual creation of the framework. In this part I will introduce the main components (existing 3rd party frameworks and libraries) I use and briefly explain my choices. At this point I think it is fair to mention that my work was basically integrating different existing software components into my desired end-product while taking into account real-world problems and offering a solution for them. There are no new magic algorithms in chemical structure searching, modeling or drug discovery to be found here!

My first try

In my previous effort at creating a framework for chemical structure search, I thought being platform independent, especially regarding the used relational database management system (RDBMS), is an important aspect. Therefore I relied on doing the chemical structure search in the application and not the database. However it is exactly that part that lead to huge performance and efficiency problems. I had to do some stuff that just felt wrong and “hacky” to get usable performance.

Encountered issues with Application-based Substructure Search

Object Creation Performance

The first issue was, that for every structure search, all the structures (molfiles) passing the fingerprint screen had to be loaded from the database and converted to an IAtomContainer Object from the Chemistry Development Kit. It was the creation of these objects that was very CPU intensive. This was due to the fact that you had to detect aromaticity and similar things for every AtomContainer object. I found the solution for this in OrChem, a free cartridge for Oracle based on the CDK. The creators seemed to have the exact same issue and came up with their custom format. That format stored everything required like aromaticity and so forth in a CDK-specific way so the creation of IAtomContainers was not an issue anymore.

Substructure Search Performance

The second issue was the mediocre performance of the substructure search itself. The solution was a complex approach using multi-threading and queues. The first thread screened all structures using the pre-generated fingerprints. Fingerprints were stored in the database but loaded into memory on application start. If a structure passed the screen it’s database id was put into a queue. A second thread reads form that queue, loaded the molfile from database and generated the IAtomContainer and put them into a second queue. Then there were multiple threads (configurable amount) that took the AtomContainers from the queue and did the actual test for subgraph isomorphism. Again, if a structure passed this phase too, it’s database id was put into the output queue and the AtomContainer discarded. This last step was required because AtomContainers are memory hogs and you had to control somehow how many there were in memory at any time.

CPU load now easily reached 100% for seconds during substructure searches. I then realized that the database alone could easily use 20% or more of that probably due to loading all the structures form it. So I added the option to hold the custom format from OrChem in memory ( not big of an issue actually in terms of memory consumption) to reduce load on database and hence use those CPU cycles for substructure search. I guess you have long figured out how convoluted this all was. But it actually worked amazingly well! Because the hits were put into a queue it was easily possible to display the first say 5 hits on a web page while the search continued in the background. So you could give the impression of a very fast search!

Why start from scratch again?

So why change it? Tons of reasons. All of this was done with plain JDBC and various kinds of data transfer objects. Tight-Coupling and maintainability was a serious issue. On the application side of things it was impossible to sort the results because hits are returned somewhat randomly and hence real paging was not possible either. The second thing was how could you search for a substructure and a numeric property at the same time? Well the solution for that was, that one of the substructure search methods had a Set-argument. The Set should contain the database ids of the structures the search should be performed over. Hence do an SQL query for the numeric property first and feed the ids into the substructure search. That worked but again, not very straight forward. Adding and using such custom properties to the database was rather messy too, it lacked proper transaction support and so forth. All in all it was nothing to be proud of and certainly not usable in a real production environment. I did however learn a lot about the Java 5 concurrency package.

Component for Substructure Search

I decided that being dependent on a specific RDBMS is a minor issue compared to above outlined problems. I already knew about the open-source Bingo Cartridge and to my luck the company behind it was developing a version for PostgreSQL. So my choice of this component was easy. Use PostgreSQL with Bingo, both are free and open-source.

Application-side Chemistry toolkit

Especially for Input-output the framework required a Chemistry Toolkit and I again chose the Chemistry Development Kit CDK.


While it would be preferable to be independent of the ORM, I wasn’t able to achieve that but I admit I did not but much effort in it. MoleculeDatabaseFramework uses JPA 2.0 and hibernate as it’s JPA provider. The part that is hibernate specific is the custom SQL dialect I created for accessing the Structure Search functions of Bingo in JPQL and hence also QueryDSL. There is no specific reason I chose hibernate except I already knew it and it was able to do what I required. So I did not investigate any other JPA providers.

Application Framework – Dependency-Injection

Well I guess this is obvious. I chose Spring. I’ve heard and read a lot about Spring. I’ve always wanted to learn it and this was my chance. I also did not want the framework to depend an a full-blown Java EE Application server.

Data Access Layer – CRUD and Querying

I initial started the project with plain Spring and JPA (Hibernate). But shortly after I in my “research” I read about Spring Data JPA and it’s integration with QueryDSL. I quote from Spring-Data website:

Spring Data JPA aims to significantly improve the implementation of data access layers by reducing the effort to the amount that’s actually needed. As a developer you write your repository interfaces, including custom finder methods, and Spring will provide the implementation automatically.

To illustrate this here an example snippet showing an example implementation of my framework:

public interface RegistrationCompoundRepository extends ChemicalCompoundRepository {

    List findByRegNumberStartingWith(String regNumber);


RegistrationCompound has a property called regNumber. Above interface method is automatically implemented by Spring Data and will return a result List of the RegistrationCompounds that match the passed in argument. That’s all you need to write. No SQL and not even a method implementation. Just create the interface and then follow the findBy method conventions of Spring Data.

A Spring Data repository can also make use of QueryDSL.

Querydsl is a framework which enables the construction of type-safe SQL-like queries for multiple backends including JPA, JDO and SQL in Java.


List result = query.from(customer)
    .orderBy(customer.lastName.asc(), customer.firstName.desc())

If you use QueryDSL in your Spring Data Repository using QueryDslPredicateExecutor

@Transactional(propagation = Propagation.MANDATORY)
public interface ChemicalCompoundRepository
        extends ChemicalStructureSearchRepository, JpaRepository<T, Long>,
        QueryDslPredicateExecutor {

the repository will have additional methods that take a QueryDSL Predicate as an input. A Predicate is basically the WHERE-Clause of the query, like from above example"A%"). Some methods take additional parameter like a Pageable. This can be used for paging, the Pageable includes the paging (limit, offset) and sorting information.

This all means it is trivial to extend the repository my framework provides and add your own custom search methods to it. With using predicates you can create complex queries which at the same time search by chemical substructure, return the result sorted and paged and all this with a 1-line method declaration.

public Page findByChemicalStructure(String structureData,
            StructureSearchType searchType,
            Pageable pageable, Predicate predicate);

So I hope this got you interested!


Spring Data JPA: My first steps

leave a comment »


In my previous article I showed my first experience with Spring using Hibernate as JPA Provider. After that article I heard about Spring Data and was immediately convinced that it is ideal for my hobby! project. In contrast to my previous article this will not be a tutorial but a short review of my experience with Spring Data. For an introduction of Spring Data please see the Spring Data Reference Guide.

The Good

It works. It is pretty great and I’m sure it can greatly reduce development time for certain types of applications.

CRUD in < 5 minutes

In Spring Data JPA you extend provided repository interfaces. Depending on which interface you extend it comes with different methods, like for CRUD. You don’t have to specify or implement any CRUD methods. You just extend a provided interface and Spring Data JPA will automatically generate implementations at runtime!

Custom Queries

If you need more specific query methods not offered by the repository interfaces you can create your own query methods. There are several version to do so. You can to it by “implicit path”. Meaning you create methods starting with “findBy” and then follow the entities properties along which every path you like. Simple example:

public interface PersonRepository extends Repository<User, Long> {

List<User> findByLastnameStartingWith(String lastname);

This assumes User entity has a property named lastname. Above example is very simple but you can also create such query methods that travel over relationship mappings.

public interface PersonRepository extends Repository<User, Long> {

List<User> findByRolesRoleName(String roleName);

This assumes entity User has a OneToMany mapping to Role entity and Role has a property roleName.

Another option is to specify a JPQL query yourself by annotating it with @Query.

public interface UserRepository extends JpaRepository<User, Long> {

  @Query("select u from User u where u.emailAddress = ?1")
  User findByEmailAddress(String emailAddress);

@Query also supports native queries!

There are even more possibilities . See the Spring Data JPA Reference for further information.

QueryDSL Integration

Spring Data JPA can be easily integrated with QueryDSL.

Querydsl is a framework which enables the construction of type-safe SQL-like queries for multiple back-ends including JPA, JDO and SQL in Java.

This is also very useful.

The Bad

I’m still a novice at both Spring and JPA (Hibernate). So not everything that I mentioned in this section is directly related to Spring Data and can happen when only using Spring or hibernate.

Simplistic Examples

All examples and tutorials I found are mostly based on a simplistic domain model and are for a fixed, well defined, not extendable application. I’m creating a “framework” for applications that need chemical structure search and hence it must be expandable by whomever uses it. So what I’m saying is it works great for very basic, simple usage scenarios but if you have anything half-complex in terms of inheritance and relationships between entities be prepared for issues or the need for adjusting your design to be suitable for your JPA provider, Spring and Spring Data. It’s safe to say I wasted at least 10x times more time searching for solutions to my issues than actual coding.

StackTrace hell

In case of exception you get confronted with a huge stacktrace. While that might not be a bad thing (better than none at all), the actual exception thrown is often not helpful at all at helping you to fix it. This almost drove me crazy.

As example I have a OneToMany relationship between 2 abstract entity classes. In my tests i created 2 different implementations to check if it my framework can deal with that in the way I expect. I had entity C1 and C2 on the “One-side” and A and B on the “Many-side”. The relationship only allows C1 containing As and C2 containing Bs. In my test when loading a B-entity, I would get an exception that C2 does not containing property C1.regNumber. Of course that was true, only C1 has that property. The real issue was, why is hibernate trying to load that property for a C2 entity? It made no sense to me at all. I went on an insane debugging spree through spring and hibernate. I saw that Spring Data had it all right, requested C2 entity. Somewhere deep in hibernate suddenly it changed to a C1. After several hours it dawned on me. The issue was I forgot to add targetEntity = AbstractC to the “Many-side” of the relation, it was on the “one-side”. It appears that hibernate then just chose that targetEntity is C1 instead of throwing an exception the targetEntity property is missing.

Version hell

Due to above issue I tried it with never version of Spring and hibernate and ran into other issues (“Could not load application context”). The context was identical. It turned out some configuration which was not correct worked in earlier version but not in never. And if you have a big XML and exactly one simple property of 1 bean causes this, it is not at all easy to detect. So be prepared for everything to fall over even when doing a minor upgrade.

Configuration hell

This is simple to explain. Use the exact same configuration for your connection pooling and data source. Don’t omit the connection pool in test configuration. Your tests can pass without it and fail with one enabled, especially in my cause were the used version of the connection pool was incompatible with spring 3. You waste a ton of time again to figure that out. I also suggest to use the same database if you have a fixed target. If you application is portable I would still suggest to run at least some integration tests on a different database and probably a “real-one”, meaning not one of the in-memory kinds.


Suitable for beginners?

Spring Data JPA is great but it includes multiple technologies and you need to know each of them especially their quirks.: Spring (ie dependency-injection), JPA and the JPA Provider you use, Spring Data itself, in my case also QueryDSL and the connection pool and its configuration. I was a beginner at all of these technologies and at times it was just too much. So if you are in the same boat as me, you need to be really, really patient and willing to learn. You need to be an expert at using google and at asking questions in forums (stackoverflow) so that readers can easily understand. You must be persistent, have a clear goal and the will to reach it. Else it will be difficult.

However if you already experienced in Spring and the JPA Provider of your choice, I can only recommend you to try it out.

web-applications with spring-data?

Possible. But I have played with Grails and Grails offers most of the above mentioned querying stuff too and more, namely the actually web-part. Spring Data offers nothing in that regard and for an average web-application your better of just using Grails (or other web frameworks). That leaves the question for what you can actually use spring data? I can’t really answer that. I had a unique use-case, create a framework for a special type of database search (chemical structure search) and despite my issues it is very suitable for that. As another option i see is for replacing an existing Data access layer in an existing legacy application, make it more maintainable. Maybe for SOA, eg. Data access layer that has a lot of different clients, web, rich and “automated” ones. Sure there are other possibilities but the conclusion is that Spring Data is for the rapid creation of a maintainable, easy-to use and extensible Data Access Layer and not to create a full application.

Written by kienerj

February 20, 2013 at 14:11

Posted in Database, Java, Programming

Tagged with ,

Spring 3 with JPA 2.0 (Hibernate) for beginners

leave a comment »


This is a follow-up post to Spring 3 and Hibernate 4 for beginners.

After some considerations I decided to change my application to use JPA instead of “native Hibernate”. The configuration here assumes a standalone application, meaning outside of application container like Tomcat. However changing to JNDI and JTA is “only” a matter of configuration.


Entity Classes

If you used JPA annotations for your entity classes you don’t have to change anything. If you want to be fully independent of the JPA Implementation you will need to remove all Hibernate specific annotations which can be problematic in certain cases.

Abstract DAO

This remains almost the same. You need to exchange the sessionFactory with entityManager and thats it.

public abstract class AbstractJpaDAO< T extends Serializable> {

    private Class< T> clazz;
    private EntityManager entityManager;

    public AbstractJpaDAO(final Class< T> clazzToSet) {
        this.clazz = clazzToSet;

    public T getById(final Long id) {
        Preconditions.checkArgument(id != null);
        return getEntityManager().find(clazz, id);

    public List< T> getAll() {
        return getEntityManager().createQuery("from " + clazz.getName())

    public void create(final T entity) {

    public T update(final T entity) {
        return (T) getEntityManager().merge(entity);

    public void delete(final T entity) {

    public void deleteById(final Long entityId) {
        final T entity = getById(entityId);
        Preconditions.checkState(entity != null);

     * @return the entityManager
    public EntityManager getEntityManager() {
        return entityManager;

     * @param entityManager the entityManager to set
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;


First you will not need to create a persistence unit! You can but since spring 3.1 this is not required anymore. If you are using Netbeans and see the warning “The Project does not contain a persistence unit” you can safely ignore it.

Below the new Spring Application-Context file. The important changes are replacing session factory with entity manager factory and changing transaction manager to jpa transaction manager. The datasource and connection pool remains exactly the same.

I’ve also added Service classes to the configuration which I created after writing the previous post.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""



    <context:component-scan base-package="org.bitbucket.kienerj.moleculedatabaseframework" />
    <context:annotation-config />    
    <bean id="entityManagerFactory" autowire="autodetect"
        <property name="dataSource" ref="dataSource" />
        <!-- This scan the packages for entity classes an hence no need for persistence unit -->
        <property name="packagesToScan" value="org.bitbucket.kienerj.moleculedatabaseframework.entity" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="false" />
                <!-- if this is true it can override settings -->
                <property name="generateDdl" value="false" />
                <property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect" />
        <!-- put any ORM specific stuff here -->
        <property name="jpaProperties">
                <!-- for test config only --> 
                <prop key="">create-drop</prop> <
    <!-- Spring bean configuration. Tell Spring to bounce off BoneCP -->
    <bean id="dataSource"
        <property name="targetDataSource">
            <ref local="mainDataSource" />
    <!-- BoneCP configuration -->
    <bean id="mainDataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close">
        <property name="driverClass" value="org.postgresql.Driver" />
        <property name="jdbcUrl" value="jdbc:postgresql:MolDB" />
        <property name="username" value="postgres"/>
        <property name="password" value="123456"/>
        <property name="idleConnectionTestPeriod" value="60"/>
        <property name="idleMaxAge" value="240"/>      
        <property name="maxConnectionsPerPartition" value="60"/>
        <property name="minConnectionsPerPartition" value="20"/>
        <property name="partitionCount" value="3"/>
        <property name="acquireIncrement" value="10"/>                              
        <property name="statementsCacheSize" value="50"/>
        <property name="releaseHelperThreads" value="3"/>
    <bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    <tx:annotation-driven transaction-manager="txManager" />   
    <bean id="chemicalCompoundService" 
    <bean id="chemicalStructureService" autowire="autodetect"
    <bean id="abstractJpaDAO" abstract="true"
    <bean id="chemicalStructureDAO" parent="abstractJpaDAO" autowire="autodetect"
    <bean id="chemicalCompoundDAO" parent="abstractJpaDAO" autowire="autodetect"


Since last post I have created some methods in the DAOs and created a Service Layer. Anyway I had to change my Queries too. The most notable change is that in queries that return 1 result only you need to change uniqueResult() to getSingleResult() but much more important is, that getSingleResult() will throw a NoResultException in case no result was found. In my case this is expected to happen and a common scenario. In my case I simulate behaviour of uniqueResult() by catching the exception and returning null.

public ChemicalStructure getByStructureKey(String structureKey) {

	try {
		ChemicalStructure structure = getEntityManager()
					"FROM ChemicalStructure structure "
				  + "WHERE structure.structureKey = :structureKey", ChemicalStructure.class)
				.setParameter("structureKey", structureKey)
		return structure;
	} catch (NoResultException nre) {
		return null;

Keep in mind you will need to change the application and test config! I wasted a lot of time because I changed application config and then ran tests which failed…Beginners mistake. 🙂

Hope this was helpful.

Written by kienerj

October 16, 2012 at 13:53

Posted in Database, Java, Programming

Tagged with , , ,

Spring 3 and Hibernate 4 for beginners

with 6 comments

Introduction Comments

One would assume there are tons of tutorials and blog post out there about this topic. This is true. There are actually so many it is hard to find one that is up to date and fits your level of knowledge. Most of them assume you are already rather good in using Spring, Hibernate or both. So some very fundamental stuff is never mentioned and that stuff will make your application throw exceptions all over the place. I mainly had trouble with the configuration file and were to put what annotation.

Scope of this Article

This article covers my first steps in using Spring and Hibernate together to create a very basic Data Access Layer. I have never used Spring or Hibernate before in a real application. During my studies in a project I once made a simple app using JPA with TopLink. Some very basic knowledge is required like you should probably have seen an @Entity annotation before (else google it) but in general this is an article from a beginner for beginners. You will need to now basic relational database terms and design principles. The project uses maven and hence you should now some basics of it. Also some knowledge in chemistry will make it easier to understand the example but that is not required. Feel free to comment if you have improvements or suggestions to the design and code shown in this article.

The Problem

The DAL I created should be able to store “chemical compounds”. What is a “chemical compound”? It’s a mixture of substances and each substance occurs in a compound in a percentage. Just like whiskey is a mixture of 40 % ethanol and 60 % water (of course this is a simplified view but you get what I mean). Note that a “substance” has a specific “chemical structure”, eg. its known of which atoms it consists and how they are linked together. To summarize we can say a chemical compound consist multiple “chemical structures” (substances) and a “chemical structure” (substance) can occur in multiple compounds. This is a classic many-to-many relationship.

Hibernate and many-to-many with percentage

It turned out that there is no simple way to create a many-to-many relationship in hibernate where the “link table” has an additional column (the percentage of the substance in the compound). I followed this tutorial and therefore created the java classes as shown in the next section. As a summary you will need to create two one-to-many relationships and a linker class. But in practice it is even more complicated.

The Entity classes


Nothing special here, eg. documentation and comments are sparse ;)..funny comments aside the important part is the @OneToMany annotation towards the bottom of the class and its “mappedBy = “pk.chemicalStructure” attribute.

<br />package org.bitbucket.kienerj.moleculedatabaseframework.entityclasses;<br /><br />import;<br />import java.util.Set;<br />import javax.persistence.CascadeType;<br />import javax.persistence.Column;<br />import javax.persistence.Entity;<br />import javax.persistence.FetchType;<br />import javax.persistence.GeneratedValue;<br />import javax.persistence.GenerationType;<br />import javax.persistence.Id;<br />import javax.persistence.OneToMany;<br />import javax.persistence.SequenceGenerator;<br />import javax.persistence.Table;<br /><br />@Entity<br />@Table(name = "chemical_structure")<br />public class ChemicalStructure implements Serializable {<br /><br /><%%KEEPWHITESPACE%%>    private Long id;<br /><%%KEEPWHITESPACE%%>    private String structureKey;<br /><%%KEEPWHITESPACE%%>    private String structureData;<br /><%%KEEPWHITESPACE%%>    private Set occurence;<br /><br /><%%KEEPWHITESPACE%%>    /**<br /><%%KEEPWHITESPACE%%>     * @return the id<br /><%%KEEPWHITESPACE%%>     */<br /><%%KEEPWHITESPACE%%>    @Id<br /><%%KEEPWHITESPACE%%>    @GeneratedValue(strategy = GenerationType.AUTO, generator = "chem_structure_seq_gen")<br /><%%KEEPWHITESPACE%%>    @SequenceGenerator(name = "chem_structure_seq_gen", sequenceName = "seq_chemical_structure")<br /><%%KEEPWHITESPACE%%>    @Column(name = "structure_id")<br /><%%KEEPWHITESPACE%%>    public Long getId() {<br /><%%KEEPWHITESPACE%%>        return id;<br /><%%KEEPWHITESPACE%%>    }<br /><br /><%%KEEPWHITESPACE%%>    /**<br /><%%KEEPWHITESPACE%%>     * @param id the id to set<br /><%%KEEPWHITESPACE%%>     */<br /><%%KEEPWHITESPACE%%>    public void setId(Long id) {<br /><%%KEEPWHITESPACE%%> = id;<br /><%%KEEPWHITESPACE%%>    }<br /><br /><%%KEEPWHITESPACE%%>    /**<br /><%%KEEPWHITESPACE%%>     * @return the structureKey<br /><%%KEEPWHITESPACE%%>     */<br /><%%KEEPWHITESPACE%%>    @Column(name = "structure_key", unique = true)<br /><%%KEEPWHITESPACE%%>    public String getStructureKey() {<br /><%%KEEPWHITESPACE%%>        return structureKey;<br /><%%KEEPWHITESPACE%%>    }<br /><br /><%%KEEPWHITESPACE%%>    /**<br /><%%KEEPWHITESPACE%%>     * @param structureKey the structureKey to set<br /><%%KEEPWHITESPACE%%>     */<br /><%%KEEPWHITESPACE%%>    public void setStructureKey(String structureKey) {<br /><%%KEEPWHITESPACE%%>        this.structureKey = structureKey;<br /><%%KEEPWHITESPACE%%>    }<br /><br /><%%KEEPWHITESPACE%%>    /**<br /><%%KEEPWHITESPACE%%>     * @return the structureData<br /><%%KEEPWHITESPACE%%>     */<br /><%%KEEPWHITESPACE%%>    @Column(name = "chemical_structure")<br /><%%KEEPWHITESPACE%%>    public String getStructureData() {<br /><%%KEEPWHITESPACE%%>        return structureData;<br /><%%KEEPWHITESPACE%%>    }<br /><br /><%%KEEPWHITESPACE%%>    /**<br /><%%KEEPWHITESPACE%%>     * @param structureData the structureData to set<br /><%%KEEPWHITESPACE%%>     */<br /><%%KEEPWHITESPACE%%>    public void setStructureData(String structureData) {<br /><%%KEEPWHITESPACE%%>        this.structureData = structureData;<br /><%%KEEPWHITESPACE%%>    }<br /><br /><%%KEEPWHITESPACE%%>    @OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.chemicalStructure",<br /><%%KEEPWHITESPACE%%>            cascade = CascadeType.ALL)<br /><%%KEEPWHITESPACE%%>    public Set getOccurence() {<br /><%%KEEPWHITESPACE%%>        return occurence;<br /><%%KEEPWHITESPACE%%>    }<br /><%%KEEPWHITESPACE%%>    public void setOccurence(Set occurence) {<br /><%%KEEPWHITESPACE%%>        this.occurence = occurence;<br /><%%KEEPWHITESPACE%%>    }<br />}<br />


Very similar to ChemicalStructure. Also note the @OneToMany annotation. Here there is some additonal stuff going on. This entity class is configured to be sub-classed. All subclasses will be stored in the same table were the column “compound_type” stores to what entity class a certain row belongs to.

<br />package org.bitbucket.kienerj.moleculedatabaseframework.entityclasses;<br /><br />import;<br />import java.util.HashSet;<br />import java.util.Set;<br />import javax.persistence.CascadeType;<br />import javax.persistence.Column;<br />import javax.persistence.DiscriminatorColumn;<br />import javax.persistence.DiscriminatorType;<br />import javax.persistence.DiscriminatorValue;<br />import javax.persistence.Entity;<br />import javax.persistence.FetchType;<br />import javax.persistence.GeneratedValue;<br />import javax.persistence.GenerationType;<br />import javax.persistence.Id;<br />import javax.persistence.Inheritance;<br />import javax.persistence.InheritanceType;<br />import javax.persistence.OneToMany;<br />import javax.persistence.SequenceGenerator;<br />import javax.persistence.Table;<br />import org.bitbucket.kienerj.moleculedatabaseframework.HashCodeUtil;<br /><br />@Entity<br />@Inheritance(strategy = InheritanceType.SINGLE_TABLE)<br />@Table(name = "chemical_compound")<br />@DiscriminatorColumn(name = "compound_type", discriminatorType=DiscriminatorType.STRING)<br />@DiscriminatorValue("ChemicalCompound")<br />public class ChemicalCompound implements Serializable {<br /><br /><%%KEEPWHITESPACE%%>    private Long id;<br /><%%KEEPWHITESPACE%%>    private String compoundName;<br /><%%KEEPWHITESPACE%%>    private Set composition = new HashSet();<br /><br /><%%KEEPWHITESPACE%%>    /**<br /><%%KEEPWHITESPACE%%>     * @return the id<br /><%%KEEPWHITESPACE%%>     */<br /><%%KEEPWHITESPACE%%>    @Id<br /><%%KEEPWHITESPACE%%>    @GeneratedValue(strategy = GenerationType.AUTO, generator = "chem_compound_seq_gen")<br /><%%KEEPWHITESPACE%%>    @SequenceGenerator(name = "chem_compound_seq_gen", sequenceName = "seq_chem_compound")<br /><%%KEEPWHITESPACE%%>    @Column(name = "chem_compound_id")<br /><%%KEEPWHITESPACE%%>    public Long getId() {<br /><%%KEEPWHITESPACE%%>        return id;<br /><%%KEEPWHITESPACE%%>    }<br /><%%KEEPWHITESPACE%%>    /**<br /><%%KEEPWHITESPACE%%>     * @param id the id to set<br /><%%KEEPWHITESPACE%%>     */<br /><%%KEEPWHITESPACE%%>    public void setId(Long id) {<br /><%%KEEPWHITESPACE%%> = id;<br /><%%KEEPWHITESPACE%%>    }<br /><br /><%%KEEPWHITESPACE%%>    /**<br /><%%KEEPWHITESPACE%%>     * @return the compoundName<br /><%%KEEPWHITESPACE%%>     */<br /><%%KEEPWHITESPACE%%>    @Column(name = "compound_name")<br /><%%KEEPWHITESPACE%%>    public String getCompoundName() {<br /><%%KEEPWHITESPACE%%>        return compoundName;<br /><%%KEEPWHITESPACE%%>    }<br /><%%KEEPWHITESPACE%%>    /**<br /><%%KEEPWHITESPACE%%>     * @param compoundName the compoundName to set<br /><%%KEEPWHITESPACE%%>     */<br /><%%KEEPWHITESPACE%%>    public void setCompoundName(String compoundName) {<br /><%%KEEPWHITESPACE%%>        this.compoundName = compoundName;<br /><%%KEEPWHITESPACE%%>    }<br /><br /><%%KEEPWHITESPACE%%>    @OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.compound", cascade = CascadeType.ALL)<br /><%%KEEPWHITESPACE%%>    public Set getComposition() {<br /><%%KEEPWHITESPACE%%>        return composition;<br /><%%KEEPWHITESPACE%%>    }<br /><%%KEEPWHITESPACE%%>    public void setComposition(Set composition) {<br /><%%KEEPWHITESPACE%%>        this.composition = composition;<br /><%%KEEPWHITESPACE%%>    }<br />}<br />

Now the special or should I say non-intuitive part for which you need to either read the whole hibernate manual or find a tutorial to be able to figure it out. Maybe there is a simpler way but I was lazy and went with the tutorial.

You need the “linker class” defining the “linker table”. That class contains an “ID Class”, ChemicalCompoundCompositionID, which is annotated with @Embeddable. This “ID Class” is used as the primary key (pk) in the “linker class”. But I suggest you look at the code. It’s rather easy to understand but to figure it out yourself…not so much.


<br />package org.bitbucket.kienerj.moleculedatabaseframework.entityclasses;<br /><br />import;<br />import javax.persistence.AssociationOverride;<br />import javax.persistence.AssociationOverrides;<br />import javax.persistence.Column;<br />import javax.persistence.EmbeddedId;<br />import javax.persistence.Entity;<br />import javax.persistence.JoinColumn;<br />import javax.persistence.Table;<br />import javax.persistence.Transient;<br /><br />@Entity<br />@Table(name = "compound_composition")<br />@AssociationOverrides({<br /><%%KEEPWHITESPACE%%>    @AssociationOverride(name = "pk.chemicalStructure",<br /><%%KEEPWHITESPACE%%>    joinColumns =<br /><%%KEEPWHITESPACE%%>    @JoinColumn(name = "chemical_structure_id")),<br /><%%KEEPWHITESPACE%%>    @AssociationOverride(name = "pk.compound",<br /><%%KEEPWHITESPACE%%>    joinColumns =<br /><%%KEEPWHITESPACE%%>    @JoinColumn(name = "chem_compound_id"))})<br />public class ChemicalCompoundComposition implements Serializable {<br /><br /><%%KEEPWHITESPACE%%>    private ChemicalCompoundCompositionID pk = new ChemicalCompoundCompositionID();<br /><%%KEEPWHITESPACE%%>    private Double percentage;<br /><br /><%%KEEPWHITESPACE%%>    @EmbeddedId<br /><%%KEEPWHITESPACE%%>    public ChemicalCompoundCompositionID getPk() {<br /><%%KEEPWHITESPACE%%>        return pk;<br /><%%KEEPWHITESPACE%%>    }<br /><%%KEEPWHITESPACE%%>    public void setPk(ChemicalCompoundCompositionID pk){<br /><%%KEEPWHITESPACE%%> = pk;<br /><%%KEEPWHITESPACE%%>    }<br /><br /><%%KEEPWHITESPACE%%>    @Transient<br /><%%KEEPWHITESPACE%%>    public ChemicalCompound getCompound(){<br /><%%KEEPWHITESPACE%%>        return pk.getCompound();<br /><%%KEEPWHITESPACE%%>    }<br /><%%KEEPWHITESPACE%%>    public void setCompound(ChemicalCompound compound){<br /><%%KEEPWHITESPACE%%>       pk.setCompound(compound);<br /><%%KEEPWHITESPACE%%>    }<br /><br /><%%KEEPWHITESPACE%%>    @Transient<br /><%%KEEPWHITESPACE%%>    public ChemicalStructure getChemicalStructure(){<br /><%%KEEPWHITESPACE%%>        return pk.getChemicalStructure();<br /><%%KEEPWHITESPACE%%>    }<br /><%%KEEPWHITESPACE%%>    public void setChemicalStructure(ChemicalStructure structure){<br /><%%KEEPWHITESPACE%%>       pk.setChemicalStructure(structure);<br /><%%KEEPWHITESPACE%%>    }<br /><br /><%%KEEPWHITESPACE%%>    /**<br /><%%KEEPWHITESPACE%%>     * @return the percentage<br /><%%KEEPWHITESPACE%%>     */<br /><%%KEEPWHITESPACE%%>    @Column(name = "percentage", nullable = false)<br /><%%KEEPWHITESPACE%%>    public Double getPercentage() {<br /><%%KEEPWHITESPACE%%>        return percentage;<br /><%%KEEPWHITESPACE%%>    }<br /><%%KEEPWHITESPACE%%>    /**<br /><%%KEEPWHITESPACE%%>     * @param percentage the percentage to set<br /><%%KEEPWHITESPACE%%>     */<br /><%%KEEPWHITESPACE%%>    public void setPercentage(Double percentage) {<br /><%%KEEPWHITESPACE%%>        this.percentage = percentage;<br /><%%KEEPWHITESPACE%%>    }<br />}<br /><br />


<br />package org.bitbucket.kienerj.moleculedatabaseframework.entityclasses;<br /><br />import;<br />import javax.persistence.Embeddable;<br />import javax.persistence.ManyToOne;<br /><br />@Embeddable<br />public class ChemicalCompoundCompositionID implements Serializable {<br /><br /><%%KEEPWHITESPACE%%>    private ChemicalCompound compound;<br /><%%KEEPWHITESPACE%%>    private ChemicalStructure chemicalStructure;<br /><br /><%%KEEPWHITESPACE%%>    @ManyToOne(fetch = FetchType.LAZY)<br /><%%KEEPWHITESPACE%%>    public ChemicalCompound getCompound() {<br /><%%KEEPWHITESPACE%%>        return compound;<br /><%%KEEPWHITESPACE%%>    }<br /><br /><%%KEEPWHITESPACE%%>    public void setCompound(ChemicalCompound compound) {<br /><%%KEEPWHITESPACE%%>        this.compound= compound;<br /><%%KEEPWHITESPACE%%>    }<br /><br /><%%KEEPWHITESPACE%%>    @ManyToOne(fetch = FetchType.LAZY)<br /><%%KEEPWHITESPACE%%>    public ChemicalStructure getChemicalStructure() {<br /><%%KEEPWHITESPACE%%>        return chemicalStructure;<br /><%%KEEPWHITESPACE%%>    }<br /><br /><%%KEEPWHITESPACE%%>    public void setChemicalStructure(ChemicalStructure structure) {<br /><%%KEEPWHITESPACE%%>        this.chemicalStructure = structure;<br /><%%KEEPWHITESPACE%%>    }<br />}<br />

As you can see this is far more complex than you would have imaged. We also need to create an entity (ChemicalCompoundComposition) that has no real meaning in the real world and for each compound you will create you will have to create as many ChemicalCompoundComposition instances as the compound contains substances. Note that fetch = FetchType.LAZY is absolutely required in the @Embeddable ID because else session.merge(chemicalCompound) will lead to a StackOverflowError (endless references).

The Data Access Objects

Now we need to create the layer that actually persists the entities to the database. To create that layer I followed the design outlined in The Persistence Layer with Spring 3.1 and Hibernate. We create a generic abstract class AbstractHibernateDAO that contains the basic database operations. The concrete classes are very simple as the only point of them is to specify which type of Entity they save. Of course you can add methods or override some if required.


The important part are the annotations @Repository, @Transactional and @Autowired

<br />package org.bitbucket.kienerj.moleculedatabaseframework.dao;<br /><br />import;<br />import;<br />import java.util.List;<br />import org.hibernate.Session;<br />import org.hibernate.SessionFactory;<br />import org.springframework.beans.factory.annotation.Autowired;<br />import org.springframework.stereotype.Repository;<br />import org.springframework.transaction.annotation.Transactional;<br /><br />@Repository<br />@Transactional<br />public abstract class AbstractHibernateDAO&lt; T extends Serializable&gt; {<br /><br /><%%KEEPWHITESPACE%%>    private final Class&lt; T&gt; clazz;<br /><%%KEEPWHITESPACE%%>    @Autowired<br /><%%KEEPWHITESPACE%%>    SessionFactory sessionFactory;<br /><br /><%%KEEPWHITESPACE%%>    public AbstractHibernateDAO(final Class&lt; T&gt; clazzToSet) {<br /><%%KEEPWHITESPACE%%>        this.clazz = clazzToSet;<br /><%%KEEPWHITESPACE%%>    }<br /><br /><%%KEEPWHITESPACE%%>    public T getById(final Long id) {<br /><%%KEEPWHITESPACE%%>        Preconditions.checkArgument(id != null);<br /><%%KEEPWHITESPACE%%>        return (T) this.getCurrentSession().get(this.clazz, id);<br /><%%KEEPWHITESPACE%%>    }<br /><br /><%%KEEPWHITESPACE%%>    public List&lt; T&gt; getAll() {<br /><%%KEEPWHITESPACE%%>        return this.getCurrentSession()<br /><%%KEEPWHITESPACE%%>                .createQuery("from " + this.clazz.getName()).list();<br /><%%KEEPWHITESPACE%%>    }<br /><br /><%%KEEPWHITESPACE%%>    public void create(final T entity) {<br /><%%KEEPWHITESPACE%%>        Preconditions.checkNotNull(entity);<br /><%%KEEPWHITESPACE%%>        this.getCurrentSession().persist(entity);<br /><%%KEEPWHITESPACE%%>    }<br /><br /><%%KEEPWHITESPACE%%>    public void update(final T entity) {<br /><%%KEEPWHITESPACE%%>        Preconditions.checkNotNull(entity);<br /><%%KEEPWHITESPACE%%>        this.getCurrentSession().merge(entity);<br /><%%KEEPWHITESPACE%%>    }<br /><br /><%%KEEPWHITESPACE%%>    public void delete(final T entity) {<br /><%%KEEPWHITESPACE%%>        Preconditions.checkNotNull(entity);<br /><%%KEEPWHITESPACE%%>        this.getCurrentSession().delete(entity);<br /><%%KEEPWHITESPACE%%>    }<br /><br /><%%KEEPWHITESPACE%%>    public void deleteById(final Long entityId) {<br /><%%KEEPWHITESPACE%%>        final T entity = this.getById(entityId);<br /><%%KEEPWHITESPACE%%>        Preconditions.checkState(entity != null);<br /><%%KEEPWHITESPACE%%>        this.delete(entity);<br /><%%KEEPWHITESPACE%%>    }<br /><br /><%%KEEPWHITESPACE%%>    public void setSessionFactory(SessionFactory sessionFactory) {<br /><%%KEEPWHITESPACE%%>        this.sessionFactory = sessionFactory;<br /><%%KEEPWHITESPACE%%>    }<br /><br /><%%KEEPWHITESPACE%%>    protected final Session getCurrentSession() {<br /><%%KEEPWHITESPACE%%>        return this.sessionFactory.getCurrentSession();<br /><%%KEEPWHITESPACE%%>    }<br />}<br />


<br />package org.bitbucket.kienerj.moleculedatabaseframework.dao;<br /><br />import org.bitbucket.kienerj.moleculedatabaseframework.entityclasses.ChemicalStructure;<br />import org.springframework.stereotype.Repository;<br /><br />@Repository<br />public class ChemicalStructureDAO extends AbstractHibernateDAO {<br /><br /><%%KEEPWHITESPACE%%>    public ChemicalStructureDAO() {<br /><%%KEEPWHITESPACE%%>        super(ChemicalStructure.class);<br /><%%KEEPWHITESPACE%%>    }<br />}<br />


<br />package org.bitbucket.kienerj.moleculedatabaseframework.dao;<br /><br />import org.bitbucket.kienerj.moleculedatabaseframework.entityclasses.ChemicalCompound;<br />import org.springframework.stereotype.Repository;<br /><br />@Repository<br />public class ChemicalCompoundDAO extends AbstractHibernateDAO{<br /><br /><%%KEEPWHITESPACE%%>    public ChemicalCompoundDAO() {<br /><%%KEEPWHITESPACE%%>        super(ChemicalCompound.class);<br /><%%KEEPWHITESPACE%%>    }<br />}<br />

The Spring configuration file

I had the most trouble with this. Keep in mind that this highly depends on what dependencies you plan on using, eg. witch database, connection pool or not and so forth. The configuration I use is for PostgreSQL using BoneCP connection pool. The configuration for BoneCP was taken from the BoneCP web page. The spring configuration file is under src/main/resources/ApplicationContext.xml. See the comments within the file.

<br />&lt;?xml version="1.0" encoding="UTF-8"?&gt;<br />&lt;beans xmlns=""<br /><%%KEEPWHITESPACE%%>       xmlns:xsi=""<br /><%%KEEPWHITESPACE%%>       xmlns:aop=""<br /><%%KEEPWHITESPACE%%>       xmlns:context=""<br /><%%KEEPWHITESPACE%%>       xmlns:tx=""<br /><br /><%%KEEPWHITESPACE%%>       xsi:schemaLocation="<br /><%%KEEPWHITESPACE%%><br /><%%KEEPWHITESPACE%%><br /><%%KEEPWHITESPACE%%><br />"&gt;<br /><br /><%%KEEPWHITESPACE%%>    &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" autowire="autodetect"&gt;<br /><%%KEEPWHITESPACE%%>        &lt;property name="dataSource" ref="dataSource" /&gt;<br /><%%KEEPWHITESPACE%%>        &lt;!-- Don't forget to list all your entity classes here --&gt;<br /><%%KEEPWHITESPACE%%>        &lt;property name="annotatedClasses"&gt;<br /><%%KEEPWHITESPACE%%>            &lt;list&gt;<br /><%%KEEPWHITESPACE%%>                &lt;value&gt;org.bitbucket.kienerj.moleculedatabaseframework.entityclasses.ChemicalStructure&lt;/value&gt;<br /><%%KEEPWHITESPACE%%>                &lt;value&gt;org.bitbucket.kienerj.moleculedatabaseframework.entityclasses.ChemicalCompound&lt;/value&gt;<br /><%%KEEPWHITESPACE%%>                &lt;value&gt;org.bitbucket.kienerj.moleculedatabaseframework.entityclasses.ChemicalCompoundComposition&lt;/value&gt;<br /><%%KEEPWHITESPACE%%>            &lt;/list&gt;<br /><%%KEEPWHITESPACE%%>        &lt;/property&gt;<br /><br /><%%KEEPWHITESPACE%%>        &lt;property name="hibernateProperties"&gt;<br /><%%KEEPWHITESPACE%%>            &lt;props&gt;<br /><%%KEEPWHITESPACE%%>                &lt;prop key="hibernate.dialect"&gt;org.hibernate.dialect.PostgreSQLDialect&lt;/prop&gt;<br /><%%KEEPWHITESPACE%%>                &lt;prop key="hibernate.show_sql"&gt;true&lt;/prop&gt;<br /><%%KEEPWHITESPACE%%>                &lt;prop key=""&gt;create&lt;/prop&gt;<br /><%%KEEPWHITESPACE%%>            &lt;/props&gt;<br /><%%KEEPWHITESPACE%%>        &lt;/property&gt;<br /><%%KEEPWHITESPACE%%>    &lt;/bean&gt;<br /><br /><%%KEEPWHITESPACE%%>    &lt;!-- Spring bean configuration. Tell Spring to bounce off BoneCP --&gt;<br /><%%KEEPWHITESPACE%%>    &lt;bean id="dataSource"<br /><%%KEEPWHITESPACE%%>          class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy"&gt;<br /><%%KEEPWHITESPACE%%>        &lt;property name="targetDataSource"&gt;<br /><%%KEEPWHITESPACE%%>            &lt;ref local="mainDataSource" /&gt;<br /><%%KEEPWHITESPACE%%>        &lt;/property&gt;<br /><%%KEEPWHITESPACE%%>    &lt;/bean&gt;<br /><br /><%%KEEPWHITESPACE%%>    &lt;!-- BoneCP configuration --&gt;<br /><%%KEEPWHITESPACE%%>    &lt;bean id="mainDataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close"&gt;<br /><%%KEEPWHITESPACE%%>        &lt;property name="driverClass" value="org.postgresql.Driver" /&gt;<br /><%%KEEPWHITESPACE%%>        &lt;property name="jdbcUrl" value="jdbc:postgresql:MolDB" /&gt;<br /><%%KEEPWHITESPACE%%>        &lt;property name="username" value="postgres"/&gt;<br /><%%KEEPWHITESPACE%%>        &lt;property name="password" value="123456"/&gt;<br /><%%KEEPWHITESPACE%%>        &lt;property name="idleConnectionTestPeriod" value="60"/&gt;<br /><%%KEEPWHITESPACE%%>        &lt;property name="idleMaxAge" value="240"/&gt;<br /><%%KEEPWHITESPACE%%>        &lt;property name="maxConnectionsPerPartition" value="60"/&gt;<br /><%%KEEPWHITESPACE%%>        &lt;property name="minConnectionsPerPartition" value="20"/&gt;<br /><%%KEEPWHITESPACE%%>        &lt;property name="partitionCount" value="3"/&gt;<br /><%%KEEPWHITESPACE%%>        &lt;property name="acquireIncrement" value="10"/&gt;<br /><%%KEEPWHITESPACE%%>        &lt;property name="statementsCacheSize" value="50"/&gt;<br /><%%KEEPWHITESPACE%%>        &lt;property name="releaseHelperThreads" value="3"/&gt;<br /><%%KEEPWHITESPACE%%>    &lt;/bean&gt;<br /><br /><%%KEEPWHITESPACE%%>    &lt;bean id="txManager"<br /><%%KEEPWHITESPACE%%>          class="org.springframework.orm.hibernate4.HibernateTransactionManager"&gt;<br /><%%KEEPWHITESPACE%%>        &lt;property name="sessionFactory" ref="sessionFactory" /&gt;<br /><%%KEEPWHITESPACE%%>    &lt;/bean&gt;<br /><%%KEEPWHITESPACE%%>    &lt;tx:annotation-driven transaction-manager="txManager" /&gt;<br /><br /><%%KEEPWHITESPACE%%>    &lt;context:annotation-config /&gt;<br /><br /><%%KEEPWHITESPACE%%>    &lt;!-- Note the usage of abstract="true" and parent="AbstractHibernateDAO" in the implementations--&gt;<br /><%%KEEPWHITESPACE%%>    &lt;bean id="AbstractHibernateDAO" abstract="true"<br /><%%KEEPWHITESPACE%%>          class="org.bitbucket.kienerj.moleculedatabaseframework.dao.AbstractHibernateDAO"/&gt;<br /><br /><%%KEEPWHITESPACE%%>    &lt;bean id="ChemicalStructureDAO" parent="AbstractHibernateDAO"<br /><%%KEEPWHITESPACE%%>          class="org.bitbucket.kienerj.moleculedatabaseframework.dao.ChemicalStructureDAO"/&gt;<br /><%%KEEPWHITESPACE%%>    &lt;bean id="ChemicalCompoundDAO" parent="AbstractHibernateDAO"<br /><%%KEEPWHITESPACE%%>          class="org.bitbucket.kienerj.moleculedatabaseframework.dao.ChemicalCompoundDAO"/&gt;<br />&lt;/beans&gt;<br />

More Configuration: Maven pom.xml

<br />&lt;project xmlns="" xmlns:xsi=""<br /><%%KEEPWHITESPACE%%>  xsi:schemaLocation=""&gt;<br /><%%KEEPWHITESPACE%%>    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;<br /><br /><%%KEEPWHITESPACE%%>    &lt;groupId&gt;org.bitbucket.kienerj&lt;/groupId&gt;<br /><%%KEEPWHITESPACE%%>    &lt;artifactId&gt;MoleculeDatabaseFramework&lt;/artifactId&gt;<br /><%%KEEPWHITESPACE%%>    &lt;version&gt;0.1-SNAPSHOT&lt;/version&gt;<br /><%%KEEPWHITESPACE%%>    &lt;packaging&gt;jar&lt;/packaging&gt;<br /><br /><%%KEEPWHITESPACE%%>    &lt;name&gt;MoleculeDatabaseFramework&lt;/name&gt;<br /><%%KEEPWHITESPACE%%>    &lt;url&gt;;/url&gt;<br /><%%KEEPWHITESPACE%%>    &lt;build&gt;<br /><%%KEEPWHITESPACE%%>        &lt;plugins&gt;<br /><%%KEEPWHITESPACE%%>            &lt;plugin&gt;<br /><%%KEEPWHITESPACE%%>                &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br /><%%KEEPWHITESPACE%%>                &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;<br /><%%KEEPWHITESPACE%%>                &lt;version&gt;2.3.2&lt;/version&gt;<br /><%%KEEPWHITESPACE%%>                &lt;configuration&gt;<br /><%%KEEPWHITESPACE%%>                    &lt;source&gt;1.7&lt;/source&gt;<br /><%%KEEPWHITESPACE%%>                    &lt;target&gt;1.7&lt;/target&gt;<br /><%%KEEPWHITESPACE%%>                    &lt;showDeprecation&gt;true&lt;/showDeprecation&gt;<br /><%%KEEPWHITESPACE%%>                &lt;/configuration&gt;<br /><%%KEEPWHITESPACE%%>            &lt;/plugin&gt;<br /><%%KEEPWHITESPACE%%>        &lt;/plugins&gt;<br /><%%KEEPWHITESPACE%%>    &lt;/build&gt;<br /><%%KEEPWHITESPACE%%>    &lt;properties&gt;<br /><%%KEEPWHITESPACE%%>        &lt;;UTF-8&lt;/;<br /><%%KEEPWHITESPACE%%>    &lt;/properties&gt;<br /><br /><%%KEEPWHITESPACE%%>    &lt;dependencies&gt;<br /><%%KEEPWHITESPACE%%>        &lt;dependency&gt;<br /><%%KEEPWHITESPACE%%>            &lt;groupId&gt;junit&lt;/groupId&gt;<br /><%%KEEPWHITESPACE%%>            &lt;artifactId&gt;junit&lt;/artifactId&gt;<br /><%%KEEPWHITESPACE%%>            &lt;version&gt;3.8.1&lt;/version&gt;<br /><%%KEEPWHITESPACE%%>            &lt;scope&gt;test&lt;/scope&gt;<br /><%%KEEPWHITESPACE%%>        &lt;/dependency&gt;<br /><%%KEEPWHITESPACE%%>        &lt;dependency&gt;<br /><%%KEEPWHITESPACE%%>            &lt;groupId&gt;org.springframework&lt;/groupId&gt;<br /><%%KEEPWHITESPACE%%>            &lt;artifactId&gt;spring-orm&lt;/artifactId&gt;<br /><%%KEEPWHITESPACE%%>            &lt;version&gt;3.1.2.RELEASE&lt;/version&gt;<br /><%%KEEPWHITESPACE%%>        &lt;/dependency&gt;<br /><%%KEEPWHITESPACE%%>        &lt;dependency&gt;<br /><%%KEEPWHITESPACE%%>            &lt;groupId&gt;org.hibernate&lt;/groupId&gt;<br /><%%KEEPWHITESPACE%%>            &lt;artifactId&gt;hibernate-entitymanager&lt;/artifactId&gt;<br /><%%KEEPWHITESPACE%%>            &lt;version&gt;4.1.7.Final&lt;/version&gt;<br /><%%KEEPWHITESPACE%%>        &lt;/dependency&gt;<br /><%%KEEPWHITESPACE%%>        &lt;dependency&gt;<br /><%%KEEPWHITESPACE%%>            &lt;groupId&gt;com.jolbox&lt;/groupId&gt;<br /><%%KEEPWHITESPACE%%>            &lt;artifactId&gt;bonecp-provider&lt;/artifactId&gt;<br /><%%KEEPWHITESPACE%%>            &lt;version&gt;0.8.0-alpha1&lt;/version&gt;<br /><%%KEEPWHITESPACE%%>        &lt;/dependency&gt;<br /><%%KEEPWHITESPACE%%>        &lt;dependency&gt;<br /><%%KEEPWHITESPACE%%>            &lt;groupId&gt;postgresql&lt;/groupId&gt;<br /><%%KEEPWHITESPACE%%>            &lt;artifactId&gt;postgresql&lt;/artifactId&gt;<br /><%%KEEPWHITESPACE%%>            &lt;version&gt;9.1-901.jdbc4&lt;/version&gt;<br /><%%KEEPWHITESPACE%%>        &lt;/dependency&gt;<br /><%%KEEPWHITESPACE%%>        &lt;dependency&gt;<br /><%%KEEPWHITESPACE%%>            &lt;groupId&gt;cglib&lt;/groupId&gt;<br /><%%KEEPWHITESPACE%%>            &lt;artifactId&gt;cglib&lt;/artifactId&gt;<br /><%%KEEPWHITESPACE%%>            &lt;version&gt;2.2.2&lt;/version&gt;<br /><%%KEEPWHITESPACE%%>        &lt;/dependency&gt;<br /><%%KEEPWHITESPACE%%>    &lt;/dependencies&gt;<br />&lt;/project&gt;<br />

You need BoneCP-0.8.0-alpha1 for Hibernate 4! The release version does not work. This was also one of the many issues i had to figure out (thanks google). Maybe other connection pools have similar issues.

How to use

<br />package org.bitbucket.kienerj.moleculedatabaseframework;<br /><br />import org.bitbucket.kienerj.moleculedatabaseframework.dao.ChemicalCompoundDAO;<br />import org.bitbucket.kienerj.moleculedatabaseframework.dao.ChemicalStructureDAO;<br />import org.bitbucket.kienerj.moleculedatabaseframework.entityclasses.ChemicalCompound;<br />import org.bitbucket.kienerj.moleculedatabaseframework.entityclasses.ChemicalCompoundComposition;<br />import org.bitbucket.kienerj.moleculedatabaseframework.entityclasses.ChemicalStructure;<br />import org.springframework.context.ApplicationContext;<br />import;<br /><br />public class App<br />{<br /><%%KEEPWHITESPACE%%>    public static void main( String[] args )<br /><%%KEEPWHITESPACE%%>    {<br /><br /><%%KEEPWHITESPACE%%>        // Yes,  I should now and then actually read manuals and documentations (=boring) but then<br /><%%KEEPWHITESPACE%%>        // I only have so much time and examples help me so much more<br /><%%KEEPWHITESPACE%%>        // THIS IS THE IMPORTANT LINE I DID NOT SEE IN ANY TUTORIAL<br /><%%KEEPWHITESPACE%%>        ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");<br /><br /><%%KEEPWHITESPACE%%>        // You need to create the DAOs from Spring Context else the "Spring magic" will not be available<br /><%%KEEPWHITESPACE%%>        ChemicalStructureDAO structureDAO = (ChemicalStructureDAO) context.getBean("ChemicalStructureDAO");<br /><%%KEEPWHITESPACE%%>        ChemicalCompoundDAO compoundDAO = (ChemicalCompoundDAO) context.getBean("ChemicalCompoundDAO");<br /><br /><%%KEEPWHITESPACE%%>        // From here on it is pretty straight forward.<br /><%%KEEPWHITESPACE%%>        // For me there are a bit too many lines to make it look nice but it works...<br /><%%KEEPWHITESPACE%%>        ChemicalStructure structure1 = new ChemicalStructure();<br /><%%KEEPWHITESPACE%%>        structure1.setStructureKey("c1ccccc1");<br /><%%KEEPWHITESPACE%%>        structure1.setStructureData("c1ccccc1");<br /><br /><%%KEEPWHITESPACE%%>        ChemicalStructure structure2 = new ChemicalStructure();<br /><%%KEEPWHITESPACE%%>        structure2.setStructureKey("CC=O");<br /><%%KEEPWHITESPACE%%>        structure2.setStructureData("CC=O");<br /><br /><%%KEEPWHITESPACE%%>        structureDAO.create(structure1);<br /><%%KEEPWHITESPACE%%>        structureDAO.create(structure2);<br /><br /><%%KEEPWHITESPACE%%>        ChemicalCompound compound = new ChemicalCompound();<br /><%%KEEPWHITESPACE%%>        compound.setCompoundName("Test Compound");<br /><br /><%%KEEPWHITESPACE%%>        ChemicalCompoundComposition composition1 = new ChemicalCompoundComposition();<br /><%%KEEPWHITESPACE%%>        composition1.setCompound(compound);<br /><%%KEEPWHITESPACE%%>        composition1.setChemicalStructure(structure1);<br /><%%KEEPWHITESPACE%%>        composition1.setPercentage(70.0);<br /><br /><%%KEEPWHITESPACE%%>        ChemicalCompoundComposition composition2 = new ChemicalCompoundComposition();<br /><%%KEEPWHITESPACE%%>        composition2.setCompound(compound);<br /><%%KEEPWHITESPACE%%>        composition2.setChemicalStructure(structure2);<br /><%%KEEPWHITESPACE%%>        composition2.setPercentage(30.0);<br /><br /><%%KEEPWHITESPACE%%>        compound.getComposition().add(composition1);<br /><%%KEEPWHITESPACE%%>        compound.getComposition().add(composition2);<br /><br /><%%KEEPWHITESPACE%%>        compoundDAO.create(compound);<br /><%%KEEPWHITESPACE%%>    }<br />}<br />

After running above snippet the database looks like this:


I hope this article can help some people to do their first steps with Spring and Hibernate. After all it is not hard if you know how it works..if…


You will need to watch out for LazyInitializationException. With above code of you call compound.getComposition().get(0).getChemicalStructure() (eg. get the first ChemicalStructure linked to this compound) outside of the DAO, meaning Hibernate Session is closed, you will get a LazyInitializationException. This happens because the data for the ChemicalStructure was not loaded (FetchType.LAZY) when loading the compound. To avoid this you will need to explicitly load the data within the DAO (Hibernate Session). Example

<br /><%%KEEPWHITESPACE%%>    public ChemicalCompound getById(Long id) {<br /><br /><%%KEEPWHITESPACE%%>        ChemicalCompound compound = compoundDAO.getById(id);<br /><%%KEEPWHITESPACE%%>        for (ChemicalCompoundComposition composition : compound.getComposition()) {<br /><%%KEEPWHITESPACE%%>            composition.getChemicalStructure().getId();<br /><%%KEEPWHITESPACE%%>        }<br /><%%KEEPWHITESPACE%%>        return compound;<br /><%%KEEPWHITESPACE%%>    }<br />

UPDATE Sep 2013

Above example of a many-to-many relationship with an additional column, namely ChemicalCompoundComposition can be achieved much easier and this easier solution is also more flexible especially in terms up updating. The solution is actually pretty obvious. No idea why I did not see it back then. Rookie mistake. Below the new code, with JPA 2.0 annotations and using project lombok annotations for auto generation of getters, setters and equals() and hashCode() methods.

<br />@Entity<br />@Table(name = "compound_composition", uniqueConstraints=<br /><%%KEEPWHITESPACE%%>        @UniqueConstraint(columnNames = {"chem_compound_id", "chemical_structure_id"}))<br />@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id")<br />@Data<br />@EqualsAndHashCode(callSuper = false, of = {"compound", "chemicalStructure"})<br />public class ChemicalCompoundComposition extends BaseEntity {<br /><br /><%%KEEPWHITESPACE%%>    @Id<br /><%%KEEPWHITESPACE%%>    @GeneratedValue(strategy = GenerationType.AUTO,<br /><%%KEEPWHITESPACE%%>            generator = "composition_seq_gen")<br /><%%KEEPWHITESPACE%%>    @SequenceGenerator(name = "composition_seq_gen",<br /><%%KEEPWHITESPACE%%>            sequenceName = "seq_compound_composition", allocationSize = 1000)<br /><%%KEEPWHITESPACE%%>    @Column(name = "composition_id")<br /><%%KEEPWHITESPACE%%>    private Long id;<br /><br /><%%KEEPWHITESPACE%%>    @Column(name = "percentage")<br /><%%KEEPWHITESPACE%%>    private Double percentage;<br /><br /><%%KEEPWHITESPACE%%>    @JoinColumn(name = "chem_compound_id", nullable = false)<br /><%%KEEPWHITESPACE%%>    @ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})<br /><%%KEEPWHITESPACE%%>    private ChemicalCompound compound;<br /><%%KEEPWHITESPACE%%>    @JoinColumn(name = "chemical_structure_id", nullable = false)<br /><%%KEEPWHITESPACE%%>    @ManyToOne(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})<br /><%%KEEPWHITESPACE%%>    private ChemicalStructure chemicalStructure;<br /><br /><%%KEEPWHITESPACE%%>    /**<br /><%%KEEPWHITESPACE%%>     * For JPA Provider<br /><%%KEEPWHITESPACE%%>     */<br /><%%KEEPWHITESPACE%%>    public ChemicalCompoundComposition() {<br /><%%KEEPWHITESPACE%%>    }<br /><br /><%%KEEPWHITESPACE%%>    public ChemicalCompoundComposition(ChemicalCompound compound,<br /><%%KEEPWHITESPACE%%>            ChemicalStructure structure,<br /><%%KEEPWHITESPACE%%>            Double percentage) {<br /><br /><%%KEEPWHITESPACE%%>        this.percentage = percentage;<br /><%%KEEPWHITESPACE%%>        this.chemicalStructure = structure;<br /><%%KEEPWHITESPACE%%>        this.compound = compound;<br /><%%KEEPWHITESPACE%%>    }<br />}<br />

Written by kienerj

October 5, 2012 at 16:38

Posted in Database, Java, Programming

Tagged with , ,