Here's my how-to for starting a Hibernate project. It is meant as a reminder for me :-)
We'll use Java Persistence API.
Mainly, Hibernate is a tool to move the SQL out of the application code. The
philosophy of Hibernate is that you should not write SQL to manipulate data,
instead, you should work with the objects and call methods like
save()
and load()
.
This is done using quite simple XML mappings, or more recently, using @annotations.
For batch selections of multiple objects or batch operations with them,
special language similar to SQL is used. For Hibernate it's
HQL
((Hibernate Query Language), for standardized JPA((Java
Persistence API) it's EQL
((Entity Query Language).
c:\sw\JavaLibs\{projectName-version}
).Create the Persistence Unit – that is a piece of XML configuration, sipmly said. In NetBeans, there is some Hibernate support, but I rather created my own library with creating persistence unit in one step.
.jar
s from the Hibernate folders you extracted above,
including the lib
sub-directories, one directory
by one..jar
s, the red notes about missing classes
should change and finally disappear.doc
dirs from all three
folders. You will have on-line documentation available – very
convenient.OK
. Now you have a new Library in NetBeans.Source Packages / META-INF / persistence.xml
. That
is __the__ persistence unit.Now let's test whether you have done your job well.
doc\reference\en\pdf\hibernate_entitymanager.pdf
.persistence.xml
file elements.right-click project -> New... -> Other -> Java -> Java Main class...
Shift+F6
). Did you see some
exceptins? You shouldn't… Sorry, use Google and your deduction to
fix it.So now you saw your application using Hibernate, although it did nothing yet – at least nothing useful. Actually, it connected to the MySQL server and checked few things – let's see at the MySQL's general query log file (if enabled):
14 Connect domov@localhost on domov 14 Query SHOW VARIABLES WHERE Variable_name ='language' OR ... OR Variable_name = 'init_connect' 14 Query SHOW COLLATION 14 Query SET character_set_results = NULL 14 Query SET autocommit=1 14 Query SET sql_mode='STRICT_TRANS_TABLES'
This is what Hibernate does upon connetion to MySQL in default configuration.
Let's make Hibernate do something.
Because we haven't mapped any entities yet, we can't load or save anything
with Hibernate.
Although, we can do a native query: That is a query in plain SQL, not in HQL
(Hibernate Query Language) or EQL (EJB Query Language).
We will modify the Main class we've run a while above. NetBeans helps very much Here, I strongly recommend you not to copy the code from here, but rather edit the code – with NetBeans it takes about a minute.
First we will try to do something with the EntityManager, what is the main object of interest for you.
em
creation line and type
em.
. NetBeans will tell you all you can do with it.createNativeQuery()
. Docs says:
public Query createNativeQuery(String arg0)
Create an instance of Query for executing a native SQL statement, e.g., for update or delete.
"SET @a = 1
and
press enter. Then dot, select executeUpdate()
and press Enter.
Nice, isn't it? :-)// Use persistence.xml configuration EntityManagerFactory emf = Persistence.createEntityManagerFactory("ISIR_PU"); EntityManager em = emf.createEntityManager(); // Retrieve an application managed entity manager em.createNativeQuery( "SET @a = 1;" ).executeUpdate(); em.close(); emf.close(); //close at application end
Now run the file (Shift+F6
).
Hibernate will complain that it needs to enclose the query in a transaction:
Exception in thread "main" javax.persistence.TransactionRequiredException: Executing an update/delete query at org.hibernate.ejb.QueryImpl.executeUpdate(QueryImpl.java:46)
So let's look for something, that will provide the transaction. Again, type
em.
and press Ctrl+Space
. Look through the methods for
something about transaction. Type get
and press the up arrow –
it will select the getTransaction()
method. Press „;“. Now,
NetBeans will help you gathering the session into a variable. Move back to the
getTransaction()
method name and wait a second. A bulb will
appear, indicating that NetBeans has a suggestion for that piece of code. Press
Alt+Enter
, which shows NetBeans' tips for that line. It will
suggest Assign Return Value to New Variable
. Press Enter. Then
begin the transaction: transaction.begin();
Move under the
createNativeQuery()
call and commit()
the transaction.
The final code will look like this:
// Use persistence.xml configuration EntityManagerFactory emf = Persistence.createEntityManagerFactory("ISIR_PU"); EntityManager em = emf.createEntityManager(); // Retrieve an application managed entity manager EntityTransaction transaction = em.getTransaction(); transaction.begin(); em.createNativeQuery( "SET @a = 1;" ).executeUpdate(); transaction.commit(); em.close(); emf.close(); //close at application end
Now run the file (Shift+F6
). No complains? Congratulations! The
you have done first steps! Later, I'll write something about object-relational
mapping.