Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
In our project we have to decide between Spring JDBCTemplate and Hibernate.
I want to know which is better in terms of performance and implementation and design. and how?
If you do all you can to make both implementations very fast, the JDBC template will probably be a bit faster, because it doesn't have the overhead that Hibernate has. But it will probably take much more time and lines of code to implement.
Hibernate has its learning curve, and you have to understand what happens behind the scenes, when to use projections instead of returning entities, etc. But if you master it, you'll gain much time and have cleaner and simpler code than with a JDBC-based solution.
I would say that in 95% of the cases, Hibernate is fast enough, or even faster than non-optimized JDBC code. For the 5% left, nothing forbids you to use something else, like Spring-JDBC for example. Both solutions are not mutually exclusive.
That depends on your project and how well the Hibernate model fits the way you think. Speed/performance is irrelevant: If you can't wrap your mind about how Hibernate works, your project will be riddled with strange bugs that will take ages to find and fix.
Also note that the internals of Hibernate will leak into your model and DAOs. Notable points of conflict are usually equals()/hashCode() and lazy loading of collections outside of transactions. Since the examples with Hibernate are so simple and you can achieve a lot in a short time, this can lead to the misconception that Hibernate is simple. It's not. Hibernate makes a lot of assumptions and forces you to think and code in a certain way.
Using JdbcTemplate is easier because it's just a very thin wrapper around JDBC itself. The price here is that you will write thousands of lines of really boring code. Also, you will find that SQL strings are really hard to maintain. When your data model changes, you will have to search your whole code base for all places which might be affected. It won't be pretty.
For our own project, we decided against Hibernate because we have really complex data structures (revisioned tree structures) and have to build complex search queries at runtime. Instead, we wrote our own DAO layer using jOOQ. jOOQ is a thin wrapper around JDBC which allows you to write SQL with a nice DSL in Java:
create.selectFrom(BOOK)
.where(PUBLISHED_IN.equal(2011))
.orderBy(TITLE)
Like Hibernate, jOOQ has some rules which you should follow or you won't be happy but these are much more lenient.
As another option, you should have a look at Spring Data. In a nutshell, Spring Data allows you to store your data into anything that remotely resembles a database. This means you can manage your model with Hibernate and another using a NoSQL database. Or you can easily migrate part of your model as needed.
One of the key features is that the DAO implementation look like so:
public interface UserRepository extends Repository<User, Long> {
List<User> findByEmailAddressAndLastname(String emailAddress, String lastname);
}
Now you may wonder where the implementation is since this is just an interface with a method definition but that's it. At runtime, Spring Data will generate code for you which implements this method. This is possible because 99% of all the queries which you will need are of the form "query table for all rows where column X is ..." so they optimized this use case.
OTOH, if you already know that you're going to build really complex search queries at runtime, Spring Data probably won't be of much help.
In our project, we are using both, JdbcTemplate and Hibernate. What you need to do is share DataSource between hibernate and jdbcTemplate.
We can check performance for both according to operations, whichever is better, we use better one. Mostly we are using hibernate for normal operations, if there are big queries or heavy operations, we check performance for jdbc and hibernate whichever better we use it.
The good point is HibernateTransactionManager works for both (JdbcTemplate, plain jdbc) and hibernate.
Is your database design hibernate friendly? If yes then use hibernate...if not then you may want to avoid it. Jdbctemplate has many upsides and there are ways to make sure your SQL queries are easily maintained. Have a class that holds all of them or read them from a file etc. If columns have to be update there is a way to use standard jdbc to get resultset meta data allowing you to retrieve column names. This can be complex but an interesting way to solve an issue. Hibernate is a great tool but complex data models make it get really tricky.
Related
I am trying to optimize the response time of an endpoint. I am faced with wondering if I should invest efforts in refactoring the code to see how three different approaches perform:
The programmatic class javax.persistence.Query
The annotation javax.persistence.NamedQuery
The annotation org.springframework.data.jpa.repository.Query
As it is, we use Spring's #Query. And the amount of refactoring to be done makes it so that I would rather get some theoretical knowledge before diving into this.
What are the advantages and disadvantages to using each of these three options?
Our stack: Postgres, EclipseLink and SpringBoot.
The javax.persistence.NamedQuery annotation just offers a way of specifying queries at the entity class, instead of e.g. as part of spring-data-repository interfaces (org.springframework.data.jpa.repository.Query). Since it is only the location of the query definition that differs, there should not be much of a perfomance difference between the two options.
The javax.persistence.Query interface is used by the JPA implementations internally, so again there is not much performance to be gained by using it explicitly in own code in some way.
Before digging into that direction, the following things should be evaluated first when optimizing response times:
query speed at the database (are indices used properly?)
number of queries issued by the ORM (e.g. avoiding n+1 problems by specifying reasonable fetching behavior using #EntityGraphs)
I am working on a new project using spring data jdbc because it is very easy to handle and indeed splendid.
In my scenario i have three (maybe more in the future) types of projects. So my domain model could be easily modelled with plain old java objects using type inheritance.
First question:
As i am using spring data jdbc, is this way (inheritance) even supported like it is in JPA?
Second question - as addition to the first one:
I could not found anything regarding this within the official docs. So i am assuming there are good reasons why it is not supported. Speaking of that, may i be on the wrong track modelling entities with inheritance in general?
Currently Spring Data JDBC does not support inheritance.
The reason for this is that inheritance make things rather complicated and it was not at all clear what the correct approach is.
I have a couple of vague ideas how one might create something usable. Different repositories per type is one option, using a single type for persisting, but having some post processing to obtain the correct type upon reading is another one.
I'm working with Laravel 5 but I think this question can be applied beyond the scope of a single framework or language. The last few days I've been all about writting interfaces and implementations for repositories, and then binding services to the IoC and all that stuff. It feels extremely slow.
If I need a new method in my service, say, Store::getReviews() I must create the relationship in my entity model class (data source, in this case Eloquent) then I must declare the method in the repo interface to make it required for any other implementation, then I must write the actual method in the repo implementation, then I have to create another method on the service that calls on the repo to extract all reviews for the store... (intentional run-on sentence) It feels like too much.
Creating a new model now isn't as simple as extending a base model class anymore. There are so many files I have to write and keep track of. Sometimes I'll get confused as of to where exactly I should put something, or find halfway throught setting up a method that I'm in the wrong class. I also lost Eloquent's query building in the service. Everytime I need something that Eloquent has, I have to implement it in the repo and the service.
The idea behind this architecture is awesome but the actual implementation I am finding extremely tedious. Is there a better, faster way to do things? I feel I'm beeing too messy, even though I put common methods and stuff in abstract classes. There's just too much to write.
I've wrestled with all this stuff as I moved to Laravel 5. That's when I decided to change my approach (it was tough decision). During this process I've come to the following conclusions:
I've decided to drop Eloquent (and the Active Record pattern). I don't even use the query builder. I do use the DB fascade still, as it's handy for things like parameterized query binding, transactions, logging, etc. Developers should know SQL, and if they are required to know it, then why force another layer of abstraction on them (a layer that cannot replace SQL fully or efficiently). And remember, the bridge from the OOP world to the Relational Database world is never going to be pretty. Bear with me, keeping reading...
Because of #1, I switched to Lumen where Eloquent is turned off by default. It's fast, lean, and still does everything I needed and loved in Laravel.
Each query fits in one of two categories (I suppose this is a form of CQRS):
3.1. Repositories (commands): These deal with changing state (writes) and situations where you need to hydrate an object and apply some rules before changing state (sometimes you have to do some reads to make a write) (also sometimes you do bulk writes and hydration may not be efficient, so just create repository methods that do this too). So I have a folder called "Domain" (for Domain Driven Design) and inside are more folders each representing how I think of my business domain. With each entity I have a paired repository. An entity here is a class that is like what others may call a "model", it holds properties and has methods that help me keep the properties valid or do work on them that will be eventually persisted in the repository. The repository is a class with a bunch of methods that represent all the types of querying I need to do that relates to that entity (ie. $repo->save()). The methods may accept a few parameters (to allow for a bit of dynamic query action inside, but not too much) and inside you'll find the raw queries and some code to hydrate the entities. You'll find that repositories typically accept and/or return entities.
3.2. Queries (a.k.a. screens?): I have a folder called "Queries" where I have different classes of methods that inside have raw queries to perform display work. The classes kind of just help for grouping together things but aren't the same as Repositories (ie. they don't do hydrating, writes, return entities, etc.). The goal is to use these for reads and most display purposes.
Don't interface so unnecessarily. Interfaces are good for polymorphic situations where you need them. Situations where you know you will be switching between multiple implementations. They are unneeded extra work when you are working 1:1. Plus, it's easy to take a class and turn it into an interface later. You never want to over optimize prematurely.
Because of #4, you don't need lots of service providers. I think it would be overkill to have a service provider for all my repositories.
If the almost mythological time comes when you want to switch out database engines, then all you have to do is go to two places. The two places mentioned in #3 above. You replace the raw queries inside. This is good, since you have a list of all the persistence methods your app needs. You can tailor each raw query inside those methods to work with the new data-store in the unique way that data-store calls for. The method stays the same but the internal querying gets changed. It is important to remember that the work needed to change out a database will obviously grow as your app grows but the complexity in your app has to go somewhere. Each raw query represents complexity. But you've encapsulated these raw queries, so you've done the best to shield the rest of your app!
I'm successfully using this approach inspired by DDD concepts. Once you are utilizing the repository approach then there is little need to use Eloquent IMHO. And I find I'm not writing extra stuff (as you mention in your question), all while still keeping my app flexible for future changes. Here is another approach from a fellow Artisan (although I don't necessarily agree with using Doctrine ORM). Good Luck and Happy Coding!
Laravel's Eloquent is an Active Record, this technology demands a lot of processing. Domain entities are understood as plain objects, for that purpose try to utilizes Doctrime ORM. I built a facilitator for use Lumen and doctrine ORM follow the link.
https://github.com/davists/Lumen-Doctrine-DDD-Generator
*for acurated perfomance analisys there is cachegrind.
http://kcachegrind.sourceforge.net/html/Home.html
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I see two main "schools of thoughts" when it comes to creating larger-scale enterprise-wide apps on .NET (Winforms, WPF, ASP.NET).
Some folks use the "repository pattern" which uses a repository that knows how to fetch, insert, update and delete objects. Those objects are rather "dumb" in that they don't necessarily contain a whole lot of logic - e.g. they're more or less data-transfer objects.
The other camp uses what I call "smart" business objects that know how to load themselves, and they typically have a Save(), possibly Update() or even Delete() method. Here you really don't need any repository - the objects themselves know how to load and save themselves.
Big question is: which do you use or prefer? And why?
Do you use the same approach in all your apps, or do you have any particular criteria when to choose one approach over the other? If so - what are those criteria?
I'm not trying to start a flame-war here - just trying to find out what everyone thinks about this and what your opinion is, and why you use one (or both) patterns over the other.
Thanks for any constructive input!
I use the repository pattern because of the Single Responsibility Principle. I don't want each individual object to have to know how to save, update, delete itself, when this can be handled by one single generic repository
The repository pattern doesn't necessary lead to dumb objects.
If the objects have no logic outside Save/Update, you're probably doing too much outside the object.
Idealy, you should never use properties to get data from your object, compute things, and put data back in the object. This is a break of encapsulation.
So the objects should not be anemic except if you use simple DTO objects with CRUD operations.
Then separating the persistence concerns from your object concerns is a good way to have Single Responsibility.
Here are two interesting articles I came across
Repository-is-the-new-singleton
The DAL should go all the way to UI
I think the most important side-effect of using the Repository pattern vs. the ActiveRecord pattern is testing and extensibility.
Without having your ActiveRecord object contain a repository itself how would you isolate data retrieval in your test cases? You can't really fake or mock it easily.
Besides testing it would also be much more difficult to swap out data access technologies, for example from Linq-to-SQL to NHibernate or EntityFramework (though this doesn't happen often admittedly).
It really depends on the needs of the application, but when dealing with a complex business model, I prefer ActiveRecord. I can encapsulate (and test) the business logic all in one place.
Most ORM's (EF, nHibernate, etc...) serve as your Repository. Many people consider a layer on top of an ORM that encapsulates all data interaction as a Repository, which I believe to be incorrect. According to Martin Fowler, a Repository encapsulates data access as a collection. So having individual methods for all data retrieval/mutation might be using a Data Mapper or a Data Access Object.
Using ActiveRecord, I like to have an "Entity" base class. I typically use an ORM (repository) with this base class, so all of my entities have a GetById, AsQueryable, Save and Delete methods.
If I'm using more of a Service Oriented Architecture, I'll use a repository (one that masks direct data access or an ORM) and call it directly in my services.
I'm trying to decide on the best strategy for accessing the database. I understand that this is a generic question and there's no a single good answer, but I will provide some guidelines on what I'm looking for.
The last few years we have been using our own persistence framework, that although limited has served as well. However it needs some major improvements and I'm wondering if I should go that way or use one of the existing frameworks. The criteria that I'm looking for, in order of importance are:
Client code should work with clean objects, width no database knowledge. When using our custom framework the client code looks like:
SessionManager session = new SessionManager();
Order order = session.CreateEntity();
order.Date = DateTime.Now;
// Set other properties
OrderDetail detail = order.AddOrderDetail();
detail.Product = product;
// Other properties
// Commit all changes now
session.Commit();
Should as simple as possible and not "too flexible". We need a single way to do most things.
Should have good support for object-oriented programming. Should handle one-to-many and many-to-many relations, should handle inheritance, support for lazy loading.
Configuration is preferred to be XML based.
With my current knowledge I see these options:
Improve our current framework - Problem is that it needs a good deal of effort.
ADO.NET Entity Framework - Don't have a good understanding, but seems too complicated and has bad reviews.
LINQ to SQL - Does not have good handling of object-oriented practices.
nHibernate - Seems a good option, but some users report too many archaic errors.
SubSonic - From a short introduction, it seems too flexible. I do not want that.
What will you suggest?
EDIT:
Thank you Craig for the elaborate answer. I think it will help more if I give more details about our custom framework. I'm looking for something similar. This is how our custom framework works:
It is based on DataSets, so the first thing you do is configure the
DataSets and write queries you need there.
You create a XML configuration file that specifies how DataSet tables map to objects and also specify associations between them (support for all types of associations).
3.A custom tool parse the XML configuration and generate the necessary code.
4.Generated classes inherit from a common base class.
To be compatible with our framework the database must meet these criteria:
Each table should have a single column as primary key.
All tables must have a primary key of the same data type generated on the
client.
To handle inheritance only single table inheritance is supported. Also the XML file, almost always offers a single way to achieve something.
What we want to support now is:
Remove the dependency from DataSets. SQL code should be generated automatically but the framework should NOT generate the schema. I want to manually control the DB schema.
More robust support for inheritance hierarchies.
Optional integration with LINQ.
I hope it is clearer now what I'm looking for.
Improve our current framework - Problem is that it needs a good deal of effort
In your question, you have not given a reason why you should rewrite functionality which is available from so many other places. I would suggest that reinventing an ORM is not a good use of your time, unless you have unique needs for the ORM which you have not specified in your question.
ADO.NET Entity Framework
We are using the Entity Framework in the real world, production software. Complicated? No more so than most other ORMs as far as I can tell, which is to say, "fairly complicated." However, it is relatively new, and as such there is less community experience and documentation than something like NHibernate. So the lack of documentation may well make it seem more complicated.
The Entity Framework and NHibernate take distinctly different approaches to the problem of bridging the object-relational divide. I've written about that in a good bit more detail in this blog post. You should consider which approach makes the most sense to you.
There has been a great deal of commentary about the Entity Framework, both positive and negative. Some of it is well-founded, and some of the seems to come from people who are pushing other solutions. The well-founded criticisms include
Lack of POCO support. This is not an issue for some applications, it is an issue for others. POCO support will likely be added in a future release, but today, the best the Entity Framework can offer is IPOCO.
A monolithic mapping file. This hasn't been a big issue for us, since our metadata is not in constant flux.
However, some of the criticisms seem to me to miss the forest for the trees. That is, they talk about features other than the essential functionality of object relational mapping, which the Entity Framework has proven to us to do very well.
LINQ to SQL - Does not have good handling of object-oriented practices
I agree. I also don't like the SQL Server focus.
nHibernate - Seems a good option, but some users report too many archaic errors.
Well, the nice thing about NHibernate is that there is a very vibrant community around it, and when you do encounter those esoteric errors (and believe me, the Entity Framework also has its share of esoteric errors; it seems to come with the territory) you can often find solutions very easily. That said, I don't have a lot of personal experience with NHibernate beyond the evaluation we did which led to us choosing the Entity Framework, so I'm going to let other people with more direct experience comment on this.
SubSonic - From a short introduction, it seems too flexible. I do not want that.
SubSonic is, of course, much more than just an ORM, and SubSonic users have the option of choosing a different ORM implementation instead of using SubSonic's ActiveRecord. As a web application framework, I would consider it. However, its ORM feature is not its raison d'être, and I think it's reasonable to suspect that the ORM portion of SubSonic will get less attention than the dedicated ORM frameworks do.
LLBLGen make very good ORM tool which will do almost all of what you need.
iBATIS is my favourite because you get a better grain of control over the SQL
Developer Express Persistence Objects or XPO as it is most known. I use it for 3 years. It provides everything you need, except that it is commercial and you tie yourself with another (single company) for your development. Other than that, Developer Express is one of the best component and framework providers for the .NET platform.
An example of XPO code would be:
using (UnitOfWork uow = new UnitOfWork())
{
Order order = new Order(uow);
order.Date = DateTime.Now();
uow.CommitChanges();
}
I suggest taking a look at the ActiveRecord from Castle
I don't have production experience with it, I've just played around with their sample app. It seems really easy to work with, but I don't know it well enough to know if it fits all your requirements