I have a question about architecture of my project.
I need to create 10 apis rest, but my database has 300 tables around without relationship.
My question is: It's necessary create all entities from my database?
What is the best practice? Generator Hibernate?
It's necessary create all entities from my database?
It's NOT necessary to generate all entities. For your use case, filter out the tables which are going to be in use by 10 rest APIs and create entities only for these tables. The list may include 5, 10 or 30 tables (count doesn't matter). To be more precise, you only need to create entities against tables on which you intend to work directly or indirectly for these endpoints.
What is the best practice? Generator Hibernate?
Almost always, entities generated by hibernate generator are good start but most often than not, generated entities are far from perfect (or near perfect). As an example, a joiner table in db usually end up being a separate Entity. Feel free to use hibernate entity generator for tables you need (yes, you can specify handful tables using "Table Filters") but I'll strongly advise to revisit all generated entities and tune them as per your specific needs. I personally prefer to hand-code entities myself instead of using generator, especially if the entities are handful.
With regard to best modeling techniques, that's a vast topic and I'll suggest to start with hibernate official documentation. While the documentation focus on hibernate specifics, it talks about various modeling techniques in hibernate feature context and which one is suited for which purpose. You may also want to look at JPA tutorials OR even spring-data-jpa for that matter.
Hope it helps!!
Related
Which is better when using JPA, especially when starting a new project?
Start with designing entities and then let JPA generate the database or
Start with the database schema and let tools generate entity classes?
im part of a small company. im both the software developer and DBA. i have complete freedom for the application and db design
im just starting the project
If you want to design a database, then start with the schema. If you want to write software, then start with the entities. The point of an ORM is to let you think about an object model without having to worry about the database that stores it, so questions of this type actually confuse the issue somewhat by insinuating crossover between the realms. Are you a software developer or a DBA? That, much more than the fact that you're using JPA, is what will determine the correct answer for you.
Um - neither? The power of JPA is that you don't have to generate one from the other! Generation of entities or database schema might be a good starting place if you have one already in place; but the generated stuff is not something you will want to use long term.
You cannot simply design one side of the mapping without any consideration of the other. If you will share the database with other applications, you will need to give more weight to the database schema. If your application has a complex model, you will want to focus on the object model first, allowing it to be driven by the use cases you uncover as you develop your application.
I tend to start with the object model first (even without a backing database to start) because that allows me to see the application in action earlier and get a feel for what we really want to build. But integration with the database must happen earlier rather than later; as its constraints will quickly impose themselves on your object model. :-)
It depends on one's needs . Usually in a product development environment , there are different teams which work on database design , interface design and implementation . So in that case , you have no option than generating the JPA entities from the already database design.
Secondly , if you are starting from the scratch and you know what are you upto then you can probably start writing your own entities (java class) and then generate the database from that.
Better go for database Scheme. Because some of the features r not available in JPA generated database.In JPA We cant give default values for our column. Check HERE for the allowable attributes in JPA.
Its upto you. whether to go top-down or bottom up approach. In case this schema would be exclusive to your application, see how your team members and analysts understand ORM or DB. In my experience analysts are better understand in terms of tables. But if they are good to discuss in terms of classes or UML diagrams go with JPA. Also, take into consideration views of your DBA and build engineer.
If you have complete flexibility and are not restricted to a DB schema and want a clean object model in your java application then start with with the model first and generate the schema from the model. This also allows you to generate clean JSON representations from the clean model to serve as on-the-wire format for your objects using technologies like Jackson (or GSON).
Doing DB Schema first and reverse engineering model classes from it will result in relational concepts seeping into your model classes resulting in poor (polluted) model.
In summary do model first unless your hands are tied and you must map to some existing schema.
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.
I spent all of yesterday reading various articles/tutorials on Hibernate and although I am blown-away by how powerful it is, I have one major concern with it.
It seems that the standard practice is to allow Hibernate to design/generate your DB schema for you, which is a new and scary concept that I am choking on. From the tutorials I read, you just add a new entity to your hibernate.cfg.xml config file, annotate any POJO you want with #Entity, and voila - Hibernate creates the tables for you. Although this is very cool, it has me wondering about a handful of scenarios:
What if you already have a DB schema and the one Hibernate wants to generate for you does not conform to it? What if you have a crazy DBA that refuses to budge on the pre-defined (non-Hibernate) schema?
What if you have reference tables with tens of thousands of records in it (like all the cities in the world)? Would you have to instantiate and save() tens of thousands of unique POJOs or is there a way to configure Hibernate so it will honor and not overwrite data already existing in your tables?
What if you want to do perf tuning on your schema/tables? This includes indexing, normalizing above and beyond what Hibernate creates automatically?
What if you want to add constraints or triggers to your tables? Indexes?
I guess at the root of this is the following:
It looks like Hibernate creates and forces a particular schema/config on your DB. I am wondering how this agenda will conflict with our platform standards, our DBA philosophies, and our ability to perf tune/tweak tables that Hibernate interacts with.
Thanks in advance.
I think you're attributing too much power to Hibernate.
Hibernate does have an idiom that may influence database implementation.
Hibernate does not generate a schema for you unless you ask it to do so. It's possible to start with an existing schema and map it to Java objects using Hibernate. But it might not be possible or optimal if the schema conflicts with Hibernate requirements.
If the DBA won't budge - as they shouldn't - or Hibernate can't accomodate you, then you have your answer: you can't use Hibernate.
Your DBA might consent, but your app might find that the dynamic SQL that's generated for you by Hibernate isn't what you want.
Fortunately for you, it's not the only game in town.
I don't think implementations have to be all or none. If you use simple JDBC to access reference data, what's the harm?
Database design considerations should be independent of Hibernate. Constraints, triggers, normalization, and indexes should be driven by business needs, not your middleware choices.
If you don't have a solid object model, or the schema can't accomodate it, then you should reconsider Hibernate. There's straight JDBC, stored procedures, Spring JDBC, and iBatis as alternatives.
Hibernate comes with a default way to map objects to tables - like several tools/libraries, it favours convention over configuration for simplicity.
However, if you want to map the entities to database tables differently, you can explicitly tell Hibernate how these are mapped (from simple attributes such as changing the table name, through to redefining the foreign-key relationships between related entities and how this is persisted).
If you do this correctly, you don't need to instantiate and save existing data, as this would be pointless - the database already contains the information about the entities in exactly the form that Hibernate understands. (Think about it - to load and then immediately save an entity should always be a no-op, and so can be skipped altogether.)
So the short answer to your question is "no". If you don't care for designing tables, you can let Hibernate adopt a reasonable default. If you do want to design your schema explicitly though, you can do this and then describe that exact schema to Hibernate.
As someone who's worked on java and hibernate in the enterprise for a long time, I have seen very few projects which use this capability. You'll see some build tools and other things do this, but for a real enterprise app, i've never seen this.
Most DBA's won't let the application user create tables. They rely on a privileged user to do those things, and the user that the app connects as would have r/w privs on the data but not the schema itself.
As a result, you write the SQL yourself, and you do the hibernate mappings to match. It doesn't mean your object design won't influence your SQL, but you should still always create your schema upfront.
No. You can use hibernate tools to generate the entities from existing database.
There are 2 ways you can go about in using Hibernate. If you have good DBA or database designer, then it is better to design the database and then map it into hibernate.
On the other hand if you don't have DBA and have good developer then let Hibernate generate Database for you.
The concept behind Hibernate is to map Database and the Objects. So it is called as ORM (Object-Relational Mapping) tool.
Read here for Object Relational Impedance.
This is the preferred way for a quick'n dirty prototype or a simple tutorial, but it's far from being the preferred way for any production application. I largely prefer designing the database independently, using scripts to generate the schema, tables, views, indexes, etc., and map the schema to entities.
As long as the mapping finds the tables and columns in the database, everything is fine.
As soon as you have data in your database and the schema must change, you'll have to write migration scripts anyway. You can't just drop everything and restart from scratch. The tutorials are written for developers starting with Hibernate and who must discover Hibernate as quick as possible, without dealing with complex SQL scripts.
What if you already have a DB schema ...
I don't know where you get that impression. Hibernate can use existing schema. It is quite flexible.
What if you have reference tables ...
Make the relationship LAZY, and it won't load automatically. Only changed object will be saved.
What if you want to do perf tuning ...
Just don't use the generated schema. It is just a starting point. You can customize as you need.
What if you want to add constraints or triggers to your tables? Indexes?
Some as above.
You can use hibernate with an existing database schema.
You can use various annotations to map to existing tables and columns, for example:
#Table(name = "dbschema.dbTable") - should be placed before your class file to map it
#Column(name = "colName") - to map a column
Just be sure that the hibernate is configured with this option:
hibernate.hbm2ddl.auto=update
If you set this to create it will create the schema, so do not do this in your case.
Use hibernate/jpa when appropiate. A common practice when designing apps is to extract the draft and alter it manually after needs (indices etc). However, it will be a pain for you if you change the db layout from hibernate way to do things. Lots of the beauty of JPA will be lost. For tasks which require heavy performance tuning and full control - just go for reguar jdbc.
Some answers:
A. It is possible to add an index annotation : see the table annotation.
B. If you have reference tables, you may choose to have lazy fetching or eager fetching (i.e - if your tables represent a person and a its books - whether to load a person without its book, or with its books)
C. Hibernate can be used to work on existing schema. The schema might not be trivial to work with , but as other have said, you should design db only according to business needs, and not according to framework conventions
D. I would like to encourage you also to read what hibernate does "under the hood" - it uses lots of usage of proxies, which hurts performance, you must understand well the scope of session , and the usages of 1st level and 2nd level cache .
E. Following what I wrote at section D - working with triggers will cause your DB to change "under the hood" when it comes to hibernate. Consider a case where updating a record will create (using a trigger) an entry in some archiving table , and let's say this table is also annotated via hibernate - your hibernate caching will not be aware of the change that happend outside of the application scope.
F. It is important to me to state that I'm not against Hibernate, but you should not use it for all solutions, this is a mistake I did in the past. I now work with Spring-JDBC and I'm quite pleased (for our application needs it will be hard to use Hibernate, and I assume we will consider this only in the case we need to support more than one DB flavor).
I am in need of some further information.
I am developing a small application which will be interacting with a PHP web application. The media server which we are incorporating with is extensible in Java.
I need very little access to the database inside the plugin which we are developing, I only need to view rows in about 10% of the tables. I only need to update data in 1 of the tables.
The schema as a whole is littered with foreign keys, but currently (and there is little chance this changes in the future) I do not need to modify any other information in the databse except for the one column (which is not a foreign key).
I don't really want to model all of these relationships -- as there is no need to.
What is my best bet? Will Hibernate make me map all of these domain objects? Is myBatis (formerly iBATIS) a better choice as the people I am handing off too are more comfortable with SQL? Does it matter which persistence framework I choose -- i.e. are they all going to make me model each of the tables?
These are mySQL InnoDB tables if it makes any difference.
Hibernate only requires you to map those items which you want to use within the context of your Java application. As a result, you can have objects only mapped to those tables which you desire access from the Java side.
A few caveats for the process though:
You will have to model all objects/relationships for all tables with which a given entity table will interact
Things could be messy with two programs hitting the database at the same time. While this is an issue that is accounted for and handled by Hibernate for locking, such things tend to fall by the wayside in PHP.
I can't really speak about Hibernate, but myBatis won't make you model anything - just create a POJO that contains the properties that you care about, then write mappings (in just straight sql) that map whatever columns from whatever tables you want into your pojo.
With Hibernate, you only need to model the objects you will be working with, and the ddl2hbm tool may be able to generate the Java classes for you based on the existing database, depending on if there are foreign keys linking to models you will not be using.
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 5 years ago.
Improve this question
For our new product re-engineering, we are in the process of selecting the best framework from Java. As the consideration is to go for database agnostic approach for model, we are working on options between Struts + Spring with iBATIS or Hibernate. Please advice which is best as both offer persistence.
iBATIS and Hibernate are quite different beasts.
The way I tend to look at it is this: Hibernate works better if your view is more object-centric. If however you view is more database-centric then iBATIS is a much stronger choice.
If you're in complete control of your schema and you don't have an extremely high throughput requirement then Hibernate can work quite well. The object model makes for fairly convenient code but at a huge complexity cost.
If you're dealing with a "legacy" database schema where you need to write fairly complicated SQL queries then chances are iBATIS will work better.
HQL (Hibernate Query Language) is another language you'll have to learn and even then you'll probably find cases where you still need to write SQL. What's more, chances are you will at some spend half a day figuring out the right combination of XML, properties, annotations, etc to get Hibernate to generate a performant SQL query.
There is no universal "A is better than B" answer for this question.
Consider what you're trying to achieve. Typically, the Command Query Response Segregation
model works well for complex domains.
The reason is that you're trying to do one of two things typically:
Create/Update/Delete some complex domain entities
Run analytic fetch queries (i.e. summation/aggregation queries)
Hibernate works well for case 1 allowing you to just make a POJO and persist/update it. It also does this quickly, unless your domain is quite large.
myBatis is great for fetch queries (case 2) where you just want an answer. Hibernate would attempt to load the entire object graph and you'd need to start tuning queries with LazyLoading tricks to keep it working on a large domain. Conversely if you just want some analytic POJO page, the myBatis implementation of the same query would be trivial.
Because of this, myBatis is faster than Hibernate at SELECTS.
These two cases are the difference between Commands where you want to change the domain data and Responses where you just want to fetch some data.
So, consider these two cases and what your application does. If you have a simple domain and just fetch information, use myBatis. If you have a complex domain and persist entities, use Hibernate. If you do both, consider a hybrid approach. That's what we use on our project that has thousands of entities to keep it under control. ;)
ORM vs persistence framework
Hibernate is object-relation mapping framework (ORM) which maps Java classes to database tables. MyBatis is persistence framework - not ORM. It maps SQL statements to Java methods.
Database schema
Hibernate can create or validate database schema according to your Java model while MyBatis does not have such feature. Also it is convenient for testing environment when you're using in-memory DB. Related discussions:
Can MyBatis create the database schema?
Cache
Hibernate has first level cache which is impossible to disable. It means that if you query item through ORM and then delete it directly with SQL, it stays in the cache. You can explicitly clear the cache to get the most updated results from database. Related discussions:
Do Jpa& Hibernate load data which changes asynchronously in DB?
What are First and Second Level caching in Hibernate?
Optimistic lock management
Also there are differences for optimistic lock management:
MyBatis doesn't support optimistic concurrency control natively,
unlike ORM tools like Hibernate/JPA with the #Version annotation.
Related discussions:
Optimistic concurrency control
How to prevent concurrency issue in UPDATE via iBatis
Lazy loading
Hibernate will try to load entire object graph except objects which are marked for lazy loading. myBatis will load data according a SQL query. Lazy loading may improve performance but it may cause connection leaks if it used with
<property name="hibernate.enable_lazy_load_no_trans" value="true" />
properties. Related discussions:
org.hibernate.LazyInitializationException - could not initialize proxy - no Session
Solve Hibernate Lazy-Init issue with hibernate.enable_lazy_load_no_trans
Hibernate Session management
Entities operations like saving, updating or deleting are performed via Hibernate Session. It requires good understanding how to implement proper Hibernate Session management strategy to avoid detached entity passed to persist and other phenomenons related to Hibernate.
Sometimes it may take more time trying to understand underlying Hibernate behavior than add a little bit more work and write raw SQL statements for myBatis.
Cascading
Hibernate provides cascading, orphan removal and other features for object graphs while they not present in myBatis - to implement them you'll need to write SQL queries explicitly.
Queries
In myBatis you'll write almost plain SQL queries. Hibernate has multiple options to form query: SQL, HQL, Criteria API. Sometimes it may be suitable to use Criteria API when you have many optional fields in criteria. It would provide more structured approach to form query and maybe avoid related mistakes.
Cletus did a great job at summarizing this comparison. Hibernate works well when you control the data model and is more object-centric while iBATIS works well when you need to integrate with an existing database and is more data-centric.
Also I think that Hibernate has a bit more of learning curve. With iBATIS, it's pretty easy to know what is going on while more "magic" happens with Hibernate. In other words, newbies might find iBatis easier to use and to understand.
But I'm not saying that you should prefer iBatis, iBatis and Hibernate are just different as said above.
And by the way, if you go for Hibernate, maybe consider using standardized JPA and EJB 3.0 (JSR-220) object/relational mapping annotations provided by Hibernate Annotations.
Hibernate is an ORM, meaning (at its most basic level) it maps instances of java objects to actual rows in a database table. Generally, for pojo's retrieved via Hibernate: any manipulations and modifications to these pojo's will appear in the database. Hibernate will generate and execute the relevant SQL at an appropriate time.
Mybatis (at its most basic level) is simply a tool for piecing together and executing SQL that is stored in xml files. It does not map instances of Java objects to rows in a database table, rather it maps Java methods to SQL statements, and therefore it is not an ORM. It can also return pojo's of course, but they are not tied to any kind of a persistence context.
Both tools do a lot more than described above, but one is an ORM and one is not.
The criteria to enable you to choose which one to use, I believe, depends critically on the database model you have to work with.
For example imagine a large sprawling schema, representing some insurance model. Developers are required to retrieve
data, and interact with that data in a way that meets the business at hand.
Developer's come on go, and would never be expected to have the requisite business knowledge to write all
the sql by hand (which Mybatis would require). Hibernate would suit a scenario like that.
Business analysts define the datamodel, the entities, the relationships and the interactions, as is their expertise.
Java developer's then use Hibernate to "walk the model". The business developer's can become very productive
quickly without the need to write complicated error prone sql to run on a very complicated schema.
In my expierence, both Hibernate and Mybatis are used regularly on the same project.
Where Hibernate is being used for
General C.R.U.D functionality
'Walking' the 'domain object' relational model
Session management
and where Mybatis is being used for
ad hoc queries
kick off (and interact with) stored procedures
support very specific or intricate queries
support complicated search queries, where search criteria is dynamic, and paging of results
if you're already using Spring, I would start with Spring JDBC rather than plunging right into Hibernate or iBatis. If you write your persistence tier in terms of interfaces, you should have no problem switching implementations after you've gotten Hibernate or iBatis under your belt.
There's no reason why it has to be an "all or none" decision. Use what's best for your situation.