Migrating to ORM - java

Stepwise, what would be a good way of integrating Spring and Hibernate into an existing JSF application that doesn't use ORM?

1) You would need to design the domain model first and then map it to the database. You could use hibernate reverse engineering tools for this.
2) Other option is to manually map your current objects(DTO) to database tables. Since you use JSF, I assume you'd be having some objects currently.
3) Design the Service Layer around the objects.
Spring -
1) You could use Spring to provide hibernate template, provide common services through bean.
2) You can manage the transaction in Spring.

I would recommend first to write tests to check your code of your previous persistent mechanism. This code could be used to check the correct behavior of our ORM integration.
As mentioned by other answers, having a clear DAO defined by interface helps to bound the DAO code.
Map the domain objects first, then write your DAO, then your service objects (which take care of large atomic suite of operations by enclosing its in a transaction).
Use persistence mechanism which is vendor-agnostic (JPA is the good and only choice).
Start with one kind of database and stick with it during all the migration. In very uncommon cases, you can meet subtle differences between databases which could be very hard to solve, especially if you're a beginner.
When starting, use automatic generation of database (generateDdl for hibernate subsystem) and then, when things starts to be stabilized, force #Table and #Column annotations to fix name of each column. At this point, write a SQL script which generate the database with empty tables. The reason if to fix your architecture and be sure you're controlling the database organization.
If you're serious about ORM, please look at Java Persistence With Hibernate of Christian Bauer (Manning publications), this is "the bible" about hibernate and JPA on Java.

If you've written Spring properly, you should have DAO/repository interfaces. If that's the case, all you have to do is write a new implementation of that interface using Hibernate, test it, and change your Spring configuration to inject it.
ORM presumes that you have an object model in place to map to a relational schema. If you don't, I would advise against using ORM. Better to use iBatis or JDBC in that case.

Related

What's the difference between Hibernate and Spring Data JPA

What are the main differences between Hibernate and Spring Data JPA?
When should we not use Hibernate or Spring Data JPA?
Also, when may Spring JDBC template perform better than Hibernate and Spring Data JPA?
Hibernate is a JPA implementation, while Spring Data JPA is a JPA data access abstraction. Spring Data JPA cannot work without a JPA provider.
Spring Data offers a solution to the DDD Repository pattern or the legacy GenericDao custom implementations. It can also generate JPA queries on your behalf through method name conventions.
With Spring Data, you may use Hibernate, EclipseLink, or any other JPA provider. A very interesting benefit of using Spring or Java EE is that you can control transaction boundaries declaratively using the #Transactional annotation.
Spring JDBC is much more lightweight, and it's intended for native querying, and if you only intend to use JDBC alone, then you are better off using Spring JDBC to deal with the JDBC verbosity.
Therefore, Hibernate and Spring Data are complementary rather than competitors.
There are 3 different things we are using here :
JPA : Java persistence api which provide specification for persisting, reading, managing data from your java object to relations in database.
Hibernate: There are various provider which implement jpa. Hibernate is one of them. So we have other provider as well. But if using jpa with spring it allows you to switch to different providers in future.
Spring Data JPA : This is another layer on top of jpa which spring provide to make your life easy.
So lets understand how spring data jpa and spring + hibernate works-
Spring Data JPA:
Let's say you are using spring + hibernate for your application. Now you need to have dao interface and implementation where you will be writing crud operation using SessionFactory of hibernate. Let say you are writing dao class for Employee class, tomorrow in your application you might need to write similiar crud operation for any other entity. So there is lot of boilerplate code we can see here.
Now Spring data jpa allow us to define dao interfaces by extending its repositories(crudrepository, jparepository) so it provide you dao implementation at runtime. You don't need to write dao implementation anymore.Thats how spring data jpa makes your life easy.
I disagree SpringJPA makes live easy. Yes, it provides some classes and you can make some simple DAO fast, but in fact, it's all you can do.
If you want to do something more than findById() or save, you must go through hell:
no EntityManager access in org.springframework.data.repository classes (this is basic JPA class!)
own transaction management (hibernate transactions disallowed)
huge problems with more than one datasources configuration
no datasource pooling (HikariCP must be in use as third party library)
Why own transaction management is an disadvantage? Since Java 1.8 allows default methods into interfaces, Spring annotation based transactions, simple doesn't work.
Unfortunately, SpringJPA is based on reflections, and sometimes you need to point a method name or entity package into annotations (!). That's why any refactoring makes big crash.
Sadly, #Transactional works for primary DS only :( So, if you have more than one DataSources, remember - transactions works just for primary one :)
What are the main differences between Hibernate and Spring Data JPA?
Hibernate is JPA compatibile, SpringJPA Spring compatibile. Your HibernateJPA DAO can be used with JavaEE or Hibernate Standalone, when SpringJPA can be used within Spring - SpringBoot for example
When should we not use Hibernate or Spring Data JPA? Also, when may Spring JDBC template perform better than Hibernate / Spring Data JPA?
Use Spring JDBC only when you need to use much Joins or when you need to use Spring having multiple datasource connections. Generally, avoid JPA for Joins.
But my general advice, use fresh solution—Daobab (http://www.daobab.io).
Daobab is my Java and any JPA engine integrator, and I believe it will help much in your tasks :)
Spring Data is a convenience library on top of JPA that abstracts away many things and brings Spring magic (like it or not) to the persistence store access. It is primarily used for working with relational databases. In short, it allows you to declare interfaces that have methods like findByNameOrderByAge(String name); that will be parsed in runtime and converted into appropriate JPA queries.
Its placement atop of JPA makes its use tempting for:
Rookie developers who don't know SQL or know it badly. This is a
recipe for disaster but they can get away with it if the project is trivial.
Experienced engineers who know what they do and want to spindle up things
fast. This might be a viable strategy (but read further).
From my experience with Spring Data, its magic is too much (this is applicable to Spring in general). I started to use it heavily in one project and eventually hit several corner cases where I couldn't get the library out of my way and ended up with ugly workarounds. Later I read other users' complaints and realized that these issues are typical for Spring Data. For example, check this issue that led to hours of investigation/swearing:
public TourAccommodationRate createTourAccommodationRate(
#RequestBody TourAccommodationRate tourAccommodationRate
) {
if (tourAccommodationRate.getId() != null) {
throw new BadRequestException("id MUST NOT be specified in a body during entry creation");
}
// This is an ugly hack required for the Room slim model to work. The problem stems from the fact that
// when we send a child entity having the many-to-many (M:N) relation to the containing entity, its
// information is not fetched. As a result, we get NPEs when trying to access all but its Id in the
// code creating the corresponding slim model. By detaching the entity from the persistence context we
// force the ORM to re-fetch it from the database instead of taking it from the cache
tourAccommodationRateRepository.save(tourAccommodationRate);
entityManager.detach(tourAccommodationRate);
return tourAccommodationRateRepository.findOne(tourAccommodationRate.getId());
}
I ended up going lower level and started using JDBI - a nice library with just enough "magic" to save you from the boilerplate. With it, you have complete control over SQL queries and almost never have to fight the library.
If you prefer simplicity and more control on SQL queries then I would suggest going with Spring Data/ Spring JDBC.
Its good amount of learning curve in JPA and sometimes difficult to debug issues.
On the other hand, while you have full control over SQL, it becomes much easier to optimize query and improve performance. You can easily share your SQL with DBA or someone who has a better understanding of Database.
Hibernate is implementation of "JPA" which is a specification for Java objects in Database.
I would recommend to use w.r.t JPA as you can switch between different ORMS.
When you use JDBC then you need to use SQL Queries, so if you are proficient in SQL then go for JDBC.

Using Hibernate for Existing Database

We have an application thats already running for a long time. Now we are migrating it to Spring and possibly using Hibernate or any other ORM.
But we caught up with a question. Is it not recommended / bad idea to use Hibernate for the already existing Database and model the object around Schema?
Most people advocate NOT using Hibernate and instead of go with some other ORMs like iBatis. But in our company, all are proponents of Hibernate.
Any experiences?
I would say that it's irresponsible to choose Hibernate, iBatis, or anything else without knowing your requirements.
If you don't have a solid object model, I'd say that Hibernate is a terrible choice.
If you use stored procedures as the interface to your database, I'd say that Hibernate is a terrible choice.
If you don't like the dynamic SQL that Hibernate generates for you, I'd say that Hibernate is a terrible choice.
Get it? Knee-jerk reactions like the ones from those Hibernate proponents aren't a good idea.
It might be that iBatis or Spring JDBC template is a better choice than Hibernate. You ought to become more informed about that decision and make it for your application rather than blindly listen to a mob.
You don't have to be all or none about it, either. It's possible to implement part of your solution with one technology and the rest in another.
I'd recommend making your persistence layer interface-based so you can swap implementations without affecting clients.
I recommend looking at SansORM (a NoORM object mapper). It is designed for SQL-first development, which fits well with retrofitting an existing schema.
Hibernate works well if you can model your database under your objects.
Vice versa, you are likely to get the database model as your your domain model. You need to evaluate how distant those two models are, otherwise you are going to map the database => ORM objects => your domain model. I would avoid that.
If I want to skip the ORM part, I find myself quite happy with JDBI which I prefer over Spring JDBC Template
As others have pointed out an ORM is only a good choice if your database is not far from an object model.
If that is the case then an option would be Hibernate through JPA for two resons:
Netbeans has a tool to generate JPA Entities from an existing database. This entities are not dependant on Netbeans so you could use a different IDE after the initial reverse engineering.
Spring Data JPA can avoid writing trivial queries and focus on the hard ones.

Support JPA and MongoDB in the same application

there exists a requirement which sounds quite simple: support a couple of RDBMS (which i intend to do by using JPA) and MongoDB (spring-data-mongodb is preferred) for persistence. More precisely either the one or the other has to be configured and used, i'm not talking about a cross store.
The procedure shall be the following: code the application, deliver the .war to the customer, in a config file the customer puts the persistence information like the databaseurl (i.e. either mongodb:localhost/test or jdbc:oracle:thin:1521#foo).
Additionally it would be nice to extend the implemenation for further datastores like couchdb.
Is there a best practice or at least any of a non-too-much-overhead-solution which is not that dirty?
Is Eclipselink an option? The latest supports JPA for both RDBMS and NOSQL (including Mongo)
https://blogs.oracle.com/theaquarium/entry/jpa_and_nosql_using_eclipselink
I am currently developing a project with similar needs. I can advise you according to my experience.
I believe that the major concern here is not regarding the technology but more regarding how you will structure data. For that I advise you to use the AbstractFactory and FactoryMethod design patterns. Regaring technology I am using Morphia for MongoDB and JPA for MySQL (as an example) and it's working like a charm.
So the easiest way is to create interfaces for all the objects you want to persist, and then do an implementation for MongoDB with Morphia tags and another with JPA tags. Create one factory for MongoDB that will deal with all the CRUD operations in the MongoDB objects and do the same with a JPA factory.
When the application is starting, you only have to verify the user choice for persistence and then initialize the corresponding factory.
DataNucleus JPA allows you to persist to RDBMS, MongoDB and a host of other datastores (LDAP, HBase, AppEngine, Neo4j, etc), with a simple change to the connection URL, and has done so for quite some time

Middle ground between JDBC and Hibernate?

We've been implementing Hibernate recently as a replacement for JDBC.
What I like is not having to constantly write SELECT, UPDATE, INSERT statements and the associated PreparedStatement and ResultSet code.
However we've been struggling with random bizarre behavior (example A) which I find hard to understand and resolve due to all the different configuration/feature options and the associated Hibernate behavior. I find some of the features like caching, lazy loading, etc, etc very cool but way more than I need - and ultimately confusing.
Is there a better middle ground for someone just looking to avoid the tediousness of JDBC but who doesn't need all the features of Hibernate?
not completely avoiding jdbc, but ... my suggestion is to use the jbdc support provided by spring framework. You still need to write your select, update and inserts, but spring nicely wraps it so you usually don't care about the result set, closing connections, cleaning up your code and such.
Have a look at this chapter from the spring documentations to see the details. You can create an entire dao layer that appears just like the hibernate dao layer, but the internal implementation is different. The RowMapper interface lets you handle the conversion from result sets to objects very nicely. Overall it provides a clean separation of concerns.
(another alternative is to use iBATIS for lightweight O/R mapping, or at least to keep your sql queries outside of Java code).
How about using Hibernate (or TopLink) as a JPA provider. IMO I find the JPA annotation-based approach to doing ORM a lot easier to understand / implement than Hibernate directly - and you can always drop down and do 'difficult' stuff with Hibernate directly.

JPA or Hibernate for Java Persistence?

I'm researching the development of Enterprise Applications in Java, .NET and Groovy. For each platform, we're going to try how hard it is to realize a simple SOAP web service. We'll use the tools and libraries that are most commonly used, to research the real world as accurately as possible.
In this regard, when using Hibernate for persistence, would it better reflect the real world to use the new JPA (Java Persistence API), or the Hibernate custom API that existed before JPA came around?
As you're probably already aware, as of 3.2 Hibernate is JPA certified. You can easily use Hibernate as your JPA provider without having to use any of Hibernate's "custom" APIs.
I'd recommend using straight JPA with Hibernate as the provider. And use annotations rather than XML (much nicer).
Then when you need a little something extra you can always get the Hibernate Session. For example I often find I need to do this in order to pass a collection to a query as a parameter (setParameterList).
It's funny how you worded your question
new JPA ... or plain old Hibernate
Sounds like one has been around forever and the other has just been released. Of course it's not true. JPA was influenced not just by Hibernate but also by TopLink and by J2EE entity beans. The first reference to JSR 220 draft is back from 2003 - how is that for new?
If you use JPA with Hibernate you still use Hibernate and is free to apply any proprietary extensions Hibernate has.
So the choice is yours: use proprietary API or use equivalent established and standard API...
You could stick with a pure JPA spec, just in case you want to swap out Hibernate, but what you'll probably find at some point is that you're never going to swap it out, and you've been missing out on all the really great Hibernate-specific features.
I'd recommend using Hibernate directly, and as Damo suggests, annotations instead of XML. Make sure you have a firm understanding of the "magic" that Hibernate brings. If you're not careful, you could really thrash the database. For example, there's an n+1 query problem depending on how you do #OneToOne joins:
Hibernate OneToOne automatic join fetching (resolving n+1 problem)
I'd also recommend to use an embedded database for unit/integration tests on your Hibernate queries, and watch the SQL that's generated to make sure it looks like something you'd write by hand.

Categories

Resources