295

It's a pretty open ended question. I'll be starting out a new project and am looking at different ORMs to integrate with database access.

Do you have any favorites? Are there any you would advise staying clear of?

Tom Neyland
  • 6,860
  • 2
  • 36
  • 52
  • 2
    See these important related questions: http://stackoverflow.com/questions/494816/using-an-orm-or-plain-sql/494853#494853 http://stackoverflow.com/questions/716532/hibernate-ibatis-jee-or-other-java-orm-tool – ripper234 Nov 21 '10 at 18:56
  • Take a look on micro-orms - thin wrappers around platform's DB access technology - like sql2o for Java https://github.com/aaberg/sql2o or ServiceStack.OrmLite for .NET https://github.com/ServiceStack/ServiceStack.OrmLite – tomaszkubacki Aug 09 '13 at 14:14
  • 3
    After using ORM for more than 5 years my personal choice is Spring JDBC over ORM, and second best is iBatis (MyBatis), I dislike hibernate because of learning curve, less control and performance issues. –  Aug 04 '15 at 12:49
  • Here is (also closed) list of lightweight jdbc wrappers that can be used as alternative to full-blown orms: http://stackoverflow.com/questions/7137929/lightweight-jdbc-helper-library-alternative-to-apache-commons-dbutils – Vadzim May 11 '17 at 13:17

10 Answers10

276

I have stopped using ORMs.

The reason is not any great flaw in the concept. Hibernate works well. Instead, I have found that queries have low overhead and I can fit lots of complex logic into large SQL queries, and shift a lot of my processing into the database.

So consider just using the JDBC package.

David Crawshaw
  • 10,427
  • 6
  • 37
  • 39
  • 95
    It's the same story over and over again with ORM: nice quick initial development, and a big drain on your resources further on in the project when tracking ORM related bugs and inefficiencies. I also hate the fact that it seems to give developers the idea that they never have to write specific optimized queries. – Eelco May 29 '10 at 06:52
  • 10
    Hey, is this all true for big real life projects? – santiagobasulto Oct 05 '10 at 02:13
  • 32
    I agree. I've been using ORM over 3 years now, and i cannot tell how much time was wasted (still is) to resolve persistence related issues. We have no control whatsoever about what is happening "under the hood", configurations are too many to be managed efficiently and there are behaviors that could drive one crazy. On the other hand i have support for major databases and never have to worry about their differences. – marcolopes Mar 05 '11 at 13:03
  • 3
    How are you mapping table rows to Java objects? Are you using setters to set every value for every object? Always create select * from User; and then map manually every user attribute to your Java object? – newbie Sep 21 '12 at 08:54
  • 67
    why not use both, depending on the complexity of query/transaction? it's not like they are mutually exclusive. – amphibient Nov 09 '12 at 20:01
  • 1
    @santiagobasulto and others, while ORM may not work for Java, I can attest that it does work for big real life projects in other languages, e.g. Perl using DBIx::Class. – Will Sheppard Apr 26 '13 at 14:43
  • 8
    @WillSheppard yes Will. I use Django ORM quite a lot and it works great. I think the difference might be in the dynamic nature of python (and perl). Using an ORM in Java is a pain. But in dynamic languages it can be really expressive. There are some great projects to embed ORM operations like DSLs in Python and are great. – santiagobasulto Apr 26 '13 at 19:04
  • 2
    Don't know, I'm using the newest version of Hibernate and haven't had to fight with it much, and I also have the option to write queries in HQL, so it gives me the best of both worlds as far as I'm concerned. I am coming from having written my own simple wrappers in JDBC for years. – Kenny Cason Mar 13 '14 at 00:48
  • 7
    So you wrote your own repositories with transactions, sql queries, object mapping, change tracking, lazy loading, migrations, and relationships, and joins? Cool. You wrote a custom ORM. – Alex May 12 '14 at 06:13
  • 1
    Wonder if this answer holds true when taking caching into account. – Ben George Jul 04 '14 at 09:42
  • Agreed. It's easy but the flaws in them make us suffer after sometime. – Viswanath Lekshmanan Nov 03 '14 at 16:56
  • What do you do when you have to change DB vendors? – dbalakirev Jan 05 '15 at 18:03
  • 1
    I agree with you. Hibernate ORM looks heavy and not flexible. It's very difficult to do the complex queries for reports. I feel free and comfortable when using MyBatis or JDBC because I can map anything I like as well as it's nearly plain SQL. – emeraldhieu Aug 11 '15 at 02:58
  • I prefer ORM, Something not heavy(eg. mybatis). All the logic written in Stored Procedures, but the database call goes through ORM. I'm using ORM as a mechanism to pass the arguments to Database. It is very effective when we push the array list as an argument to database call. – MukeshKoshyM Mar 15 '16 at 15:20
  • @amphibient I'm so agree with you. Why just not use both approaches and combine benefits of each one? I guess the main reason of ORMs is not doing all the stuff, but just doing part of it, which is simple, needs to be more manageable and repetitive. Other complex stuff must be using JDBC and writing queries directly! – HMD Nov 04 '20 at 07:46
111

None, because having an ORM takes too much control away with small benefits. The time savings gained are easily blown away when you have to debug abnormalities resulting from the use of the ORM. Furthermore, ORMs discourage developers from learning SQL and how relational databases work and using this for their benefit.

simon
  • 12,666
  • 26
  • 78
  • 113
  • 4
    I agree with this statement. How much from the total development time will be consumed by writing persistence code? I think less than 10-15% – adrian.tarau Nov 25 '09 at 18:50
  • 19
    It depends. Sure, if you're using just one particular kind of database, it's easy to get away with not using an ORM. However, when you need to support other kinds of databases, it can quickly become less manageable. – Jason Baker Jan 23 '10 at 16:26
  • 4
    "The time savings gained are easily blown away when you have to debug abnormalities resulting from the use of the ORM" This not true when skills curve is a decent factor when taking technologies choices. – elsadek Apr 30 '14 at 20:05
  • 9
    Your argument could be offered against the use of any library. The biggest gains of ORMs are things like units of work, object mapping, change tracking, lazy loading, migrations, and relationships. It is a wonderful thing to be able to write user.profile.givenName and not care about what structure was used to store the data for it. – Alex May 12 '14 at 06:17
  • 1
    It could be used against any library, but to varying degrees. Generally I'm a great advocate of using libraries - why re-invent the wheel? However, in this case I feel that Hibernate is for most uses too heavy weight and a more lightweight ORM would be more preferrable. My experiences are based on several years of experience developing with Hibernate and learning its ins and outs thoroughly. – simon May 15 '14 at 14:02
  • 1
    Oh my god, I feel sorry for Java developers. Not using ORM? But maybe you are right, I would be surprised if any library would work correctly in Java world and it's 176 different properties that you must set up. – EralpB Jan 23 '17 at 10:06
  • Using a lower level language (Java) to generate sources for a much higher level language (SQL) makes no sense. It's like writing assembly to generate Java sources so you don't have to write any of that "tricky" Java manually! – barneypitt Oct 02 '22 at 19:02
99

Many ORM's are great, you need to know why you want to add abstraction on top of JDBC. I can recommend http://www.jooq.org to you (disclaimer: I'm the creator of jOOQ, so this answer is biased). jOOQ embraces the following paradigm:

  • SQL is a good thing. Many things can be expressed quite nicely in SQL. There is no need for complete abstraction of SQL.
  • The relational data model is a good thing. It has proven the best data model for the last 40 years. There is no need for XML databases or truly object oriented data models. Instead, your company runs several instances of Oracle, MySQL, MSSQL, DB2 or any other RDBMS.
  • SQL has a structure and syntax. It should not be expressed using "low-level" String concatenation in JDBC - or "high-level" String concatenation in HQL - both of which are prone to hold syntax errors.
  • Variable binding tends to be very complex when dealing with major queries. THAT is something that should be abstracted.
  • POJO's are great when writing Java code manipulating database data.
  • POJO's are a pain to write and maintain manually. Code generation is the way to go. You will have compile-safe queries including datatype-safety.
  • The database comes first. While the application on top of your database may change over time, the database itself is probably going to last longer.
  • Yes, you do have stored procedures and user defined types (UDT's) in your legacy database. Your database-tool should support that.

There are many other good ORM's. Especially Hibernate or iBATIS have a great community. But if you're looking for an intuitive, simple one, I'll say give jOOQ a try. You'll love it! :-)

Check out this example SQL:

  // Select authors with books that are sold out
  SELECT * 
    FROM T_AUTHOR a
   WHERE EXISTS (SELECT 1
                   FROM T_BOOK
                  WHERE T_BOOK.STATUS = 'SOLD OUT'
                    AND T_BOOK.AUTHOR_ID = a.ID);

And how it can be expressed in jOOQ:

  // Alias the author table
  TAuthor a = T_AUTHOR.as("a");

  // Use the aliased table in the select statement
  create.selectFrom(a)
        .whereExists(create.selectOne()
                           .from(T_BOOK)
                           .where(T_BOOK.STATUS.equal(TBookStatus.SOLD_OUT)
                           .and(T_BOOK.AUTHOR_ID.equal(a.ID))))));
Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
Lukas Eder
  • 1,015
  • 7
  • 2
  • 1
    ORM tools are as great as you manage to use them properly. There are projects where ORM tools work like a charms, while in others, they don’t fit well at all. In the end, it’s the development team responsibility to choose the right tool for their project requirements. ORM tools are complex. Unfortunately, only a part of all developers will spend time to understand how they work. The rest will just blame the tool and say it’s bad. The question is: Does the most upvoted answer offers the best advice? > So consider just using the JDBC package. Do we really want to use plain JDBC? – Vlad Mihalcea Jul 07 '16 at 13:06
  • 1
    I try not to let "The database comes first.". An application contains the business rules for the features a client asks for and they almost never ask to create a database. That's a technical detail determined during implementation. – Kwebble Sep 03 '16 at 21:49
  • "Do we really want to use plain JDBC?" - not quite plain JDBC. But not far-off. You can knock up something which uses reflection to populate your objects from JDBC ResultSets and properties files to map database table/field names in a day or two and it's all the ORM you'll ever need. – barneypitt Oct 02 '22 at 18:50
61

Hibernate, because it's basically the defacto standard in Java and was one of the driving forces in the creation of the JPA. It's got excellent support in Spring, and almost every Java framework supports it. Finally, GORM is a really cool wrapper around it doing dynamic finders and so on using Groovy.

It's even been ported to .NET (NHibernate) so you can use it there too.

Abdullah Jibaly
  • 53,220
  • 42
  • 124
  • 197
  • 4
    I vote Hib too, but with an important addition: we should use JPA API *only* even if JPA implementation is in fact provided by Hib. – Vladimir Dyuzhev Jan 17 '09 at 01:24
55

Hibernate, because it:

  • is stable - being around for so many years, it lacks any major problems
  • dictates the standards in the ORM field
  • implements the standard (JPA), in addition to dictating it.
  • has tons of information about it on the Internet. There are many tutorials, common problem solutions, etc
  • is powerful - you can translate a very complex object model into a relational model.
  • it has support for any major and medium RDBMS
  • is easy to work with, once you learn it well

A few points on why (and when) to use ORM:

  • you work with objects in your system (if your system has been designed well). Even if using JDBC, you will end up making some translation layer, so that you transfer your data to your objects. But my bets are that hibernate is better at translation than any custom-made solution.
  • it doesn't deprive you of control. You can control things in very small details, and if the API doesn't have some remote feature - execute a native query and you have it.
  • any medium-sized or bigger system can't afford having one ton of queries (be it at one place or scattered across), if it aims to be maintainable
  • if performance isn't critical. Hibernate adds performance overhead, which in some cases can't be ignored.
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • When I compare Hibernate and JPA I go for Hibernate, and if compare JPA and JDO I go for JDO! I like JDO very much, but I love two features of Hibernate (which are not available in JDO), one is @Filters and the other is you can map version fields (for optimistic locking) into normal fields, which is not possible in JDO. – Amir Pashazadeh Feb 24 '12 at 22:13
33

I would recommend using MyBatis. It is a thin layer on top of JDBC, it is very easy to map objects to tables and still use plain SQL, everything is under your control.

Derek Mahar
  • 27,608
  • 43
  • 124
  • 174
adrian.tarau
  • 3,124
  • 2
  • 26
  • 29
  • 10
    Ibatis for complex reads, and hibernate for create, update delete and simple reads is perfect choice. – darpet Aug 24 '10 at 13:47
20

I had a really good experience with Avaje Ebean when I was writing a medium sized JavaSE application.

It uses standard JPA annotations to define entities, but exposes a much simpler API (No EntityManager or any of that attached/detached entities crap). It also lets you easily use SQL queries or event plain JDBC calls when necessary.

It also has a very nice fluid and type-safe API for queries. You can write things like:

List<Person> boys = Ebean.find(Person.class)
                                  .where()
                                       .eq("gender", "M")
                                       .le("age", 18)
                                  .orderBy("firstName")
                                  .findList();
user11153
  • 8,536
  • 5
  • 47
  • 50
IgKh
  • 925
  • 8
  • 10
  • 6
    I must be a little bit weird... select from Person where gender = 'M' and age < 18 ordered by firstName just looks so much better to me :-) – Eelco May 29 '10 at 06:46
  • 4
    This is one of the better orms I've seen in java. It's decision to use a singleton is refreshing and gives it a massive practical advantage over the others. – opsb Jun 23 '10 at 07:46
  • I think you mean [fluent](http://en.wikipedia.org/wiki/Fluent_interface) not fluid. – Montdidier Apr 07 '15 at 08:46
  • @opsb I think technically it's a monostate, not a singleton. – Montdidier Apr 07 '15 at 08:50
  • How to get Started with Avaje Ebean ORM? Any videos Tutorials?? – Avinash Dec 26 '17 at 10:27
12

SimpleORM, because it is straight-forward and no-magic. It defines all meta data structures in Java code and is very flexible.

SimpleORM provides similar functionality to Hibernate by mapping data in a relational database to Java objects in memory. Queries can be specified in terms of Java objects, object identity is aligned with database keys, relationships between objects are maintained and modified objects are automatically flushed to the database with optimistic locks.

But unlike Hibernate, SimpleORM uses a very simple object structure and architecture that avoids the need for complex parsing, byte code processing etc. SimpleORM is small and transparent, packaged in two jars of just 79K and 52K in size, with only one small and optional dependency (Slf4j). (Hibernate is over 2400K plus about 2000K of dependent Jars.) This makes SimpleORM easy to understand and so greatly reduces technical risk.

David Schmitt
  • 58,259
  • 26
  • 121
  • 165
  • Haven't used it, but ActiveObjects describes itself as sort of a Hibernate-lite on their website, so there probably is some similarity. – Abdullah Jibaly Jan 17 '09 at 05:01
10

Eclipse Link, for many reasons, but notably I feel like it has less bloat than other main stream solutions (at least less in-your-face bloat).

Oh and Eclipse Link has been chosen to be the reference implementation for JPA 2.0

Tom Neyland
  • 6,860
  • 2
  • 36
  • 52
5

While I share the concerns regarding Java replacements for free-form SQL queries, I really do think people criticizing ORM are doing so because of a generally poor application design.

True OOD is driven by classes and relationships, and ORM gives you consistent mapping of different relationship types and objects. If you use an ORM tool and end up coding query expressions in whatever query language the ORM framework supports (including, but not limited to Java expression trees, query methods, OQL etc.), you are definitely doing something wrong, i.e. your class model most likely doesn't support your requirements in the way it should. A clean application design doesn't really need queries on the application level. I've been refactoring many projects people started out using an ORM framework in the same way as they were used to embed SQL string constants in their code, and in the end everyone was suprised about how simple and maintainable the whole application gets once you match up your class model with the usage model. Granted, for things like search functionality etc. you need a query language, but even then queries are so much constrained that creating an even complex VIEW and mapping that to a read-only persistent class is much nicer to maintain and look at than building expressions in some query language in the code of your application. The VIEW approach also leverages database capabilities and, via materialization, can be much better performance-wise than any hand-written SQL in your Java source. So, I don't see any reason for a non-trivial application NOT to use ORM.

Mirko Klemm
  • 2,048
  • 1
  • 23
  • 22
  • 14
    If you're building applications on top of a persistent store, like many of us do, whether that is a RDBMS or some NoSQL flavor, that store will have it's own efficient way of accessing it. Trying to abstract from that too much is just overengineering. Being overly zealous about 'true OOD' gets those astronaut architectures Java is infamous for. – Eelco May 06 '11 at 20:57