7 Replies - 6573 Views - Last Post: 28 February 2012 - 02:21 PM

#1 nick2price  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 562
  • View blog
  • Posts: 2,826
  • Joined: 23-November 07

spring and hibernate

Posted 27 February 2012 - 03:30 PM

Thought I would start looking into spring and hibernate, struggling to fully understand them though. Say I create a java EE application, are these frameworks something I would look to implement afterwards? What do you lot use them for?
I dont see the need for hibernate when you have JDBC and spring just looks like a few extra additions to a build file or a java bean.

Just trying to see what people use them for so I can get a better understanding of when to implement them.

Nick

Is This A Good Question/Topic? 1
  • +

Replies To: spring and hibernate

#2 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1155
  • View blog
  • Posts: 2,536
  • Joined: 05-May 05

Re: spring and hibernate

Posted 27 February 2012 - 04:25 PM

Hibernate is ORM (Object-relational mapping) tool. It completely removes the need for JDBC code. It has vendor-specific database drivers that implement the queries for you. Instead of (in JDBC):

class Customer {
      int id;
      String first;
      int age;
}

void saveToDB(Customer c) {
    Statement stmt = null; //createStatement()
    stmt.executeUpdate("UPDATE customers set first_name ='"+c.firstName+"', age ='"+c.age+"' WHERE id ='"+c.id+"'");
}



With ORM, it's simply (or at least close to):

void saveToDB(Customer c) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    session.save(c);
}



One of the nice things is that your not hard coding all your SQL queries. Its just cleaner and uses less code. Don't you hate all that boilerplate JDBC code? You could create a full app without one line of SQL. ORM lets you focus on domain logic, instead of DB development. And, if you update your domain objects, you don't have to update the mapped tables. That's huge! ORM has its own query language. Some ORM tools support concurrency, caching, and the list goes on; things that would be a pain to do without them. See 10 advantages of ORM. Hibernate is very powerful. It does let you use raw SQL if you need it. Here's a small tutorial.

Spring is an IOC framework. Dependency injection is an IOC implementation that allows you to code to interfaces at compile-time without knowing the interface implementation. You can then specify the implementation at runtime via a configuration file for example. You can imagine a system administrator choosing a database configuration among many for some business system at deployment time or during a system migration. The Spring container will read the configuration and use reflection to create the specific implementation and inject it into the class(es) that depend on it.

Suppose I define some injectable classes:

interface DataSource {
     boolean persist(Object o); //hey hibernate integration would be nice here!
}

class OracleDS implements DataSource {
     boolean persist(Object o){}
}

class MySQLDS implements DataSource {
     boolean persist(Object o){}
}



Here's the class that needs an injectable class:

class DataManager {
     DataSource dataSource;
     public void setDataSource(DataSource dataSource){
          this.dataSource = dataSource;
     }
}



I just write that. And when I actually use the DataManager, I can assume the dataSource has a valid reference. In an XML file I can define which data source I want:

<hibernate>
     <dep class="DataManager">
          <property name="dataSource">
               <inject class="OracleDS"/>
          </property>
     </dep>
</hibernate>



That's a psuedo XML file.

Spring also provides a ton of other features that make business development easier. Spring supports abstracting distributed components and data sources, MVC development, aspect oriented programming, transactions, etc. I think it has a ton of useful APIs that are geared towards business process as well. I think the philosophy is to allow the developer to focus on business logic. That's just a high-level overview. I'm sure Spring has many useful things that can only be realized when using it on a real project. Note that EJB 3 supports DI, so I wouldn't be surprised if Spring lost its mojo over the last few years. Do remember that both Hibernate and Spring are geared towards enterprise systems, which are usually very large.
Was This Post Helpful? 3
  • +
  • -

#3 nick2price  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 562
  • View blog
  • Posts: 2,826
  • Joined: 23-November 07

Re: spring and hibernate

Posted 27 February 2012 - 05:07 PM

So really, they are just frameworks which make your life easier. Everything they provide can be done manually, it will just be a longer, more complicated process. I do like hibernate though, cos I know how annoying JDBC can get, especially when your dealing with inner joins etc. I suppose in the real world though, you would be expected to know these things as they wouldnt want you taking years coding something which could be done with a few lines.

I am interested in your hibernate code. Normally when working with jdbc, I have a DatabaseUtils class which basically provides method implementations for updating, saving etc. So these are already defined in hibernate as I see you use save©. So I presume they have other methods such as drop? I also presume it can handle more complex scenarios where your working across several tables? (So, update customers if age in the student table changes) (Or would this be where you needed to use raw sql)

Spring does look very useful, also very large. I know a lot of java jobs still ask for this skill, so better start learning it :dontgetit:

As most of my time has been spent in JavaSE, I am now moving onto JavaEE (which is fantastic!). Before starting EE, I never really heard of a Bean. I still cant figure out why it is different to a standard setter/getter class. Basically, all Objects I created were beans, and I didnt even know. I thought I was really proficient in java (as I know most things in SE). I didnt realise I was missing out on so much, I mean, I have barely scraped the surface with SE. I know most web languages aswell, so I have started to move onto Drupal and I tell you what, its a killer!!! Unfortunately though, I suppose it is like spring. If your asked to create a large system for a client which basically manages their content, if you dont use something like Drupal you are just going to spend a very long time reinventing the wheel!!!

Nick
Was This Post Helpful? 0
  • +
  • -

#4 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1155
  • View blog
  • Posts: 2,536
  • Joined: 05-May 05

Re: spring and hibernate

Posted 27 February 2012 - 07:03 PM

Quote

So really, they are just frameworks which make your life easier. Everything they provide can be done manually, it will just be a longer, more complicated process.


Yes.

Quote

I do like hibernate though, cos I know how annoying JDBC can get, especially when your dealing with inner joins


I wouldn't doubt that hibernate makes SQL joins a lot easier. I haven't used it thoroughly, so I wouldn't know.

Quote

Normally when working with jdbc, I have a DatabaseUtils class which basically provides method implementations for updating, saving etc.


But does the utils class expose interfaces as easy as these:

session.persist(<My domain object>);
session.find(<My domain object>.class, <My object primary key>);
session.list(<My domain object>.class);



Quote

So I presume they have other methods such as drop?


Of course. Whatever abstractions the API doesn't support can be handled in HQL. Most of the JOIN examples I see use HQL. HQL is really no different than JDBC code, but still should be less code. Instead of using table and field names, you use class and property names.

Quote

(So, update customers if age in the student table changes) (Or would this be where you needed to use raw sql)


Good question. So you asking whether it supports cascading operations. Yes it does. See this example.

Here's the official Hibernate docs.

Quote

Before starting EE, I never really heard of a Bean.


It's a Java concept that never really took flight at its inception. It was created in an attempt to create a framework for creating GUI builders -- or something along those lines. Beans are reusable components that following a convention. Their reusable because they can be used within any framework that conforms to the convention. They are also configurable because they conform to the convention.

Quote

I still cant figure out why it is different to a standard setter/getter class.


By making the setter method name conform to the convention you can use reflection to find the correct setter/getter for the bean property. E.g.:

class Foo {
     String bar;
     void setBar(String bar){ this.bar = bar; } 
}


Suppose I have the following XML that specifies a string value (it could easily be a class too) to inject:

<hibernate>
     <dep class="Foo">
          <property name="bar" class="java.lang.String" >
               <inject class="java.lang.String" val="Hello World!">
          </property>
     </dep>
</hibernate>



The Spring container will read the XML, see that Foo.bar needs the value "Hello World" injected in to it. Here's a simple example. I'm using reflection to find the class field rather than the setter method.

Spoiler


Take notice of these two methods:

private static boolean inject(Object obj, DIEntry e) {
    Class<?> cls = obj.getClass();
    try {
        String properFieldName = Character.toUpperCase(e.propertyName.charAt(0))+""+e.propertyName.substring(1);
        Method m = cls.getDeclaredMethod("set"+properFieldName, String.class);
        m.invoke(obj, e.value);
        return true;
    } catch (Exception exp) {
        exp.printStackTrace();
    }
    return false;
}

private static DIEntry createMockXMLDIEntry(Class cls) {
    // check Class and find it's XML entry
    DIEntry e = new DIEntry();
    e.className = "Foo";
    e.propertyName = "bar";
    e.value = "Hello World!";
    return e;
}



DIEntry is an dependency injection entry loaded from the XML. inject puts the DI entry values into the new instance. That's basically what Spring does for you. You can see reflection is used to find the setter method for the class field that's specified in the XML.

String properFieldName = Character.toUpperCase(e.propertyName.charAt(0))+""+e.propertyName.substring(1);
Method m = cls.getDeclaredMethod("set"+properFieldName, String.class);



Then the actual injection:

m.invoke(obj, e.value);



This mock container code follows JavaBeans naming conventions for setters. Without those conventions, there would be no standard for creating components that can you can expect to work in various frameworks (reusable). People could name their setters (e.g. setBAR, SetBar, SetBar) whatever they want and expect the framework to figure it out, and it won't of course because there are just too many possibilities to cover.

Quote

I know most web languages aswell, so I have started to move onto Drupal and I tell you what, its a killer!!!


I actually went ahead and tried OpenCMS. It's was pretty darn cool. Putting dynamic code in a web page took seconds. I like coding from that perspective. It was so streamlined. :bigsmile:

Quote

If your asked to create a large system for a client which basically manages their content, if you dont use something like Drupal you are just going to spend a very long time reinventing the wheel!!!


Yeah, Java and web languages have their trade-offs.
Was This Post Helpful? 3
  • +
  • -

#5 nick2price  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 562
  • View blog
  • Posts: 2,826
  • Joined: 23-November 07

Re: spring and hibernate

Posted 27 February 2012 - 08:07 PM

Fantastic reply, so much useful information to look into. OpenCMS is kool. I am scared to use it as a cms for the time being though as I am unsure how popular it is, meaning I dont know if it will end next week. Thats why I am learning Drupal, quite a complicated cms (I not talking about creating basic webpages. The complicated bit is when you get into advance themeing and module development). I also out of interest got the prices for the enterprise edition of OpenCms....not cheap (close to 10k anually). I am also looking into Magnolia, which is another big java cms. It looks like they have good spring integration.

Thanks for the great info.

Nick
Was This Post Helpful? 0
  • +
  • -

#6 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1155
  • View blog
  • Posts: 2,536
  • Joined: 05-May 05

Re: spring and hibernate

Posted 27 February 2012 - 08:50 PM

Quote

I am scared to use it as a cms for the time being though as I am unsure how popular it is, meaning I dont know if it will end next week.


I get that same feeling that open source development is slow.

Amazon Web Services was built using OpenCMS. Regardless, it's still magnitudes better than working from scratch.

Quote

Thanks for the great info.


No problem. :^:
Was This Post Helpful? 0
  • +
  • -

#7 nick2price  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 562
  • View blog
  • Posts: 2,826
  • Joined: 23-November 07

Re: spring and hibernate

Posted 28 February 2012 - 01:38 PM

Hey, been doing some more research and it seems spring and hibernate are generally geared towards web apps. Say I wanted to develop a desktop app using SE, which will be used by a company on their own computer. This app will do a lot of things like store input into a database and send emails. Can spring and hibernate be used with a SE app?

Also, I see that spring is basically 6 modules, one of them is ORM which includes hibernate. So is hibernate actually part of spring, not its own independent framework? I also see a DAO module which is a JDBC transcation management. Is this like working with general JDBC? Strange they would offer this module when they have all the ORM stuff.
Was This Post Helpful? 0
  • +
  • -

#8 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1155
  • View blog
  • Posts: 2,536
  • Joined: 05-May 05

Re: spring and hibernate

Posted 28 February 2012 - 02:21 PM

Quote

Can spring and hibernate be used with a SE app?


Yes. They're just libraries with a configuration file.

Quote

Also, I see that spring is basically 6 modules, one of them is ORM which includes hibernate. So is hibernate actually part of spring, not its own independent framework?


I think you're referring to integration classes. The core hibernate jar is 4MB, whereas the Spring ORM jar is ~65 KBs. Besides, it wouldn't make sense for spring to bundle hibernate when it can be retrieved easily through Maven. Their both bloated as it is.

Quote

I also see a DAO module which is a JDBC transcation management. Is this like working with general JDBC?


I guess. I know they do support JDBC through the JdbcTemplate API.

Quote

Strange they would offer this module when they have all the ORM stuff.


You may not need or use ORM tools. That would be pretty restrictive to enforce them on all users.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1