RSS RSS feed | Atom Atom feed

Spring and Hibernate, Simplify the DAO layer

Spring and Hibernate Simplify the DAO layer

When developing web applications, many people create their data access layer using two basic design patterns(design pattern meaning an informal description, not to be confused with the gang of four). The first is to put the responsibility on the DAO class of acquiring the data source. Approaches may vary from coding this in a super class to externalizing it in a specialized delegate class. The bottom line is that the DAO cannot provide value to your app without obtaining a data source directly(e.g. JNDI) or via a delegate class. One of the major limiting factors here is that your DAO classes are not easily testable outside of the container. An arguable better implementation would be to parameterize the data source. This allows the unit test to acquire the data source independent of the DAO class and pass it in upon execution. This has an upside for the DAO class since it can focus on it's primary responsibility of providing data. This also makes the DAO class testable outside the container since the unit test would pass it in. It's a win, win situation right? Well not exactly! The downside is that now client modules, unit tests in this case, need to know how to obtain a data source. This is a grave injustice placed on the client code developers. After all, part of the reason that we have the DAO layer is to simplify data access. Pick your poison: Testable and inflexible or flexible but difficult to test.

To make things worse, what if you want to swap out your JDBC DAO classes for ones that use a persistence framework like Hibernate. Hibernate catches my eye because I immensely dislike writing gobs of SQL. For a Java programmer, Hibernate offers a much more natural way of persisting objects. Instead of writing JDBC code, hibernate allows me to deal with POJO's and persist them for me. The bulk of my work lies in maintaing OR Mapping files. With hibernate, developers working outside the data access layer will not know which classes are persisted and which are not since the POJO's do not extend or implement anything. So lets use hibernate in our application them. Unfortunately for us, our make believe application has DataSource's floating around in method signatures. Since hibernate uses a SessionFactory object instead of a data source, mass code changes will need to be made to make the transition. Obviously Hibernate knows about data sources under the covers but client code is not aware of that. For those of you thinking of a "find and replace" engineering solution, I hope I never get the opportunity to work with you :) The find and replace approach is similar to loosening a rusty bolt with a pair of pliers. It might work once, maybe twice, but over time your bolt's integrity will be compromised and in need of a replacement. The same is true for your code. It will start to deteriorate over time. I've seen this over and over and over again! Heck I may have even participated in this kind of macro programming in years past. What are the options now?

So far I have preached that working with Hibernate is easier and more enjoyable than working with JDBC directly. This is a personal opinion but one that I know many developers share. An even better approach is to use the Spring Framework with Hibernate. Bringing Spring into the mix will allow you to reduce the amount of plumbing code required for hibernate by a factor of 50% or more. In Spring Live, Matt Raible claims that this code reduction is in the neighborhood of 75%. I tend to agree with Matt and I have created a sample application to make my case. My application contains two unit tests(one DAO using just hibernate and the other using spring and hibernate) that create a 3 field record in a MySQL database(loosely based on the myusers app from spring live).

First both DAO classes implement the MyRecordDAO interface.

package com.shoesobjects;

import java.io.Serializable;

public class MyRecord implements Serializable {    
    private Long id = null;
    private String firstName = null;
    private String lastName = null;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

 

Here is the data access object using just hibernate. Not to bad but lots of cookie cutter try/catch blocks and redundant opening/closing of sessions. Notice it is 114 lines of code and would be even larger if I handled exceptions properly like any good programmer would.

package com.shoesobjects.dao;

import com.shoesobjects.MyRecord;
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.Configuration;

import java.util.List;

public class MyRecordDAOHibernate implements MyRecordDAO {
    private static SessionFactory sessionFactory = null;

    public MyRecordDAOHibernate() {
        Configuration cfg = null;
        try {
            cfg = new Configuration().addClass(MyRecord.class);
        } catch (MappingException e) {
            e.printStackTrace();
        }

        try {
            sessionFactory = cfg.buildSessionFactory();
        } catch (HibernateException e) {
            e.printStackTrace();
        }
    }

    private Session getSession() {
        Session session = null;
        try {
            session = sessionFactory.openSession();
        } catch (HibernateException e) {
            e.printStackTrace();
        }
        return session;
    }

    public MyRecord getRecord(Long id) {
        Session session = this.getSession();
        MyRecord record = null;
        try {
            record = (MyRecord) session.load(MyRecord.class, id);
        } catch (HibernateException e) {
            e.printStackTrace();
        } finally {
            if (session != null) {
                try {
                    session.close();
                } catch (HibernateException e) {
                    e.printStackTrace();
                }
            }
        }

        return record;
    }

    public List getRecords() {
        Session session = this.getSession();
        List list = null;
        try {
            Query query = session.createQuery("select myrecord from com.shoesobjects.MyRecord");
            list = query.list();
        } catch (HibernateException e) {
            e.printStackTrace();
        } finally {
            if (session != null) {
                try {
                    session.close();
                } catch (HibernateException e) {
                    e.printStackTrace();
                }
            }
        }

        return list;
    }

    public void saveRecord(MyRecord record) {
        Session session = this.getSession();
        try {
            session.saveOrUpdate(record);
            session.flush();
        } catch (HibernateException e) {
            e.printStackTrace();
        } finally {
            if (session != null) {
                try {
                    session.close();
                } catch (HibernateException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void removeRecord(Long id) {
        Session session = this.getSession();
        try {
            MyRecord record = (MyRecord) session.load(MyRecord.class, id);
            session.delete(record);
            session.flush();
        } catch (HibernateException e) {
            e.printStackTrace();
        } finally {
            if (session != null) {
                try {
                    session.close();
                } catch (HibernateException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

Hibernate uses a properties file or xml file for it's configuration information(datasource url, username, password, database dialect, etc). For simplicity, I'm listing only the necessary information.

#hibernate.properties
#only used for MyRecordDAOHibernateTest
hibernate.connection.url = jdbc:hsqldb:mem:test
hibernate.connection.username = sa
hibernate.connection.password =
hibernate.dialect = net.sf.hibernate.dialect.HSQLDialect
hibernate.connection.driver_class = org.hsqldb.jdbcDriver
hibernate.hbm2ddl.auto=create

 

The unit test to exercise this DAO class is listed below. It is a pretty straight forward JUnit test. The only thing that might look out of the ordinary is that we are instantiating the MyRecordDAOHibernate() class directly. In practice, it would be beneficial to hide this behind a Factory. Then you could more easily allow for alternate implementations.

package com.shoesobjects;

import com.shoesobjects.dao.MyRecordDAO;
import com.shoesobjects.dao.MyRecordDAOHibernate;
import junit.framework.Assert;
import junit.framework.TestCase;

public class MyRecordDAOHibernateTest extends TestCase {
        private MyRecord record = null;
        private MyRecordDAO dao = null;

    protected void setUp() throws Exception {
        super.setUp();
        dao = new MyRecordDAOHibernate();
    }

    protected void tearDown() throws Exception {
        super.tearDown();
        dao = null;
    }

    public void testSaveRecord() throws Exception {
        record = new MyRecord();
        record.setFirstName("Gavin");
        record.setLastName("King");
        dao.saveRecord(record);
        Assert.assertNotNull("primary key assigned", record.getId());
    }
}

 

The version using Hibernate and Spring has a much cleaner implementation thanks to Springs. Notice this version doesn't have to deal with creating the SessionFactory or dealing with opening/closing sessions. The Spring Framework takes care of this under the covers for you. All you have to do is add the SessionFactory as a needed dependency in Spring's applicationContext.xml file. Notice this class is only 26 lines of code. Look at how clear and concise this version is.

package com.shoesobjects.dao;

import com.shoesobjects.MyRecord;
import org.springframework.orm.hibernate.support.HibernateDaoSupport;

import java.util.List;

public class MyRecordDAOHibernateWithSpring extends HibernateDaoSupport implements MyRecordDAO {

    public MyRecord getRecord(Long id) {
        return (MyRecord) getHibernateTemplate().get(MyRecord.class, id);
    }

    public List getRecords() {
        return getHibernateTemplate().find("from MyRecord");
    }

    public void saveRecord(MyRecord record) {
        getHibernateTemplate().saveOrUpdate(record);
    }

    public void removeRecord(Long id) {
        Object record = getHibernateTemplate().load(MyRecord.class, id);
        getHibernateTemplate().delete(record);
    }
}

 

The applicationContext.xml file contains all the information for Spring's Bean Factory to instantiate the necessary class es and wire the dependencies. Notice the bean with an id of myRecordDAO, it has a reference to the bean sessionFactory which is also defined in this config file.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName"><value>org.hsqldb.jdbcDriver</value></property>
        <property name="url"><value>jdbc:hsqldb:mem:test</value></property>
        <property name="username"><value>sa</value></property>
        <property name="password"><value></value></property>
    </bean>

    <!-- Hibernate SessionFactory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
        <property name="dataSource"><ref local="dataSource"/></property>
        <property name="mappingResources">
            <list>
                <value>MyRecord.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">net.sf.hibernate.dialect.HSQLDialect</prop>
            <prop key="hibernate.hbm2ddl.auto">create</prop>
        </props>
        </property>
    </bean>

    <!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager">
        <property name="sessionFactory"><ref local="sessionFactory"/></property>
    </bean>

    <bean id="myRecordDAO" class="com.shoesobjects.dao.MyRecordDAOHibernateWithSpring">
        <property name="sessionFactory"><ref local="sessionFactory"/></property>
    </bean>
</beans>

 

Here is the JUnit test for Hibernate+Spring implementation of the data access object. Notice it is just as straight forward as the last unit test but has one noticeable advantage. Look at line 22 where we instantiate the data access object. No concrete implementation is listed, only the interface. The concrete class is instantiated by Spring's BeanFactory behind the scenes allowing us to swap out the implementation by editing the applicationContext.xml descriptor. This flexibility allows our unit test to easily be modified to use a mock implementation without using command line parameters to the JVC or making code changes.

package com.shoesobjects;

import com.shoesobjects.dao.MyRecordDAO;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyRecordDAOHibernateWithSpringTest extends TestCase {
    private ApplicationContext ctx = null;
    private MyRecord record = null;
    private MyRecordDAO dao = null;

    public MyRecordDAOHibernateWithSpringTest() {
        // Should put in a parent class that extends TestCase
        String[] paths = {"applicationContext.xml"};
        ctx = new ClassPathXmlApplicationContext(paths);
    }

    protected void setUp() throws Exception {
        super.setUp();
        dao = (MyRecordDAO) ctx.getBean("myRecordDAO");
    }

    protected void tearDown() throws Exception {
        super.tearDown();
        dao = null;
    }

    public void testSaveRecord() throws Exception {
        record = new MyRecord();
        record.setFirstName("Rod");
        record.setLastName("Johnson");
        dao.saveRecord(record);
        Assert.assertNotNull("primary key assigned", record.getId());
    }

}

 

In order to run this example, the following steps are required.
1) Install MySQL, login as root
2) Create a database called myrecord
   create database myrecord;
3) Create a database user called myrecord with a password of myrecord.
   grant all privileges on myrecord.* to myrecord@localhost identified by 'myrecord' with grant option;
4) Run the unit test's. The database table will be created upon running the test due to the following line in applicationContext.xml
    <prop key="hibernate.hbm2ddl.auto">update</prop>
3) Run the unit tests

IntelliJ IDEA project files are included in the archive. Also, all required jar files are in the lib directory so you will not have to download anything else.

Download the sample app here.

 

Note: There is now a version of the code that uses maven2 to build, package, and run tests.  Get it here

 

Tags :


Re: Spring and Hibernate, Simplify the DAO layer

Try OJB. It will reduce the size of your DAO's even more!

DAO Fusion

Hi, we have released an OpenSource project that goes far beyond a generic CRUD-like DAO.

You can find it here: http://opensource.anasoft.com/daofusion-site/ or http://opensource.anasoft.sk/daofusion-site/

DAO Fusion is a lightweight yet comprehensive tool for building reliable, maintainable and testable DAO layers using JPA / Hibernate.

It covers five main areas related to DAO layer development:

- persistent entity model
- standard persistent entity DAO interfaces / abstract implementations
- persistent entity criteria API with advanced filtering, sorting and paging capabilities
- criteria transfer object (CTO) pattern that allows clients to specify entity criteria easily (this is especially useful for grid-like operations)
- integration test support using JUnit / Spring TestContext framework (core DAO functionality is integration-tested out-of-the-box for many popular databases)

The project is open to everyone interested in JPA, Hibernate and related technologies.

Cheers,
Vojtech

Re: Try OJB

Why's that? Any interest in getting more specific than that?

Re: Spring and Hibernate, Simplify the DAO layer

Using Hibernate and Generics in Java 1.5, Eric Burke has greatly simplified his DAO code also.. Eric's Blog: Hibernate and Java 5 http://www.ericburke.com/blog/2004/11/hibernate-and-java-5.html

Re: Spring and Hibernate, Simplify the DAO layer

Interesting, but I'm willing to bet that it could be even better if Eric incorporated Spring into his utility. Not to mention I see a bit of transaction logic that would not be necessary if he used spring. I'm interested in seeing a completed code sample. Do you know if one is available?

Re: Spring and Hibernate, Simplify the DAO layer

I have intentionally avoided Spring so far. I'm trying to learn as much about Hibernate as possible before Dec 10, when I give an OCI Java Lunch meeting. I hope to have cleaned things up by then and will post more complete code examples.

Will I ever migrate to Spring? Perhaps, but I'm not too worried about it. I have a single DAO base class that creates the transaction. I haven't had any trouble with the unit tests. Supposing I did use Spring, the change would be localized to a few lines of code in the base class.

In all honesty, I don't "get it" with regards to the tradeoff I'd have to make. Spring looks like it requires an awful lot of JAR files and would introduce more configuration headaches for me. All that for a few lines of transaction code in my base class? I'm extremely skeptical.

Re: Spring and Hibernate, Simplify the DAO layer

If you're working with Servlets, I think the servlet filter idea (see Eric's Blog: Hibernate Update - Nov 11) shows great promise.

I worry about fat base classes though. I hope your "few lines of code in the base class" involves a Spring-ignorant interface to a delegate.

Re: Spring and Hibernate, Simplify the DAO layer

Eric, Spring is an a la carte framework. You can pick and choose what you want. Also your comment "Spring looks like it requires an awful lot of JAR files", is not true. Spring at a minimum requires spring.jar which will fit on a floppy disk. This is the only spring jar that my project needs.

Do you have a sample binary that I can download to look at your approach? I'm curious how you deal with obtaining a SessionFactory.

Re: Spring and Hibernate, Simplify the DAO layer

Excellent example, and a great road map to do JUnit tests, I just would like to add the following comment I had some problems loading the applicationContext.xml, first of all because with the class path it looks under /web-inf/classes (obviously) but if you are developing web applications all your xml’s generally are under the /web-inf/ path, so I solve this by using FileSystemXmlApplicationContext… public CategoriaJUnit(){ // Should put in a parent class that extends TestCase String paths = "**/*-hibernate.xml"; ctx = new FileSystemXmlApplicationContext(paths); } that’s all folks

Re: Spring and Hibernate, Simplify the DAO layer

Hector, thanks for the info. I'll keep that in mind since I'm typically doing web apps.

Re: Spring and Hibernate, Simplify the DAO layer

Hi, if you know can you also please tell how to look for the applicationContext.xml if it is outside current JVM folder. e.g if i have one web proj with struts and Business object+applicationConfig.XML and another java proj (say prj name P) in same workspace with Entity and Entity and EntityManager and i write test cases for entity manager in proj P then how to load appContext.xml.

Re: Spring and Hibernate, Simplify the DAO layer

For the love of god, please don't use the word design patterns when it doesn't mean the same thing. It doesn't matter whether you explain that it's a different meaning, just don't do it. There's already enough misunderstanding that we don't need anymore.

Re: Spring and Hibernate, Simplify the DAO layer

Good example! This is small enough to grok quickly.

Re: Spring and Hibernate, Simplify the DAO layer

All the session opening/closing code and the try-catch blocks can be moved to a base class and all DAO implmentation classes can extend from that. This makes the dao classes as simple or simpler than the Hibernate+Spring implementation. Plus I dont have to learn a new framework and also save myself from complicating my application further. To Anonymous: Yes, this does involve a slightly fat base class but what exactly is the objection to that?

Ant build

Great article, but i wish you would have provided an example with an Ant Build. Most of us do not have IDEA, and it takes forever to even try out your example. To make your point, you should not tie yourself to an IDE, and just use the universal Ant Build.

Tools?

Any tools that can help with code/xml generation that work with the S+H combo?

Tools?

Hi jaag works well with S+H combo and various databases but it doesnt support composite keys and "is a" relationship

Re: Spring and Hibernate, Simplify the DAO layer

I typically just write the mapping files by hand. Same goes for the Spring config files. I've heard of a few plugin's but nothing earth shattering.

Re: Spring and Hibernate, Simplify the DAO layer

Yes, XDoclet works really well for generating those items

Re: Spring and Hibernate, Simplify the DAO layer

Its just a cool exmaple.

Re: Spring and Hibernate, Simplify the DAO layer

Using spring with hibernate is worth it. The people in the above posts are kind of missing the point (the article kind of misses it too). Yes, you could probably use a base class to do transactions and reduce code the same as spring. However, why would you want to write a base class that as already been written and standardized (and written better)? Using spring isn't merely about reducing code, it's about keeping your projected managable, scalable, flexible, and uncoupled. You can change settings in a custom made base class, which if given to someone else they wouldn't know what the hell you are doing. Or you can configure everything in a standardized xml file that everyone else will be able to understand. If you noticed the growing trend among all the new programming tools and technology, they all scream at you. Configuring XML > configuring source code. Once you learn spring, you'll understand.

Re: Spring and Hibernate, Simplify the DAO layer

I see the usual Java buzz words and concepts getting thrown around but is all this really groundbreakingly simpler and clearer? Despite Anonymous' arrogant assumption that the only people who do not appreciate Spring are people who don't know it, I do know a thing or two about Spring and I would have to say that for me, I would rather inherit from a clean, concise, fast base class than configure and rely on the usual set of JEE smoke and mirrors. I'm not afraid to write a little code and if it takes longer to learn and configure a framework (and relearn parts of it when I forget was I was thinking 6 months ago) then I really haven't made things simpler or more maintainable at all. In the case of using Spring with Hibernate, I feel like people are using Spring to do something that is already taken care of just because Spring is all the rage now. I think there is a time and place for a lot of the frameworks out there but the time and place is not "all the time" and "everywhere."

Re: Spring and Hibernate, Simplify the DAO layer

Please note this blog entry was written back in 2004 and it is now 2007. Lots of things have changed since it was originally created. With that being said, it is still obvious to me that inheritance is not the best solution. For instance you can no longer extend another class. Also, Spring facilitates unit testing with almost no pain.

Re: Spring and Hibernate, Simplify the DAO layer

I haven't had much of a need for a DAO to inherit from anything more than the base class but if I did, I would chalk that up to a shortcoming of Java itself, not necessarily a shortcoming of the DAO base design. I have run into that situation in other cases and can't seem to figure out why Sun thought that multiple inheritance would be so horribly confusing to programmers that its wasn't worth the value it adds. It funny to see how so many useful features from languages like C++ were not included in Java for the sake of making a clean, concise, easy to follow language... and now they are all coming back one at a time, like generics (templates in C++) and enumerations.

Re: Spring and Hibernate, Simplify the DAO layer

I'm not so sure I've ever run into a situation where I really needed to extend more than one class. First there is almost always a better approach using aggregation or composition. Secondly, most of what I do is business oriented so all the tricks usually involve how to acquire the data. OO topics such as the diamond problem are generally few and far between.

Re: Spring and Hibernate, Simplify the DAO layer

Very well said. 

Re: Spring and Hibernate, Simplify the DAO layer

that changed my mind

Re: Spring and Hibernate, Simplify the DAO layer

Maybe you should read the article again. I think it's pretty clear that separating concerns and keeping things uncoupled is a major advantage. Reducing plumbing code that provides no business value leads to a much more manageable solution as well. I do realize that this isn't the only way to keep a project manageable. As always, the quality of the comment has a direct correlation to the anonymity of the author.

Re: Spring and Hibernate, Simplify the DAO layer

I can sympathize.  95% of the programming I do now is simple business oriented webapp work - get data, persist it, retrieve data, display it, and so on.&amp;nbsp; There isn't always much need for multiple inheritance in situations like that but not needing something 95% of the time (or even 99.9% for that matter) is not justification for removing it 100%.&amp;nbsp; After all, it was your argument that inheriting from a base class was bad because it uses up Java's one and only shot at inheritance.&amp;nbsp; Besides, JEE apps aren't all there is to Java.&amp;nbsp; Uses for multiple inheritance are more abundant in other area.

But even without multiple inheritance, Sun still made some questionable decisions that they are just now correcting, like type safe enumerations.  Defining public static finals and passing ints gets the job done but not much else.

And Java's garbage collection that doesn't reclaim objects in a timely matter or predictable order?  Don't get me started.&amp;nbsp; If you have ever seen an error about your connection pool being used up, you should understand.&amp;nbsp; The finalize method of JDBC connections, statements, and so on actually close themselves when they are collected.&amp;nbsp; The only problem is that the garbage collector can't collect them when references go out of scope.&amp;nbsp; So if for example you have a loop that connects and does some work, there is a pretty decent change that if the &amp;quot;work&amp;quot; isn't too memory intensive or time consuming, you will open multiple connections before the previous connection is collected and closes itself.&amp;nbsp; Now, is opening the connection inside the loop a good idea?&amp;nbsp; Probably not.&amp;nbsp; And as good Java programmers, we all know to explicitly close our own connections but in a corporate - or should I say enterprise : ) - environment, bad programming is everywhere and the unreliability of finalize() makes it difficult to automate that in a reliable way.

Re: Spring and Hibernate, Simplify the DAO layer

Just a simple question: in the DAOHibernate implementation what is the difference between using getHibernateTemplate().find("from MyRecord"); and getSession().find("from MyRecord"); ? Note: this is possible only with Hibernate 2 (org.springframework.orm.hibernate.support.HibernateDaoSupport), no more with Hibernate 3 (org.springframework.orm.hibernate3.support.HibernateDaoSupport)

Re: Spring and Hibernate, Simplify the DAO layer

If you look at the java doc, getSession() is suppose to be called in plain Hibernate code, not Hibernate template code. Here is the snippet "Note that this is not meant to be invoked from HibernateTemplate code but rather just in plain Hibernate code"

thank you for example

It helped me to understand using Spring. But I also want to ask you about using your code in real program. For example your need use class MyRecordDAOHibernateWithSpringTest more than one times (at first time get something from db, than doing something with data in UI, at last - write to db). Need we make it static ?

Re: Spring and Hibernate, Simplify the DAO layer

hello, how to use spring and hibernate? what is the archtecture flow? pls give brief explnation.

Re: Spring and Hibernate, Simplify the DAO layer

Hi, I am getting error "java.lang.NoClassDefFoundError: net/sf/hibernate/HibernateException".i had all the jar files as given in lib folder. Can you help me out in this. Thanks in advance.

Re: Spring and Hibernate, Simplify the DAO layer

i had the same problem initially. ultimately (and i don't know if this is the cleanest solution) i had to have both hibernate3.jar and hibernate2.jar in my build classpath (i'm using ANT) to resolve that compile error.

Re: Spring and Hibernate, Simplify the DAO layer

I was always confused with hibernate mixed with spring. But after seeing this example its very clear now.It is a very good example one has to see to understand how both hibernate and spring work together.

Re: Spring and Hibernate, Simplify the DAO layer

The sample-code was pretty much useful to display the utility of hibernate-spring combination...Thanks

Re: Spring and Hibernate, Simplify the DAO layer

I would like to thank you for this blog entry - it has made clear what other articles (and even books) have been struggling with for some time

Re: Spring and Hibernate, Simplify the DAO layer

This one is th best code with explanation ever i saw...........

Re: Spring and Hibernate, Simplify the DAO layer

if you are doing this now (late 2006) then remember to replace all hibernate with hibernate3 in imports etc...apart from that this is a good place to start with Spring and Hibernate.

Re: Spring and Hibernate, Simplify the DAO layer

Very good explanation. Thanks!!!

Re: Spring and Hibernate, Simplify the DAO layer

Hi
Thanks for the nice article.
May i know what tool you have used for html coloring of the source code ? is that part of intelliJ ?
Thank you.
Balaji

Re: Spring and Hibernate, Simplify the DAO layer

Actually I copy/pasted the source from IDEA to JEdit and used the built in color coding. Worked like a champ.

Re: Spring and Hibernate, Simplify the DAO layer

Thanks Mike

Re: Spring and Hibernate, Simplify the DAO layer

i get the following exception, when i customized ur xml config file for my app!...what causes this problem? org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [spring-hibernate.xml]: Invocation of init method failed; nested exception is net.sf.hibernate.MappingException: invalid mapping Caused by: net.sf.hibernate.MappingException: invalid mapping

Re: Spring and Hibernate, Simplify the DAO layer

The article is useful as a quick start. Example with some related entities would be really useful.

Re: Spring and Hibernate, Simplify the DAO layer

I'm assuming you are not asking me to write the example you refer to. Instead, why don't you create it and I'd be happy to add a link to your post from this article. Then we both made "the net" a better place or at least a bit more informative.

Re: Spring and Hibernate, Simplify the DAO layer

Lots of tutorials are much alike. It's hard to get understood to who is not familiar with spring api when Spring itself do the 'wiring' job, delegating so much work for coders. This article is very helpful to me!

Re: Spring and Hibernate, Simplify the DAO layer

Excellent tutorial, thank you very much! (Perhaps an update to hibernate 3 and spring 2.0 are appropriate, but the logic is nicely explained.)

Re: Spring and Hibernate, Simplify the DAO layer

Very Nice tutor!!!

it helps me much.

Re: Spring and Hibernate, Simplify the DAO layer

Where do you specify applicationContext.xml file? (hopefully somewhere in web.xml). How to do it is missing.

Re: Spring and Hibernate, Simplify the DAO layer

Thanks for useful information.

Reducing complexity in specification

While the quantity of code is reduced, how much are we really simplifying the persistence problem? It seems to me we are moving complexity from one language of specification (Java) to another (an XML dialect). While the XML config is not unintelligible, many lines are certainly not obvious (e.g. to write from scratch).

I'm relatively new to persistence in Java (roots in Lisp). I've been looking for is a mechanism whereby I can declare which pojo's must be persisted, and let the framework do the rest. I might even want more than one persistence strategy: e.g. O-R, flat-file, binary or XML serialised formats, etc. I should be able to point the persistence tool at my java code, which would use a declaration file (may be XML, but without obscure jargon) to generate the Java DAO's, supporting classes, DDL scripts, maybe even the ORM's, and so on, that are needed build-time. The rest is managed run-time by the libraries. [A bit like JAXB binding classes, or Xstream, but in a different problem domain.]

When I look at the methods of both of the MyRecord examples, they look as though they could be generated rather than written, so why aren't they? After all, the common requirement in persisting objects is basic CRUDS (i.e. plus Search) support. And I hate spending time on brainless code that could be automated. And if generation can be automated, do I really care how many lines there are?

So, please forgive my naivete, but.... am I asking too much? Are we still aways from the sophistication I'm looking for in a publically available framework? Or does Spring + Hibernate (+ ???) do what I want, and I just don't quite get it?

Re: Spring and Hibernate, Simplify the DAO layer

Very nicely explained!!!

It really helped me to understand the concepts.

Re: Spring and Hibernate, Simplify the DAO layer

Awesome tutorial to start with.Perfectly explained.

Re: Spring and Hibernate, Simplify the DAO layer

Fantastic thank you. Find the files you are looking for at best-soft-archive.com the most comprehensive source for free-to-try files downloads on the Web

Re: Spring and Hibernate, Simplify the DAO layer

I've been looking at Struts2, Hibernate3 for about a week now, and now I've looking at putting Spring into it as well and I have to say, I'm not in the slightest bit impressed"! This is so over the top compared to JSP/Servlets with EJB3.1 I can't believe it.
I've got knowhere, it's taken all this time and I could have done more in about 1 hour with EJB3.1 and Servlets than I've managed with this, so much setting up and config and stuff just to get a simple test working!

Why does/would anyone use this method of development?

Re: Spring and Hibernate, Simplify the DAO layer

You've given it a week? Come on, man.  You need that much just for Struts. I agree that HIbernate and Spring have been over hyped. Be patient with setting up the configurations and&amp;nbsp;it will pay off big. At a minimum&amp;nbsp;you should be using Struts or you end up creating you're own controller (nightmare). Hibernate grew out of frustration with whole bloaty EJB world.&amp;nbsp;

Turn to the source. The open-source, that is.

Re: Spring and Hibernate, Simplify the DAO layer

Hello friends i am new to this springs technology and i downloaded the above given example, after building project  my classes folder with all the classes are coming but in all the class files it is showing as souce not found.

I am using Eclipse IDI, please help me to configure java build path in project properties

Re: Spring and Hibernate, Simplify the DAO layer

I can not understand how hibernate simplify persistence. Too many configuration, and not easy to learn. New jdbc templates with java is the best.

Add a comment