Can i replace the JDBC logic with hibernate afterwards
I am building a website with spring MVC. As I am new to Java EE, I'm finding it difficult to apply everything at once.
So, is it possible that I can start building the app with simple JDBC and sp开发者_C百科ring and then later replace that with hibernate?
Will the shift be easier so I should learn hibernate first and then start with the website?
Only with (at least) two preconditions:
you completely abstract database access in a DAO layer. Each DAO should have an interface, and a
JdbcXDao
implementation. Later you can add the sameHibernateXDao
your DAO should return domain objects. No result sets or statements should go out of the dao. For example, if you need to get the messages by a given user, you can write
List<Message> messages = dao.getMessages(user)
.
If either of the above is not met, you will have hard time migrating to hibernate.
But it's likely that you won't have the nerves to change the whole DAO layer afterwards, so spend some more time on hibernate and start directly with it.
If JDBC is all you need to build your application, I don't see any benefits on rewriting everything just to use Hibernate.
Hibernate's main purpose is to save you from the hassle of writing repetitive INSERT/UPDATE/DELETE/SELECT code with plain JDBC. And you could mix some PLAIN-JDBC with Hibernate and add ORM to your application gradually if you feel you need to.
Having said that, for simple database stuff, of database stuff that needs complicated queries, I would pick plain JDBC 1000 times before I go into a Hibernate based solution.
Yes, of course you can. It can even be easy to do if you write it properly.
Start your persistence tier with interfaces; only allow your clients to call objects that are interface reference types. Put a JDBC implementation behind them today; tomorrow you can switch to a Hibernate implementation and your clients will be none the wiser. That's the beauty of interfaces.
Something like this:
package persistence;
public interface FooDao
{
List<Foo> find();
Foo find(Long id);
void saveOrUpdate(Foo foo);
void delete(Foo foo);
}
One important thing to note: this interface is dealing only with your model objects, not SQL. The manner in which your persistence layer deals with the relational database starts with the object model. This is a requirement for Hibernate. It immediately becomes mandatory for your JDBC implementation if your intent is to be able to replace it with Hibernate someday.
精彩评论