Hibernate and stored procedures - java

As my understanding on setting hibernate, I need to create
table meta data file (person.hbm.xml), include all the fields mapping
java object (person.java)
If we use stored procedures for all transaction, do we still need the above configuration?
It seems hibernate and stored procedures will overlap,
We set up the stored procedure because we don't want the to developer know all the field in db. If tables change, then we need update above files.
Does it mean if we purely use stored procedure, we should just go for JDBC?
If hibernate, we should stay in HQL?

You can use native SQL and map the result to object:
sess.createSQLQuery("SELECT * FROM CATS").addEntity(Cat.class);
The JDBC syntax to invoke store procedure is like following:
CallableStatement proc =
connection.prepareCall("{ call set_death_age(?, ?) }");
proc.setString(1, poetName);
proc.setInt(2, age);
So maybe, you can invoke stored procedure and map them to object:
sess.createSQLQuery("{ call my_stored_proc }").addEntity(Cat.class);
Note also that updates made through stored procedures will escape hibernate, which means that you will need to evict objects from the 1st level and 2nd level cache yourself.
So as you see, hibernate and stored procedure don't really fit naturally together.
we set up the stored procedure because
we don't want the to developer know
all the field in db. if table change,
then we need update above files.
If you're concerned about security, either use:
database views
Oracle column priviledges
provide mapping files and forbid their modification by developpers

Using Hibenate with Stored Procedures is a certain overlap. As you for example need to write astored procedure for INSERT, UPDATE, DELETE and SELECT, Hibernate provides an easiest way to interract with with relational database objects by mappings them into metadata files like you mentioned person.hbm.xml.
Yes, the use of stored procedure wil require you to write these metadata files anyway. A stored procedure will not replace the Hibernate mappings. Those mapping only tell Hibernate how to persist your object-oriented model to the database. A great thing about Hibernate is that you may even, if needed, generate you database model from your JAVA code through the schema generation tool.
As for the stored procedures, one recommended way is to configure your stored procedures as named queries from within the configuration file. This, however, makes you miss the better potential, in my opinion, of Hibernate.
Does this answer your question? Do you need further explanations?

It is possible to use native-sql and to use stored procedure for querying (with limiations/rules). But, as written in the documentation:
Stored procedures currently only return scalars and entities. <return-join> and <load-collection> are not supported.
So if you want to work with non-managed entities (i.e. not scalars in an Object[]), you'll have to apply a ResultTransformer in the code.
But at the end, if you want to hide the database to developers, if you don't want to map objects to tables, if you don't want to work with associations, if you don't want to use HQL, if you don't want to use an OO approach, then I really wonder why you want to use Hibernate. You'd better use raw JDBC (with Spring for example) or maybe a data-mapper like iBATIS.

You can map the database fields in a result set to an object in hibernate: the documentation explains how.
The idea of Hibernate is to fill the object-relational gap. With the stored procedures (which I can't guess since you haven't told anything about them) you can't get objects from database. You still get rows.
Hiding the database columns from developers sounds like a bad practice to me. Hiding them from the application is perhaps what you want, and you achieve that with the metadata file.

Related

Why the inserting explicit values is not allowed in HQL?

As it mentioned in Hibernate ORM 5.2.13.Final User Guide:
Only the INSERT INTO …​ SELECT …​ form is supported. You cannot specify explicit values to insert.
Is the reasoning behind it elaborated by official sources? Is there any certain limitation that interferes a support of the INSERT INTO ... VALUES ... form in HQL?
The primary reason why DML-style operations have been introduced is the ability to process multiple records in the database at the expense of one (or just a few in some cases involving entity hierarchies) real SQL statement. This way we can avoid fetching all affected data in-memory to perform equivalent logic using CRUD operations on single entities (rows).
Basically this allows us to use familiar UPDATE and DELETE statements from the SQL world in cases where it is needed, while still utilizing all the benefits of HQL/JPQL.
insert ... select also serves that purpose, while insert ... values would provide no benefit comparing to simply persisting an entity instance.

How many ways Hibernate provide to access database?

How many ways Hibernate provide to access database?
For example, I want to CRUD an object to database, I found out:
Using session from SessionFactory:
session.save(object);
...
Using Hibernate Query Language.
Using Hibernate Criteria Queries.
Using Native SQL.
But I don't know what I should use. Please list your practice to access database in PRIORITY DECREASING ORDER and the reason why you do that.
Thank you.
If you have an ID and wants the associated entity, the use Session.get(). It's efficient, and makes use of the first-level cache to avoid reexecuting the query again and again.
If you need to get entities via other criteria (like all the users with a given first name, for example), then use JPQL queries. They are simple to write, very readable, and have less limitations than criteria queries.
If you need to take various optional criteria (like for a complex search form), the criteria API is the tool for the job. But it can't do everything a JPQL query does. There are other APIs available, and you can relatively easily write an API that generates dynamic JPQL queries if needed.
If you have a really complex query that can't be expressed using JPQL, then use SQL.
To write things to the database, queries should generally not be used, except in very specific circumstances where many entities must be modified the same way. Instead, get the entities to modify, and modify them. Hibernate will save their new state automatically.

Why do we need to create native query?

I am working in a project which uses JPA ORM and framework provides two kinds of method to create queries.
entityManager.createQuery(query1);
entityManager.createNativeQuery(query2);
I understand the kinds of query string is to be passed to use them, but I don't know exactly why do we need to create native query? Probably we don't want to use ORM capabilities there?
You do not need to create a native query unless you want to. JPQL eventually is translated into SQL by the framework but the framework lets you call the native query also. Why would want to do that:
Low level access, which means that you can optimize and handle the mapping by yourself; with SQL you actually access the database table while with JPQL you access the entity objects;
Maybe you do not want to learn JPQL if you already know SQL
You already have the queries written in SQL, and do not have resources/time to port them to JPQL
createQuery uses JPAs own query language, you select from Class names instead of table names. This is not SQL, it is just similar, and is later transformed to real SQL. Mapping to java classes will be done automatically and actual class instances will be returned as result.
createNativeQuery uses real SQL, and will not be able to use JPA features. This method is used in general if you need to do something really odd that is not supported by JPA. A list of Object[] will be returned, and mapping to java objects will have to be done manually. In other words, its just like working with a DB before JPA came to, just slightly more convenient since connection handling is done automatically.
I have used it for optimization purposes. Using Native queries means that the ORM mapping is not in place, and instead of JPQL, you use the DB's native syntax. So, as #RasmusFranke also pointed out, if you need something that is not supported by JPA (like when you want to use DB vendor specific extensions, which is conceptually a bad idea, since JPA is all about being DB agnostic, but happens nevertheless. I know...)
The other effect of this is that by using native queries, only the supplied query is run. No eager fetching of other entities, or other unwanted stuff. This way, if you deal with huge amounts of objects, you can save some heap space.

Will hibernate java programs have no sql code?

I haven't worked with hibernate. I have little bit of experience in java. I was going through source of a beast of an java application created by Oracle(Retail Price Management). I was expecting a lot of sql code embedded in there as the application makes heavy use of database. But to my surprise, NO embedded SQL code! so far. I found that it was using what is called as "Hibernate" from the lot of .hbm.xml files. Is it a trademark for java programs using hibernate or maybe I haven't seen the complete codebase?. Could someone enlighten me how this is possible?. Thanks.
Hibernate, as all ORM tools, indeed lessens or eliminates the need to use raw SQL in Java code, due to the following:
many associations between various entities are recorded in the Hibernate mapping, so these are fetched automatically by Hibernate - i.e. if you have an aggregation relationshiop between two classes on the Java side, this may be mapped as a foreign key relationship in the DB, and Hibernate, whenever an instance of class A is loaded, can automatically load the associated instances of class B too,
many queries can be done in Hibernate's own HQL query language, or using its Criteria API.
Under the hood Hibernate does generate SQL to communicate with the DB, but this is not visible on the Java side. It can be seen in the logs though, if it is enabled.
Due to this, programs using Hibernate very rarely need to use JDBC or SQL directly. The exceptions are typically ralted to "tricky" legacy DB schemas which can't be fully handled by Hibernate.
Because that's the whole purpose of using Hibernate or any other object-relational mapping framework.
Hibernate solves object-relational impedance mismatch problems by replacing direct persistence-related database accesses with high-level object handling functions.
Hibernate generates SQL for all its standard database operations. It understands different SQL dialects, and the mapping files (.hbm.xml) tell it about the database structure so it knows how to construct its queries. There is a showSql setting you can turn on if you want to see it outputting its generated SQL as it runs.
Hibernate is an Object-Relational Mapper (ORM). ORMs are used to hide the ugly details of SQL incompatibility[sic] between databases from your program -- you define your tables and map them to an object hierarchy (the .hbm.xml files) and then Hibernate does the rest. Thus most programs that use Hibernate won't see a single phrase of SQL, unless there's a specific reason to execute a complicated query.
Hibernate is a tool, or technology that takes care of the interaction between the database and application for you. You have to tell the structure of the application and the database to it, this is what is in the .hbm.xml files.
The SQL is generated by Hibernate at runtime (kind of)
Say you have an Fruit class, and objects of this is persisted into a T_FRUIT table.
You say this to hibernate, via the .hbm.xml files. That there is a table T_FRUIT, this table is represented by the Fruit class, and which fields in the Fruit class correspond to which columns in th T_FRUIT table.
And then it knows whenever you are trying to save a fruit, it should insert/update to the T_FRUIT table.
When you want to create an Apple, you create an object of fruit corresponding to apple and save "save this fruit".
Hibernate takes care of persisting it.
You can have relationships defined between tables, and Hibernate is intelligent enough to persist in multiple tables.
When you fetch a fruit, hibernate fetches the details of the fruit and its children also(data from referencing tables). And you can say whether you want fetch all the children
at once, or as and when required.
And so on. Aim is to make your life easier, and code maintainable, easy to read, portable,...
With this info, let me redirect you.

insert hibernate domain objects to different database?

I want to copy all data of a specific table from database1 to database2. In my system i have access via hibernate to the domain object from database1, i don't have to transform the data-structure. i have only a native jdbc connection to database2.
whats the best solution to make this groovy script very generally to support all kinds of domain objects i have? so this script only gets my domain object and the connection string to database and inserts all the data?
I faced a similar issue where I needed the ability to export every hibernate entity to an SQL script, in other words if you had a Person object with two properties (username, password) you should be able to generate the SQL insert statement of that Object.
Person.username = x
Person.password = y
then the process would extract from that object the equivalent SQL insert and create something like:
insert into person (username, password) values ('x', 'y');
However my solution was based on the fact that mappings are done using hibernate annotations and not XML configuration, if this is your case you could achieve the same with 1 or 2 working days, just read the annotations. noting that you will have to do an extra step which is executing the resulted SQL inserts on the other DB.
FYI: this method toSQL() was added in a superclass (AbstractHibernateEntity) that every hibernate entity extended, so calling it was the easiest thing to do.
This was the complicated solution and most general one, however if you only need to copy one table from DB to another I would suggest to simple go with a simple JDBC call and avoid complicating your life ;-)
Regards.
Maybe the easiest would be to stick on the technology level that is common to both databases.
If they exist, you could use database-specific commands, that would be really fast.
If not, you could use simple jdbc on both. You could that in a generic way :-)

Categories