Does Spring Data JDBC support inheritance - spring-data-jdbc

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.

Related

Validate a GraphQL schema against another reference schema

I'm not quite sure the wording I should be searching for on this.
I have a GraphQL schema which wraps a group of services using graphql-link-schema to perform the data resolution on the client side. The schema is intended to be built against a separate reference schema. How can I programmatically validate that my implementation matches the reference?
For bonus points- is it possible to determine whether a schema is a superset of another?
Thanks in advance (:
It's an interesting use case, but it's a bit unclear how validation like that would work. What causes validation to fail? Any differences between the two schemas? Extra types? Extra fields on existing types? Differences in return types? Differences in arguments or argument types?
Depending on your answer to the above questions, though, you may be able to cobble together your own validation function using the utility functions available here. Outside the main findBreakingChanges function, some of the utility functions available in that module:
findRemovedTypes
findTypesThatChangedKind
findFieldsThatChangedTypeOnObjectOrInterfaceTypes
findFieldsThatChangedTypeOnInputObjectTypes
findTypesRemovedFromUnions
findValuesRemovedFromEnums
findArgChanges
findInterfacesRemovedFromObjectTypes
If you have a reference or base schema available, though, rather than validating against it, you might also consider extending it when building the second schema. In doing so, you would effectively guarantee that the second schema matches the first except in whatever ways you intentionally deviate from it (by extending existing types, etc.). You could use extendSchema for relatively simply changes, or something like graphql-tool's mergeSchemas for more complicated changes.

spring-data-solr advanced nested model use case

I was given a task to introduce solr to our product so I thought about spring-data-solr. I have seen this blog:
http://www.petrikainulainen.net/spring-data-jpa-tutorial/
and I was able to run embedded solr in integration test. Since I have a simple POC I wanted to make it more advanced to see whether it fits our needs. So I started to search for mapping nested objects. I found this:
https://stackoverflow.com/questions/30561245/is-is-possible-to-use-embeddables-in-spring-data-solr
Someone answered that version 1.4.0 did not support nested objects. Anyone knows whether it changed? These links look promising:
https://dzone.com/articles/using-solr-49-new
Solr: Indexing nested Documents via DIH
https://issues.apache.org/jira/browse/SOLR-1945
So, wrapping up, here is a list of my questions:
Is it possible to map parent-child relation? (on one level at least?)
If you answered 'no' to first question - then how can I flatten child's fields to be part of solr's document? Should I register some kind of converter somehow? Is there anything else I should do?
I found also this: http://docs.spring.io/spring-data/solr/docs/current/api/org/springframework/data/solr/core/mapping/Indexed.html What is the purpose of this annotation? So far I have seen example with #Id and #Field annotations only. Is it used to generate schema based on model maybe? If so then how can I do that?
Last, but not least - when I create a SolrRepository should I use my JPA entity (annotated with #Fields annotations) as a generic type? Or rather should I create a totally different POJO which should be a view/dto of my jpa entity? This question is again about conversion I guess. If I create a dedicated POJO than I can convert/map fields manually in constructor, but this feels rather bad idea.

Streamlining the implementation of a Repository Pattern and SOA

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

Spring JDBCTemplate VS Hibernate in terms of performance [closed]

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.

Persistence framework?

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

Resources