📜 ⬆️ ⬇️

Hibernate Basics



I want to begin by thanking the person who threw karma yesterday, allowing me to write to my personal blog.

I thought for a long time about what to write my “first” topic ... It was not for nothing that I took the first word in quotes, since the first topic was already in fact, the experience was unfortunately unsuccessful - the matter ended with a ban. Decided not to copy-paste anymore. Confidence that it is necessary to write something of their own, gave this one topic . I decided firmly - let it be rare, but I will write myself.
')
Well, we go further!

Most recently, by the nature of my activity, I had to face such a concept as ORM - (eng. Object-relational mapping). In a nutshell, ORM is the mapping of objects from an object-oriented language into relational database structures. It is the objects, such as they are, with all the fields, values, relationships m / y each other.

The ORM solution for the Java language is Hibernate technology, which not only takes care of associating Java classes with database tables (and Java data types into SQL data types), but also provides tools for automatically building queries and extracting data and can significantly reduce the time development, which is usually spent on manually writing SQL and JDBC code. Hibernate generates SQL calls and frees the developer from manually processing the resulting dataset and converting objects, keeping the application portable to all SQL databases.

So, we have the task to write a small application that would carry out a simple interaction with the database, using Hibernate technology.

A little thought, I decided to write the so-called "Virtual fleet". The essence of the park is this: there are buses, there are routes and there are drivers. Buses and routes are connected by a one-to-many relationship, i.e. on one route can ride several buses at once. Drivers and buses are related to many to many, i.e. one driver can drive different buses and one bus can drive different drivers. It seems nothing complicated.
Here is the database schema.

For quality, do not scold - there was not a normal tool for drawing plates near at hand ...
Here is a link to the dump , taken from the base, suddenly someone decides to raise the whole thing :)
Getting to the code. First, we need to describe the classes of our entities, i.e. class bus, driver and route.
Class bus.
package logic;

import java.util.Set;
import java.util.HashSet;

public class Bus {
private Long id;
private String number;
private Set drivers = new HashSet ();
private Long route_id;

public Bus () {
}
public void setId (Long id) {
this .id = id;
}
public void setNumber ( String number) {
this .number = number;
}
public void setDrivers (Set drivers) {
this .drivers = drivers;
}
public void setRoute_id (Long route_id) {
this .route_id = route_id;
}
public Long getId () {
return id;
}
public String getNumber () {
return number;
}
public Set getDrivers () {
return drivers;
}
public Long getRoute_id () {
return route_id;
}
} * This source code was highlighted with Source Code Highlighter .

Class driver.
package logic;

import java.util.Set;
import java.util.HashSet;

public class Driver {
private Long id;
private String name;
private String surname;
private int age;
private Set busses = new HashSet ();

public Driver () {
}
public void setBusses (Set busses) {
this .busses = busses;
}
public Set getBusses () {
return busses;
}
public void setId (Long id) {
this .id = id;
}
public void setName ( String name) {
this .name = name;
}
public void setSurname ( String surname) {
this .surname = surname;
}
public void setAge ( int age) {
this .age = age;
}
public Long getId () {
return id;
}
public String getName () {
return name;
}
public String getSurname () {
return surname;
}
public int getAge () {
return age;
}
} * This source code was highlighted with Source Code Highlighter .

And class route.
package logic;

import java.util.Set;
import java.util.HashSet;

public class Route {
private Long id;
private String name;
private int number;
private Set busses = new HashSet ();

public Route () {
}
public void setId (Long id) {
this .id = id;
}
public void setName ( String name) {
this .name = name;
}
public void setNumber ( int number) {
this .number = number;
}
public void setBusses (Set busses) {
this .busses = busses;
}
public Long getId () {
return id;
}
public String getName () {
return name;
}
public int getNumber () {
return number;
}
public Set getBusses () {
return busses;
}
} * This source code was highlighted with Source Code Highlighter .

Note that all entity classes must comply with Java naming conventions , i.e. they must have getters, setters, and a default constructor. Nothing complicated :)

Now for our classes it is necessary to describe the mapping as xml files, these files will be responsible for the interaction of our objects with Hibernate and with the database.
Bus.hbm.xml
< hibernate-mapping >
< class name = "logic.Bus" table = "busses" >
< id column = "bus_id" name = "id" type = "java.lang.Long" >
< generator class = "increment" />
</ id >
< property column = "number" name = "number" type = "java.lang.String" />

< set name = "drivers" table = "busDriver" lazy = "false" >
< key column = "bus_id" />
< many-to-many column = "driver_id" class = "logic.Driver" />
</ set >

</ class >
</ hibernate-mapping > * This code was highlighted with the Source Code Highlighter .


Driver.hbm.xml
< hibernate-mapping >
< class name = "logic.Driver" table = "drivers" >
< id column = "driver_id" name = "id" type = "java.lang.Long" >
< generator class = "increment" />
</ id >
< property column = "name" name = "name" type = "java.lang.String" />
< property column = "surname" name = "surname" type = "java.lang.String" />
< property column = "age" name = "age" type = "java.lang.Integer" />

< set name = "busses" table = "busDriver" lazy = "false" >
< key column = "driver_id" />
< many-to-many column = "bus_id" class = "logic.Bus" />
</ set >

</ class >
</ hibernate-mapping > * This code was highlighted with the Source Code Highlighter .

Route.hbm.xml
< hibernate-mapping >
< class name = "logic.Route" table = "routes" >
< id column = "route_id" name = "id" type = "java.lang.Long" >
< generator class = "increment" />
</ id >
< property column = "name" name = "name" type = "java.lang.String" />
< property column = "number" name = "number" type = "java.lang.Integer" />

< set name = "busses" lazy = "false" >
< key column = "route_id" />
< one-to-many class = "logic.Bus" />
</ set >

</ class >
</ hibernate-mapping > * This code was highlighted with the Source Code Highlighter .

Now let's take a little look at these xml pasta :)


Now we will create the main configuration file hibernate.cfg.xml , the file from which it will pull all the information it needs.
< hibernate-configuration >

< session-factory >
< property name = "connection.url" > jdbc: mysql: // localhost / autopark </ property >
< property name = "connection.driver_class" > com.mysql.jdbc.Driver </ property >
< property name = "connection.username" > root </ property >
< property name = "connection.password" />
< property name = "connection.pool_size" > 1 </ property >
< property name = "current_session_context_class" > thread </ property >
< property name = "show_sql" > true </ property >
< property name = "dialect" > org.hibernate.dialect.MySQL5Dialect </ property >

< mapping resource = "logic / Bus.hbm.xml" />
< mapping resource = "logic / Driver.hbm.xml" />
< mapping resource = "logic / Route.hbm.xml" />

</ session-factory >

</ hibernate-configuration > This source code was highlighted with Source Code Highlighter .

Here I will not particularly go into the explanation, I think many people understand everything :) I will say that you only need to remember to add the mapping tag at the end and specify the configuration files of your beans as a parameter resources .

Now we will create a class that will hack our config file and return us an object of type SessionFactory , which is responsible for creating a hibernate session.
package util;

import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;

public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new Configuration (). configure (). buildSessionFactory ();
} catch (Throwable ex) {
System.err.println ( “Initial SessionFactory creation failed.” + Ex);
throw new ExceptionInInitializerError (ex);
}
}

public static SessionFactory getSessionFactory () {
return sessionFactory;
}
} * This source code was highlighted with Source Code Highlighter .


Now we have to deal with the interaction of our application with the database. To do this, for each class-entity, we define an interface containing a set of necessary methods (I will give only one interface and one of its implementations, interfaces and implementations for other classes like these.)
package DAO;

import logic.Bus;
import logic.Driver;
import logic.Route;

import java.util.Collection;
import java.sql.SQLException;

public interface BusDAO {
public void addBus (Bus bus) throws SQLException;
public void updateBus (Long bus_id, Bus bus) throws SQLException;
public Bus getBusById (Long bus_id) throws SQLException;
public Collection getAllBusses () throws SQLException;
public void deleteBus (Bus bus) throws SQLException;
public Collection getBussesByDriver (Driver driver) throws SQLException;
public Collection getBussesByRoute (Route route) throws SQLException;

} * This source code was highlighted with Source Code Highlighter .


Now we define the implementation of this interface in the class BusDAOImpl
package DAO.Impl;

import DAO.BusDAO;
import logic.Bus;
import logic.Driver;
import logic.Route;
import java.sql.SQLException;
import java.util.Collection;
import java.util. ArrayList ;
import java.util. List ;
import util.HibernateUtil;
import javax.swing. *;
import org.hibernate.Session;
import org.hibernate.Query;

public class BusDAOImpl implements BusDAO {

public void addBus (Bus bus) throws SQLException {
Session session = null ;
try {
session = HibernateUtil.getSessionFactory (). openSession ();
session.beginTransaction ();
session.save (bus);
session.getTransaction (). commit ();
} catch (Exception e) {
JOptionPane.showMessageDialog ( null , e.getMessage (), "Error inserting" , JOptionPane.OK_OPTION);
} finally {
if (session! = null && session.isOpen ()) {

session.close ();
}
}
}

public void updateBus (Long bus_id, Bus bus) throws SQLException {
Session session = null ;
try {
session = HibernateUtil.getSessionFactory (). openSession ();
session.beginTransaction ();
session.update (bus);
session.getTransaction (). commit ();
} catch (Exception e) {
JOptionPane.showMessageDialog ( null , e.getMessage (), "Error inserting" , JOptionPane.OK_OPTION);
} finally {
if (session! = null && session.isOpen ()) {
session.close ();
}
}
}

public Bus getBusById (Long bus_id) throws SQLException {
Session session = null ;
Bus bus = null ;
try {
session = HibernateUtil.getSessionFactory (). openSession ();
bus = (Bus) session.load (Bus. class , bus_id);
} catch (Exception e) {
JOptionPane.showMessageDialog ( null , e.getMessage (), "Error 'findById'" , JOptionPane.OK_OPTION);
} finally {
if (session! = null && session.isOpen ()) {
session.close ();
}
}
return bus;
}

public Collection getAllBusses () throws SQLException {
Session session = null ;
List busses = new ArrayList <Bus> ();
try {
session = HibernateUtil.getSessionFactory (). openSession ();
busses = session.createCriteria (Bus. class ) .list ();
} catch (Exception e) {
JOptionPane.showMessageDialog ( null , e.getMessage (), "Error 'getAll'" , JOptionPane.OK_OPTION);
} finally {
if (session! = null && session.isOpen ()) {
session.close ();
}
}
return busses;
}

public void deleteBus (Bus bus) throws SQLException {
Session session = null ;
try {
session = HibernateUtil.getSessionFactory (). openSession ();
session.beginTransaction ();
session.delete (bus);
session.getTransaction (). commit ();
} catch (Exception e) {
JOptionPane.showMessageDialog ( null , e.getMessage (), "Error deleting" , JOptionPane.OK_OPTION);
} finally {
if (session! = null && session.isOpen ()) {
session.close ();
}
}
}

public Collection getBussesByDriver (Driver driver) throws SQLException {
Session session = null ;
List busses = new ArrayList <Bus> ();
try {
session = HibernateUtil.getSessionFactory (). getCurrentSession ();
session.beginTransaction ();
Long driver_id = driver.getId ();
Query query = session.createQuery (
"select b"
+ "from Bus b INNER JOIN b.drivers driver"
+ "where driver.id =: driverId"
)
.setLong ( "driverId" , driver_id);
busses = ( List <Bus>) query.list ();
session.getTransaction (). commit ();

} finally {
if (session! = null && session.isOpen ()) {
session.close ();
}
}
return busses;
}

public Collection getBussesByRoute (Route route) {
Session session = null ;
List busses = new ArrayList <Bus> ();
try {
session = HibernateUtil.getSessionFactory (). getCurrentSession ();
session.beginTransaction ();
Long route_id = route.getId ();
Query query = session.createQuery ( “from Bus where route_id =: routeId„ ) .setLong ( “routeId” , route_id);
busses = ( List <Bus>) query.list ();
session.getTransaction (). commit ();

} finally {
if (session! = null && session.isOpen ()) {
session.close ();
}
}
return busses;
}

} * This source code was highlighted with Source Code Highlighter .


I would also say that the implementations of DriverDAOimpl and RouteDAO Impl will be similar to this one.
Of greatest interest to us are the two latter methods, take a closer look at them. How do you communicate with the base? From the SessionFactory object, a new session is created or the current session is obtained, why the transaction starts, the necessary actions are performed, the transaction is committed and the session is closed. It seems to be nothing complicated :) Pay attention to the syntax for the database request. This is the so-called HQL (Hibernate Query Language). HQL is an object-oriented query language, its capabilities are wide, but I’m not so much mastered yet :) Besides save , load , update , delete and HQL , you can also use regular SQL . For example:
String query = "SELECT driver_id, name, surname, age FROM drivers";
List drivers = new ArrayList();
drivers = (List) session.createSQLQuery(query).list();



, DAO , .
public class Factory {

private static BusDAO busDAO = null ;
private static DriverDAO driverDAO = null ;
private static RouteDAO routeDAO = null ;
private static Factory instance = null ;

public static synchronized Factory getInstance(){
if (instance == null ){
instance = new Factory();
}
return instance;
}

public BusDAO getBusDAO(){
if (busDAO == null ){
busDAO = new BusDAOImpl();
}
return busDAO;
}

public DriverDAO getDriverDAO(){
if (driverDAO == null ){
driverDAO = new DriverDAOImpl();
}
return driverDAO;
}

public RouteDAO getRouteDAO(){
if (routeDAO == null ){
routeDAO = new RouteDAOImpl();
}
return routeDAO;
}
}
* This source code was highlighted with Source Code Highlighter .

- , , , . , , , , :)
public class Main {
public static void main( String [] args) throws SQLException {

Collection routes = Factory.getInstance().getRouteDAO().getAllRoutes();
Iterator iterator = routes.iterator();
System. out .println( "======== =========" );
while (iterator.hasNext()) {
Route route = (Route) iterator.next();
System. out .println( " : " + route.getName() + " : " + route.getNumber());
Collection busses = Factory.getInstance().getBusDAO().getBussesByRoute(route);
Iterator iterator2 = busses.iterator();
while (iterator2.hasNext()) {
Bus bus = (Bus) iterator2.next();
System. out .println( " â„– " + bus.getNumber());

}
}

Collection busses = Factory.getInstance().getBusDAO().getAllBusses();
iterator = busses.iterator();
System. out .println( "======== =========" );
while (iterator.hasNext()) {
Bus bus = (Bus) iterator.next();
Collection drivers = Factory.getInstance().getDriverDAO().getDriversByBus(bus);
Iterator iterator2 = drivers.iterator();
System. out .println( " â„– " + bus.getNumber());
while (iterator2.hasNext()) {
Driver driver = (Driver) iterator2.next();
System. out .println( " : " + driver.getName() + " : " + driver.getSurname());

}
}

}
}
* This source code was highlighted with Source Code Highlighter .
, , GUI Web- , :)

PS . , 100%- , , , - .

PSS .
String query = "SELECT driver_id, name, surname, age FROM drivers";
List drivers = new ArrayList();
drivers = (List) session.createSQLQuery(query).list();



, DAO , .
public class Factory {

private static BusDAO busDAO = null ;
private static DriverDAO driverDAO = null ;
private static RouteDAO routeDAO = null ;
private static Factory instance = null ;

public static synchronized Factory getInstance(){
if (instance == null ){
instance = new Factory();
}
return instance;
}

public BusDAO getBusDAO(){
if (busDAO == null ){
busDAO = new BusDAOImpl();
}
return busDAO;
}

public DriverDAO getDriverDAO(){
if (driverDAO == null ){
driverDAO = new DriverDAOImpl();
}
return driverDAO;
}

public RouteDAO getRouteDAO(){
if (routeDAO == null ){
routeDAO = new RouteDAOImpl();
}
return routeDAO;
}
}
* This source code was highlighted with Source Code Highlighter .

- , , , . , , , , :)
public class Main {
public static void main( String [] args) throws SQLException {

Collection routes = Factory.getInstance().getRouteDAO().getAllRoutes();
Iterator iterator = routes.iterator();
System. out .println( "======== =========" );
while (iterator.hasNext()) {
Route route = (Route) iterator.next();
System. out .println( " : " + route.getName() + " : " + route.getNumber());
Collection busses = Factory.getInstance().getBusDAO().getBussesByRoute(route);
Iterator iterator2 = busses.iterator();
while (iterator2.hasNext()) {
Bus bus = (Bus) iterator2.next();
System. out .println( " â„– " + bus.getNumber());

}
}

Collection busses = Factory.getInstance().getBusDAO().getAllBusses();
iterator = busses.iterator();
System. out .println( "======== =========" );
while (iterator.hasNext()) {
Bus bus = (Bus) iterator.next();
Collection drivers = Factory.getInstance().getDriverDAO().getDriversByBus(bus);
Iterator iterator2 = drivers.iterator();
System. out .println( " â„– " + bus.getNumber());
while (iterator2.hasNext()) {
Driver driver = (Driver) iterator2.next();
System. out .println( " : " + driver.getName() + " : " + driver.getSurname());

}
}

}
}
* This source code was highlighted with Source Code Highlighter .
, , GUI Web- , :)

PS . , 100%- , , , - .

PSS .
String query = "SELECT driver_id, name, surname, age FROM drivers";
List drivers = new ArrayList();
drivers = (List) session.createSQLQuery(query).list();



, DAO , .
public class Factory {

private static BusDAO busDAO = null ;
private static DriverDAO driverDAO = null ;
private static RouteDAO routeDAO = null ;
private static Factory instance = null ;

public static synchronized Factory getInstance(){
if (instance == null ){
instance = new Factory();
}
return instance;
}

public BusDAO getBusDAO(){
if (busDAO == null ){
busDAO = new BusDAOImpl();
}
return busDAO;
}

public DriverDAO getDriverDAO(){
if (driverDAO == null ){
driverDAO = new DriverDAOImpl();
}
return driverDAO;
}

public RouteDAO getRouteDAO(){
if (routeDAO == null ){
routeDAO = new RouteDAOImpl();
}
return routeDAO;
}
}
* This source code was highlighted with Source Code Highlighter .

- , , , . , , , , :)
public class Main {
public static void main( String [] args) throws SQLException {

Collection routes = Factory.getInstance().getRouteDAO().getAllRoutes();
Iterator iterator = routes.iterator();
System. out .println( "======== =========" );
while (iterator.hasNext()) {
Route route = (Route) iterator.next();
System. out .println( " : " + route.getName() + " : " + route.getNumber());
Collection busses = Factory.getInstance().getBusDAO().getBussesByRoute(route);
Iterator iterator2 = busses.iterator();
while (iterator2.hasNext()) {
Bus bus = (Bus) iterator2.next();
System. out .println( " â„– " + bus.getNumber());

}
}

Collection busses = Factory.getInstance().getBusDAO().getAllBusses();
iterator = busses.iterator();
System. out .println( "======== =========" );
while (iterator.hasNext()) {
Bus bus = (Bus) iterator.next();
Collection drivers = Factory.getInstance().getDriverDAO().getDriversByBus(bus);
Iterator iterator2 = drivers.iterator();
System. out .println( " â„– " + bus.getNumber());
while (iterator2.hasNext()) {
Driver driver = (Driver) iterator2.next();
System. out .println( " : " + driver.getName() + " : " + driver.getSurname());

}
}

}
}
* This source code was highlighted with Source Code Highlighter .
, , GUI Web- , :)

PS . , 100%- , , , - .

PSS .
String query = "SELECT driver_id, name, surname, age FROM drivers";
List drivers = new ArrayList();
drivers = (List) session.createSQLQuery(query).list();



, DAO , .
public class Factory {

private static BusDAO busDAO = null ;
private static DriverDAO driverDAO = null ;
private static RouteDAO routeDAO = null ;
private static Factory instance = null ;

public static synchronized Factory getInstance(){
if (instance == null ){
instance = new Factory();
}
return instance;
}

public BusDAO getBusDAO(){
if (busDAO == null ){
busDAO = new BusDAOImpl();
}
return busDAO;
}

public DriverDAO getDriverDAO(){
if (driverDAO == null ){
driverDAO = new DriverDAOImpl();
}
return driverDAO;
}

public RouteDAO getRouteDAO(){
if (routeDAO == null ){
routeDAO = new RouteDAOImpl();
}
return routeDAO;
}
}
* This source code was highlighted with Source Code Highlighter .

- , , , . , , , , :)
public class Main {
public static void main( String [] args) throws SQLException {

Collection routes = Factory.getInstance().getRouteDAO().getAllRoutes();
Iterator iterator = routes.iterator();
System. out .println( "======== =========" );
while (iterator.hasNext()) {
Route route = (Route) iterator.next();
System. out .println( " : " + route.getName() + " : " + route.getNumber());
Collection busses = Factory.getInstance().getBusDAO().getBussesByRoute(route);
Iterator iterator2 = busses.iterator();
while (iterator2.hasNext()) {
Bus bus = (Bus) iterator2.next();
System. out .println( " â„– " + bus.getNumber());

}
}

Collection busses = Factory.getInstance().getBusDAO().getAllBusses();
iterator = busses.iterator();
System. out .println( "======== =========" );
while (iterator.hasNext()) {
Bus bus = (Bus) iterator.next();
Collection drivers = Factory.getInstance().getDriverDAO().getDriversByBus(bus);
Iterator iterator2 = drivers.iterator();
System. out .println( " â„– " + bus.getNumber());
while (iterator2.hasNext()) {
Driver driver = (Driver) iterator2.next();
System. out .println( " : " + driver.getName() + " : " + driver.getSurname());

}
}

}
}
* This source code was highlighted with Source Code Highlighter .
, , GUI Web- , :)

PS . , 100%- , , , - .

PSS .
String query = "SELECT driver_id, name, surname, age FROM drivers";
List drivers = new ArrayList();
drivers = (List) session.createSQLQuery(query).list();



, DAO , .
public class Factory {

private static BusDAO busDAO = null ;
private static DriverDAO driverDAO = null ;
private static RouteDAO routeDAO = null ;
private static Factory instance = null ;

public static synchronized Factory getInstance(){
if (instance == null ){
instance = new Factory();
}
return instance;
}

public BusDAO getBusDAO(){
if (busDAO == null ){
busDAO = new BusDAOImpl();
}
return busDAO;
}

public DriverDAO getDriverDAO(){
if (driverDAO == null ){
driverDAO = new DriverDAOImpl();
}
return driverDAO;
}

public RouteDAO getRouteDAO(){
if (routeDAO == null ){
routeDAO = new RouteDAOImpl();
}
return routeDAO;
}
}
* This source code was highlighted with Source Code Highlighter .

- , , , . , , , , :)
public class Main {
public static void main( String [] args) throws SQLException {

Collection routes = Factory.getInstance().getRouteDAO().getAllRoutes();
Iterator iterator = routes.iterator();
System. out .println( "======== =========" );
while (iterator.hasNext()) {
Route route = (Route) iterator.next();
System. out .println( " : " + route.getName() + " : " + route.getNumber());
Collection busses = Factory.getInstance().getBusDAO().getBussesByRoute(route);
Iterator iterator2 = busses.iterator();
while (iterator2.hasNext()) {
Bus bus = (Bus) iterator2.next();
System. out .println( " â„– " + bus.getNumber());

}
}

Collection busses = Factory.getInstance().getBusDAO().getAllBusses();
iterator = busses.iterator();
System. out .println( "======== =========" );
while (iterator.hasNext()) {
Bus bus = (Bus) iterator.next();
Collection drivers = Factory.getInstance().getDriverDAO().getDriversByBus(bus);
Iterator iterator2 = drivers.iterator();
System. out .println( " â„– " + bus.getNumber());
while (iterator2.hasNext()) {
Driver driver = (Driver) iterator2.next();
System. out .println( " : " + driver.getName() + " : " + driver.getSurname());

}
}

}
}
* This source code was highlighted with Source Code Highlighter .
, , GUI Web- , :)

PS . , 100%- , , , - .

PSS .

Source: https://habr.com/ru/post/29694/


All Articles