Go to ...
Go to ...
The beginning of the Java Project " Human Resources Department”
Book 1 Book 2
Courses
Initial Java Course Professional Java Course Free webinars Why our courses
Articles Contacts/Questions
The scheme for building an Enterprise application is the new Hibernate data structure.
The beginning of the Hibernate path.
Writing as XML files of Hibernate.
Annotations instead of XML Spring.
The business level is in Spring action.
Go to Web Struts 1.
x. First acquaintance
Hibernate a package for DAO
The most important task of Hibernate is to make the developer think in terms of objects.
And not just at the table level – at the level of relationships between tables.
That is, if the same student is studying in a group, then the relationship should be at the object level, and not at the level of the student's groupId field.
In other words, the uploaded "Student" object must have a link to the “Group " object.
Moreover – to get data about the “Student " object group, you do not need to make an explicit request to the database.
This function should be taken over by Hibernate – in the Java code, we just have to call the student.getGroup()method In principle, all packages like Hibernate are designed for exactly this purpose – to enable the developer to think in terms of objects and relationships between them.
Moreover, these relations can be different – one to one, one to many, many to one, many to many.
Another important thing to note is that you can create class hierarchies.
Yes, yes, it is inheritance that inspires the advocates of object oriented programming so much.
Of course, not everything is absolutely chic and smooth, but in general it is quite decent.
But keep in mind Hibernate should not be a replacement for DAO.
Yes, in general, it will not work very well.
It just allows you to conveniently communicate with the database.
But as we have already considered before, the database is not the only storage option.
We will postpone the development using the DAO template for some time.
But we will definitely return to it as soon as there is a suitable occasion.
To solve its tasks, Hibernate must receive the following information from the developer:
Parameters of the database connection.
In general, we canot get away from this anywhere.
The package is a package, but the connection to the database must somehow specify a description of the mapping of classes to tables.
This description includes the relationship between a column in a table and a field in a class.
If we recall the same students, then for each field in the Student class, we had a field in the table.
That's what we'll have to do.
Description of relations between classes
At first, all these difficulties will seem superfluous – well, in the end, that we should write several SQL queries to get data add, query, fix and delete.
But if you have not 3-4 tables, but 500-600 ?
And if you need to add some field and a relationship between the tables ?
Such corrections become a non trivial task that requires a lot of time and subsequent testing.
On the other hand, you should not flatter yourself – Hibernate is not so great at solving absolutely all tasks.
For example, complex queries that are often required to create puzzling reports are often easier and more efficient to do in SQL.
Hibernate allows you to do this – you can create a regular SQL query in it.
Also, mass changes in it are not done very effectively.
And I would also highlight the not always successful implementation of relationships – especially the many to many relationship – when editing such a list, Hibernate simply deletes all the old relationships and replaces them with new ones.
In general, look, compare, optimize.
But still, Hibernate makes it much easier to work with the database and significantly simplifies the code of your application.
Well, let's get started.
First, you need to download the package itself.
Go to the Hibernate page.
On the left there will be a menu in which we select the Download item.
In the list of implementations, select "Hibernate Core".
I will use the version 3.3.1.GA.
It goes without saying that it will become outdated over time, but we hope that compatibility will help to understand the newer version.
To immediately remove all questions about the rest of the development tools:
The JDK version is 1.6.
Regarding the sub versions, I think that this will not be significant for us.
But just in case, I will specify the version under which I worked 1.6.0_03.
NetBean 6.5.
In principle, you can also use version 6.1.
I donot think it will be fundamentally Tomcat 6.0.16.
But in general, any Tomcat 6 MySQL 5.0 sub – version will do we even installed and configured it.
Who does not remember what and how refer to Part 3 Database
As for the rest of the packages – every time I study, I will write the version with which I wrote the examples.
I usually install all the packages in a separate folder – JAVA.
There are Tomcat, NetBeans, JDK, Hibernate, etc.
You can choose some other name for yourself.
It's just a habit
Pre configuring the environment
This section is intended for those who have never worked with NetBeans.
Because you can often see questions “How do I connect the library ?”
, "How do I start programs ?”
– I will try to remove some of them.
To start, you will have to install the JDK.
You can do this by running the installer.
During the installation, you will need to select the directory where the JDK will be installed – then you will need to create the JAVA HOME environment variable.
You can see all this in Part 7 – what is a Servlet.
There is a section “Launching the Tomcat WEB server”.
So use this information.
By the way, Tomcat can be installed immediately after the JDK.
Despite the fact that it describes the installation of an earlier version – in general, nothing has changed much.
Now let's start installing and configuring NetBeans.
In general, there is nothing complicated in the installation – the only thing that can cause any thoughts is setting up the JDK.
But usually NetBeans finds it itself (I very much suspect that it uses the JAVA HOME variable).
Also, some questions about configuring NetBeans can be found in Part 11 Application Server and Enterprise Java Beans
The only thing we will definitely need is to configure the library package.
In order not to connect all the JAR files separately each time, we will create a library in which we will put all the necessary jars as needed.
To create our library, run NetBeans.
Then select menu Tools->Libraries.
A form for configuring libraries will appear.
Click the “New library... " button and enter the name of our library in the form – StudentLibrary.
After that, click OK.
Now we have a library where we can add our JAR files.
Which is very convenient.
Now it will be enough for us to install a link to our library in the project and the project will get access to all the JAR files that are in it.
I think that you have guessed how to use the buttons for editing the contents of the library.
they are located on the right side of the form.
Note: Be sure to put at least some JAR in our library before closing the form.
Empty libraries are not saved !!!
The final step is to connect the library to the project.
In general, there is nothing complicated here either.
Right - click on the Libraries section in the window with the project structure and select "Add Library..." in it.
Then choose our wonderful library.
In general, that's all.
What is also important to note is that the system automatically tracks changes in our library.
If we add a new JAR file, this file will immediately be displayed on the structure of the files used.
As you can see in the picture – there are now two files in the library.
I just added a new JAR.
Required Libraries
All the libraries needed for the project "Student Personnel Department" are located HERE
For the current project, these libraries will be enough for us.
You can download it right here
antlr 2.7.6.jar
commons collections 3.1.jar
dom4j 1.6.1.jar
hibernate3.jar
javassist 3.4.GA.jar
jta 1.1.jar
log4j 1.2.15.jar
mysqlJDBC 3.1.13.jar
slf4j api 1.5.3.jar
slf4j log4j12-1.5.3.jar
So the contents of the StudentsLibrary library should look something like this:
In the future, I will not dwell on the libraries in such detail – I will just give a list of them and you will have to install everything yourself.
I think you can handle it.
Hibernate – the first application
Since our database includes several tables and besides it has complex relationships, we will take the first steps with one table – I think it will be easier and clearer this way.
After we see and try simple things, it will be easier for us to build a complete application.
As I have already said, Hibernate includes at least two important things – the parameters of the database connection and the description (mapping) of classes relative to tables.
Hibernate stores this data in configuration files, which we will consider using the example of just one table – PROFESSION.
It is not complicated for us and it does not require any other tables to create it.
She is our reference.
So run MySQL, run the SQL script.
Who does not know how to do this see the previous part Part 15 – A new data structure
So, let's create a new project.
Menu File->New Project.
In the form, select the Java project -> Java Application.
On the next screen, select the directory where our project will be located.
Pay attention to the checkboxes at the bottom - put them in accordance with the drawing.
Now I will give the structure of the files that we will use in our small project.
All of them are located in the scr folder of our project.
hibernate.cfg.xml – The Hibernate Main configuration file.java – although it has such a proud name, we only need it to launch our Profession application.a java class that stores data from a table.
It would be more accurate to say the data of one row of the table.
Profession.hbm.xml – a file that contains a description of how the Profession class is mapped to the HibernateUtil PROFESSION table.java is an auxiliary class for initializing the Hibernate system.
Its name is already so well established (it was given in the earliest versions of the documentation) that it is almost standard.
Although life may be different.
But we will not stand out in this case
Pay attention to the file hibernate.cfg.xml.
It is located right at the root of the scr directory.
You can sort out the position of the others yourself.
And now we will gradually analyze all the files that we have presented here.
Let's start with the file hibernate.cfg.xml.
hibernate.cfg.xml
<?xml version='1.0' encoding='utf 8'?
> <!DOCTYPE hibernate configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://hibernate.sourceforge.net/hibernate configuration 3.0.dtd">
<hibernate configuration>
<session factory>
<!-- Database connection settings --> <property name="connection.driver class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://127.0.0.1:3306/db applicant</property> <property name="connection.username">root</property> <property name="connection.password">root</property>
<!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
<!-- JDBC connection pool (use the built in) --> <property name="connection.pool size">1</property>
<!-- Enable Hibernate's automatic session context management --> <property name="current session context class">thread</property>
<!
-- Disable the second level cache --> <property name="cache.provider class">org.hibernate.cache.
NoCacheProvider</property>
<!-- Echo all executed SQL to stdout --> <property name="show sql">true</property>
<!-- Mapping files --> <mapping resource="students/entity/Profession.hbm.xml"/>
</session factory>
</hibernate configuration>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
<?xml version='1.0' encoding='utf 8'?
> <!DOCTYPE hibernate configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://hibernate.sourceforge.net/hibernate configuration 3.0.dtd">
<hibernate configuration>
<session factory>
<!-- Database connection settings --> <property name="connection.driver class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://127.0.0.1:3306/db applicant</property> <property name="connection.username">root</property> <property name="connection.password">root</property>
<!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
<!-- JDBC connection pool (use the built in) --> <property name="connection.pool size">1</property>
<!-- Enable Hibernate's automatic session context management --> <property name="current session context class">thread</property>
<!
-- Disable the second level cache --> <property name="cache.provider class">org.hibernate.cache.
NoCacheProvider</property>
<!-- Echo all executed SQL to stdout --> <property name="show sql">true</property>
<!-- Mapping files --> <mapping resource="students/entity/Profession.hbm.xml"/>
</session factory>
</hibernate configuration>
The principle here presents quite obvious things.
With a little effort, you will be able to figure out what and why yourself.
But I'll still run through the names.
connection.driver class is a fairly clear property.
It shows the driver class that is used to connect to the database.
This is our old friend (of course, if you have read the previous parts) - the driver for MySQL connection.
url is also obvious.
This is the URL for the connection to the database connection.
username – the login to the database connection.
password – the password to the database
Now we are moving on to more complex properties, although their complexity is probably somewhat exaggerated.
dialect – since Hibernate can work with different databases, and each has some features (primary key generation, page output, functions), we need to specify which database we are working with.
In this case, we have MySQL, which we specify connection.
pool size – this property shows how many connections to the database will be open at the same time.
As you've probably already heard, it's a fairly common technique to have multiple connections.
This increases the speed of the current session context class this property indicates how the control is performed.
I think that for now you do not need to go too deep into this issue cache.provider class – caching allows you to significantly speed up your work.
Frequently requested data can be stored in memory and not read it every time.
This method has its advantages speed, but also its disadvantages.
If someone changes the data bypassing Hibernate, they may not know about it.
In our case, we do not use the cache.
show sql this property indicates whether the SQL queries generated by Hibernte will be output to the console.
This can be very convenient during debugging
And finally, the last property, or more precisely, the tag mapping.
It is used to list all classes that have a connection with the database.
That is, if you want to use some class to link to some table, you must specify it here.
In this case, we have only one.
But we can analyze everything in detail, without being distracted by complex relationships.
The next interesting file is Profession.hbm.xml.
It describes how our Profession class is related to the PROFESSION table.
Let's first give the Profession file.java
Profession.java
package students.entity;
public class Profession {
private Long professionId; private String professionName;
public Long getProfessionId() { return professionId; }
public void setProfessionId(Long professionId) { this.professionId = professionId; }
public String getProfessionName() { return professionName; }
public void setProfessionName(String professionName) { this.professionName = professionName; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
package students.entity;
public class Profession {
private Long professionId; private String professionName;
public Long getProfessionId() { return professionId; }
public void setProfessionId(Long professionId) { this.professionId = professionId; }
public String getProfessionName() { return professionName; }
public void setProfessionName(String professionName) { this.professionName = professionName; } }
Here, in general, everything is very simple – there is a class with fields where you can store data.
Of course, you need to use the IDE tools that allow you to immediately generate set/get methods based on the typed fields.
Note: Get used to the correct naming of fields and set/get methods.
I think that you are already aware, but I will repeat myself
And now let's look at the file Profession.hbm.xml
<?xml version="1.0" encoding="UTF 8"?
> <!DOCTYPE hibernate mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate mapping 3.0.dtd">
<hibernate mapping package="students.entity"> <class name="Profession" table="profession"> <id name="professionId" column="profession id"> <generator class="native"/> </id> <property name="professionName" column="profession name"/> </class> </hibernate mapping>
1 2 3 4 5 6 7 8 9 10 11 12
<?xml version="1.0" encoding="UTF 8"?
> <!DOCTYPE hibernate mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate mapping 3.0.dtd">
<hibernate mapping package="students.entity"> <class name="Profession" table="profession"> <id name="professionId" column="profession id"> <generator class="native"/> </id> <property name="professionName" column="profession name"/> </class> </hibernate mapping>
Here we see a fairly simple description of the relationship between the table and the class.
Let's focus on some attributes and tags
package= "students.
entity” – this parameter specifies which package contains the class class name=” Profession”table=” profession” – this piece specifies which table which class is associated with id name=” professionId”column=” profession id" - this tag is specifically designed to describe the record id.
You just canot do without it.
The ID itself may not be a single field, but a composite one, but in our case we will not go so far into generator – here we specify a way to generate a unique value for the ID.
The word native indicates that the value will be generated by the means of the SQL server itself.
Here we can again look at the dialect parameter in файлеhibernate.cfg.xml.
It is he who gives an understanding of how to create an ID.
for example, for Oracle, this mechanism is different from MySQL.
In Oracle, you need to use a special sequence mechanism that creates unique values.
property name= "professionName" column= " profession name – - I think that this tag does not cause any difficulties for you.
It describes the relationship between a field in a table and a field in a class.
Here is a very simple form of the record, where the type is not specified (in this case, it is determined automatically), no restrictions are specified, etc.
As you probably already guessed, this file does not include all the possibilities of describing fields.
For a more detailed understanding, please refer to the documentation.
We donot have much left.
Now the HibernateUtil file is next in line.java
package students.utils;
import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static { try { // Create the SessionFactory from hibernate.cfg.xml sessionFactory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } }
public static SessionFactory getSessionFactory() { return sessionFactory; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
package students.utils;
import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static { try { // Create the SessionFactory from hibernate.cfg.xml sessionFactory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } }
public static SessionFactory getSessionFactory() { return sessionFactory; } }
I didnot even remove the comments – I have this file for several years.
And I just copy it sometimes.
As a result, there is also nothing particularly difficult here.
I will highlight two points:
The SessionFactory object is essentially a factory (creator) of sessions (connections) to the database.
We specified in файлеhibernate.cfg.xml all the necessary parameters that our SessionFactory object uses when creating the Configuration class – this class is used to load the Hibernate configuration
I think that the code should be quite clear how it all works.
When loading the class, the Hibernate configuration is read and all the necessary parameters allow you to create a SessionFactory object.
It is declared as static – i.e. it exists in a single instance.
And now you can access it to get a Hibernate session that allows you to make queries to the database.
And finally, our main file for launching and demonstrating Main.java
package students;
import students.entity.Profession; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import org.hibernate.Session; import students.utils.HibernateUtil;
public class Main {
// This method simply shows how the request is made when working at the JDBC level private void oldJDBC() { Connection connection = null; Statement statement = null; ResultSet rs = null; try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/db applicant", "root", "root"); statement = connection.createStatement(); List<Profession> list = new ArrayList<Profession>(); rs = statement.executeQuery("select profession id, profession name from professio n " + "order by profession name"); while (rs.next()) { Profession r = new Profession(); r.setProfessionId(rs.getLong("profession id")); r.setProfessionName(rs.getString("profession name")); list.add(r); System.out.println(r.getProfessionId() + ":" + r.getProfessionName()); } } catch (SQLException ex) { ex.printStackTrace(); System.err.println("Error SQL execution: " + ex.getMessage());
} catch (ClassNotFoundException ex) { ex.printStackTrace(); System.err.println("Error SQL execution: " + ex.getMessage()); } finally { try { if (rs != null) { rs.close(); } if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } catch (SQLException ex) { ex.printStackTrace(); System.err.println("Error: " + ex.getMessage()); } } }
// Метод добавляет новую запись в таблицу PROFESSION private void addProfession(String name) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); Profession r= new Profession(); r.setProfessionName(name); session.save(r); session.getTransaction().commit(); }
// Метод возвращает список профессий private List<Profession> listProfession() { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); List<Profession> result = session.createQuery("from Profession order by professionName").list(); session.getTransaction().commit(); return result; }
// Метод удаляет по очереди все записи, которые ему переданы в виде списка private void deleteProfessions(List<Profession> result) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); for(Profession p : result) { System.out.println("Delete:"+p.getProfessionId()+":"+p.getProfessionName()); session.delete(p); //session.flush(); } session.getTransaction().commit(); }
// Методу удаляет одну запись private void deleteEntity(Object o) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); session.delete(o); session.flush(); session.getTransaction().commit(); }
public static void main(String[] args) { Main main = new Main();
// Вызов "старого стиля" main.oldJDBC();
// Добавление новых профессий main.addProfession("Profession 1"); main.addProfession("Profession 2"); main.addProfession("Profession 3"); main.addProfession("Profession 4"); main.addProfession("Profession 5");
// Вариант вызова списка List<Profession> result = main.listProfession();
// Вариант вызова удаления одной записи result = main.listProfession(); main.deleteEntity(result.get(0));
// Вариант вызова списка и последующее удаление result = main.listProfession(); main.deleteProfessions(result); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
package students;
import students.entity.Profession; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import org.hibernate.Session; import students.utils.HibernateUtil;
public class Main {
// Данный метод просто показывает, как делается запрос при работе на уровне JDBC private void oldJDBC() { Connection connection = null; Statement statement = null; ResultSet rs = null; try { Clas
