Skip to content

Hibernate (конфигурация в стиле xml)

Синопсис

В этом посте создадим простое приложение, которое будет работать с базой данных через фреймворк hibernate и выводить все имеющиеся данные которые хранятся в базе данных. Суть приложения точно такая же как я описывал в посте Работа с базой данных через JDBC, только вместо JDBC теперь будем использовать фреймворк hibernate. Hibernate — это средство доступа к данным, его идея заключается в том, что программа оперирует не записями и полями, а объектами. То есть мы работаем с базой данных в стиле ООП, когда из базы данных мы вытаскиваем уже готовые объекты, а если таблицы в базе данных связаны между собой, то объекты будут содержать в себе массивы ассоциированных с ним объектов, то есть если мы достаем объект склад, то hibernate сформирует запрос и свяжет таблицу склады с таблицей товары и выдаст нам объект Склад который будет содержать в себе массив объектов Товар, потому что в базе данных таблицы Склады и Товары связаны по внешнему ключу.
Конфигурировать hibernate будем старым способом, то есть используя xml файлы с расширением .hbm.xml, а в следующем посте мы переделаем на конфигурации в стиле аннотаций.

Похожие посты

  • Работа с базой данных через JDBC
  • Hibernate (конфигурация в стиле аннотации)
  • Hibernate (конфигурация spring)
  • Основы JPA
  • JPA и Spring
  • Простой Spring MVC
  • Что нам потребуется

    1. JDK
    2. Так как будем собирать приложение вручную, то нам понадобятся библиотеки, ссылка на которые чуть ниже
    3. Shell скрипт, который мы напишем сами

    Библиотеки можно взять здесь:


    Весь проект можно взять с gitHub: https://github.com/dev-blogs/hibernate-without-annotations

    База данных

    База данных в этом примере такая же как в посте Работа с базой данных через JDBC. Там приводится ее структура и как ее поднять в MySQL. Для экономии места в этом посте я эти детали не привожу. Кто собирается все это дело компилировать и запускать, то убедитесь, что у вас установлена MySQL и засетаплена соответствующая база из того поста.

    Структура проекта

    После того как база данных подготовлена, возьмемся за кодирование. Билдить и запускать проект будем опять же из командной строки, хотя признаюсь этот проект я сначала создавал с помощью инструмена управления зависимостями maven, а то я бы долго мучался какие хибернейту нужны зависимости кроме самой библиотеки hibernate-3.1.3.jar, но об этом в следующем посте. А почему я этот проект собираю баш-скриптами а не мавеном, потому что при обучении нужно пройти все стадии и понимать, что происходит на каждой из них, а потом уже пользоваться мавеном.
    А сейчас создайте проект представленной ниже структуры:

    hibernate
        ├──src
        │   ├─com
        │   │   └─dev
        │   │       └─blogs
        │   │           └─hibernate
        │   │               ├─App.java
        │   │               └─Factory.java
        │   ├─DAO
        │   │   ├─impl
        │   │   │   ├─ItemDAOImpl.java
        │   │   │   ├─ProviderDAOImpl.java
        │   │   │   └─WarehouseDAOImpl.java
        │   │   ├─ItemDAO.java
        │   │   ├─ProviderDAO.java
        │   │   └─WarehouseDAO.java
        │   ├─model
        │   │   ├─Item.java
        │   │   ├─Provider.java
        │   │   └─Warehouse.java
        │   └─util
        │       └─HibernateUtil.java
        ├──resources
        │   ├─hibernate.cfg.xml
        │   ├─Item.hbm.xml
        │   ├─Provider.hbm.xml
        │   └─Warehouse.hbm.xml
        ├──lib
        │   ├─antlr-2.7.6rc1.jar
        │   ├─asm-1.5.3.jar
        │   ├─asm-attrs-1.5.3.jar
        │   ├─cglib-2.1_3.jar
        │   ├─commons-collections-2.1.1.jar
        │   ├─commons-logging-1.0.4.jar
        │   ├─dom4j-1.6.1.jar
        │   ├─ehcache-1.1.jar
        │   ├─hibernate-3.1.3.jar
        │   ├─jta-1.0.1B.jar
        │   └─mysql-connector-java-5.1.34.jar
        └──build.sh
    

    Все перечисленные библиотеки можете взять по ссылке в самом начале поста, а сейчас пару слов как я вычислял какие библиотеки будут необходимы для хибернейт приложения, если мы строим приложение не прибегая к такому инструменту как мавен. Так вот, ответ заключатеся в том, что я все таки прибегал. Для этого я использовал тул STS — Spring Tool Suite или можно просто взять eclipse с мавенским плагином. Создаем мавенский проект и добавляем в pom.xml в раздел dependencies такую зависимость:

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate</artifactId>
        <version>3.1.3</version>
    </dependency>
    

    После этого maven подтянет не только библиотеку hibernate-3.1.3.jar, но и все библиотеки от которых hibernate-3.1.3.jar зависит, в данном случае их всего 10 включая и саму библиотеку hibernate-3.1.3.jar. Для того чтобы проверить от каких библиотек зависит hibernate-3.1.3.jar кликаем на вкладку Dependency Hierarchy помчика (pom.xml) (все это надо делать в туле STS — Spring Tool Suite):
    1
    Смотрим на левую часть рисунка. Из нее видно, что библиотека hibernate-3.1.3.jar зависит еще от девяти бибилиотек, это commons-logging-1.0.4.jar, ehcache-1.1.jar, cglib-2.1_3.jar, asm-1.5.3.jar, asm-attrs-1.5.3.jar, commons-collections-2.1.1.jar, dom4j-1.6.1.jar, jta-1.0.1B.jar, antlr-2.7.6rc1.jar.
    Обратите внимание, что библиотеки mysql-connector-java-5.1.34.jar и junit.4.11 идут как отдельные зависисмости, это видно по смещению немножко влево отностильено остальных зависимостей, то есть к hibernate-3.1.3.jar отношения не имеют, но нужны приложению.
    Теперь, после того как соберем приложение, в том же каталоге должен появиться каталог build со следующей структурой:

    build
        ├─com
        │   └─dev
        │       └─blogs
        │           └─hibernate
        │               ├─App.class
        │               └─Factory.class
        ├─DAO
        │   ├─impl
        │   │   ├─ItemDAOImpl.class
        │   │   ├─ProviderDAOImpl.class
        │   │   └─WarehouseDAOImpl.class
        │   ├─ItemDAO.class
        │   ├─ProviderDAO.class
        │   └─WarehouseDAO.class
        ├─model
        │   ├─Item.class
        │   ├─Provider.class
        │   └─Warehouse.class
        └─util
            └─HibernateUtil.class
    

    Java code

    Начнем с классов предметной области. Всего в нашем приложении взаимодействовать между собой будет 3 объекта предметной области это Детали, Поставщик деталей и Склад где хранятся детали. Добавим эти классы:

    Item.java

    package model;
    
    import java.util.HashSet;
    import java.util.Set;
    
    public class Item {
    	private Long id;
    	private String name;
    	private Set<Provider> providers = new HashSet<Provider>();
    
    	public Long getId() {
    		return id;
    	}
    
    	public void setId(Long id) {
    		this.id = id;
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public Set<Provider> getProviders() {
    		return providers;
    	}
    
    	public void setProviders(Set<Provider> providers) {
    		this.providers = providers;
    	}
    }
    

    Provider.java

    package model;
    
    import java.util.HashSet;
    import java.util.Set;
    
    public class Provider {
    	private Long id;
    	private String name;
    	private Set<Item> items = new HashSet<Item>();
    
    	public Long getId() {
    		return id;
    	}
    
    	public void setId(Long id) {
    		this.id = id;
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public Set<Item> getItems() {
    		return items;
    	}
    
    	public void setItems(Set<Item> items) {
    		this.items = items;
    	}
    }
    

    Warehouse.java

    package model;
    
    import java.util.HashSet;
    import java.util.Set;
    
    public class Warehouse {
    	private Long id;
    	private String address;
    	private Set<Item> items = new HashSet<Item>();
    
    	public Long getId() {
    		return id;
    	}
    
    	public void setId(Long id) {
    		this.id = id;
    	}
    
    	public String getAddress() {
    		return address;
    	}
    
    	public void setAddress(String address) {
    		this.address = address;
    	}
    
    	public Set<Item> getItems() {
    		return items;
    	}
    
    	public void setItems(Set<Item> items) {
    		this.items = items;
    	}
    }
    

    После того как классы предметной области определены, определим слой доступа к данным, в котором будет реализована логика для обращения к логике отображающей структуры лежащей в основе реляционной базы данных на POJO объекты. Сначала определим для каждого объекта предметной области интерфейсы обращений к данным:

    ItemDAO.java

    package DAO;
    
    import java.sql.SQLException;
    import java.util.Collection;
    
    import model.Item;
    
    public interface ItemDAO {
    	public void addItem(Item item) throws SQLException;
    	public void updateItem(Item item) throws SQLException;
    	public Item getItemById(Long id) throws SQLException;
    	public Collection<Item> getAllItems() throws SQLException;
    	public void deleteItem(Item item) throws SQLException;
    }
    

    ProviderDAO.java

    package DAO;
    
    import java.sql.SQLException;
    import java.util.Collection;
    
    import model.Provider;
    
    public interface ProviderDAO {
    	public void addProvider(Provider provider) throws SQLException;
    	public void updateProvider(Provider provider) throws SQLException;
    	public Provider getProviderById(Long id) throws SQLException;
    	public Collection<Provider> getAllProviders() throws SQLException;
    	public void deleteProvider(Provider provider) throws SQLException;
    }
    

    WarehouseDAO

    package DAO;
    
    import java.sql.SQLException;
    import java.util.Collection;
    
    import model.Warehouse;
    
    public interface WarehouseDAO {
    	public void addWarehouse(Warehouse warehouse) throws SQLException;
    	public void updateWarehouse(Warehouse warehouse) throws SQLException;
    	public Warehouse getWarehouseById(Long id) throws SQLException;
    	public Collection<Warehouse> getAllWarehouses() throws SQLException;
    	public void deleteWarehouse(Warehouse warehouse) throws SQLException;
    }
    

    Далее реализуем интерфейсы доступа к данным:

    ItemDAOImpl.java

    package DAO.impl;
    
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.List;
    
    import model.Item;
    
    import org.hibernate.Session;
    
    import util.HibernateUtil;
    import DAO.ItemDAO;
    
    public class ItemDAOImpl implements ItemDAO {
    
    	public Collection<Item> getAllItems() throws SQLException {
    		Session session = null;
    		List<Item> items = new ArrayList<Item>();
    		try {
    			session = HibernateUtil.getSessionFactory().openSession();
    			items = session.createCriteria(Item.class).list();
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			if (session != null && session.isOpen()) {
    				session.close();
    			}
    		}
    		return items;
    	}
    
    	public void addItem(Item item) throws SQLException {
    		Session session = null;
    		try {
    			session = HibernateUtil.getSessionFactory().openSession();
    			session.beginTransaction();
    			session.save(item);
    			session.getTransaction().commit();
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			if (session != null && session.isOpen()) {
    				session.close();
    			}
    		}
    	}
    
    	public void updateItem(Item item) throws SQLException {
    		Session session = null;
    		try {
    			session = HibernateUtil.getSessionFactory().openSession();
    			session.beginTransaction();
    			session.update(item);
    			session.getTransaction().commit();
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			if (session != null && session.isOpen()) {
    				session.close();
    			}
    		}
    	}
    
    	public Item getItemById(Long id) throws SQLException {
    		Session session = null;
    		Item item = null;
    		try {
    			session = HibernateUtil.getSessionFactory().openSession();
    			item = (Item) session.load(Item.class, id);
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			if (session != null && session.isOpen()) {
    				session.close();
    			}
    		}
    		return item;
    	}
    
    	public void deleteItem(Item item) throws SQLException {
    		Session session = null;
    		try {
    			session = HibernateUtil.getSessionFactory().openSession();
    			session.beginTransaction();
    			session.delete(item);
    			session.getTransaction().commit();
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			if (session != null && session.isOpen()) {
    				session.close();
    			}
    		}
    	}
    }
    

    ProviderDAOImpl.java

    package DAO.impl;
    
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.List;
    
    import org.hibernate.Session;
    
    import util.HibernateUtil;
    import model.Item;
    import model.Provider;
    import DAO.ProviderDAO;
    
    public class ProviderDAOImpl implements ProviderDAO {
    
    	public void addProvider(Provider provider) throws SQLException {
    		Session session = null;
    		try {
    			session = HibernateUtil.getSessionFactory().openSession();
    			session.beginTransaction();
    			session.save(provider);
    			session.getTransaction().commit();
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			if (session != null && session.isOpen()) {
    				session.close();
    			}
    		}
    	}
    
    	public void updateProvider(Provider provider) throws SQLException {
    		Session session = null;
    		try {
    			session = HibernateUtil.getSessionFactory().openSession();
    			session.beginTransaction();
    			session.update(provider);
    			session.getTransaction().commit();
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			if (session != null && session.isOpen()) {
    				session.close();
    			}
    		}
    	}
    
    	public Provider getProviderById(Long id) throws SQLException {
    		Session session = null;
    		Provider provider = null;
    		try {
    			session = HibernateUtil.getSessionFactory().openSession();
    			provider = (Provider) session.load(Provider.class, id);
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			if (session != null && session.isOpen()) {
    				session.close();
    			}
    		}
    		return provider;
    		
    	}
    
    	public Collection<Provider> getAllProviders() throws SQLException {
    		Session session = null;
    		List<Provider> providers = new ArrayList<Provider>();
    		try {
    			session = HibernateUtil.getSessionFactory().openSession();
    			providers = session.createCriteria(Provider.class).list();
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			if (session != null && session.isOpen()) {
    				session.close();
    			}
    		}
    		return providers;
    	}
    
    	public void deleteProvider(Provider provider) throws SQLException {
    		Session session = null;
    		try {
    			session = HibernateUtil.getSessionFactory().openSession();
    			session.beginTransaction();
    			session.delete(provider);
    			session.getTransaction().commit();
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			if (session != null && session.isOpen()) {
    				session.close();
    			}
    		}
    	}
    }
    

    WarehouseDAOImpl.java

    package DAO.impl;
    
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.List;
    
    import org.hibernate.Session;
    
    import util.HibernateUtil;
    import model.Provider;
    import model.Warehouse;
    import DAO.WarehouseDAO;
    
    public class WarehouseDAOImpl implements WarehouseDAO {
    
    	public void addWarehouse(Warehouse warehouse) throws SQLException {
    		Session session = null;
    		try {
    			session = HibernateUtil.getSessionFactory().openSession();
    			session.beginTransaction();
    			session.save(warehouse);
    			session.getTransaction().commit();
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			if (session != null && session.isOpen()) {
    				session.close();
    			}
    		}
    	}
    
    	public void updateWarehouse(Warehouse warehouse) throws SQLException {
    		Session session = null;
    		try {
    			session = HibernateUtil.getSessionFactory().openSession();
    			session.beginTransaction();
    			session.update(warehouse);
    			session.getTransaction().commit();
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			if (session != null && session.isOpen()) {
    				session.close();
    			}
    		}
    	}
    
    	public Warehouse getWarehouseById(Long id) throws SQLException {
    		Session session = null;
    		Warehouse warehouse = null;
    		try {
    			session = HibernateUtil.getSessionFactory().openSession();
    			warehouse = (Warehouse) session.load(Warehouse.class, id);
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			if (session != null && session.isOpen()) {
    				session.close();
    			}
    		}
    		return warehouse;
    	}
    
    	public Collection<Warehouse> getAllWarehouses() throws SQLException {
    		Session session = null;
    		List<Warehouse> warehouses = new ArrayList<Warehouse>();
    		try {
    			session = HibernateUtil.getSessionFactory().openSession();
    			warehouses = session.createCriteria(Warehouse.class).list();
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			if (session != null && session.isOpen()) {
    				session.close();
    			}
    		}
    		return warehouses;
    	}
    
    	public void deleteWarehouse(Warehouse warehouse) throws SQLException {
    		Session session = null;
    		try {
    			session = HibernateUtil.getSessionFactory().openSession();
    			session.beginTransaction();
    			session.delete(warehouse);
    			session.getTransaction().commit();
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			if (session != null && session.isOpen()) {
    				session.close();
    			}
    		}
    	}
    }
    

    Factory.java

    package com.dev.blogs.hibernate;
    
    import DAO.ItemDAO;
    import DAO.ProviderDAO;
    import DAO.WarehouseDAO;
    import DAO.impl.ItemDAOImpl;
    import DAO.impl.ProviderDAOImpl;
    import DAO.impl.WarehouseDAOImpl;
    
    public class Factory {
    	private static Factory instance = null;
    	private static ItemDAO itemDAO = null;
    	private static ProviderDAO providerDAO = null;
    	private static WarehouseDAO warehouseDAO = null;
    	
    	public static synchronized Factory getInstance() {
    		if (instance == null) {
    			instance = new Factory();
    		}
    		return instance;
    	}
    	
    	public ItemDAO getItemDAO() {
    		if (itemDAO == null) {
    			itemDAO = new ItemDAOImpl();
    		}
    		return itemDAO;
    	}
    	
    	public ProviderDAO getProviderDAO() {
    		if (providerDAO == null) {
    			providerDAO = new ProviderDAOImpl();
    		}
    		return providerDAO;
    	}
    	
    	public WarehouseDAO getWarehouseDAO() {
    		if (warehouseDAO == null) {
    			warehouseDAO = new WarehouseDAOImpl();
    		}
    		return warehouseDAO;
    	}
    }
    

    HibernateUtil.java

    package util;
    
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    
    public class HibernateUtil {
    	private static final SessionFactory sessionFactory;
    	
    	static {
    		try {
    			sessionFactory = new Configuration().configure().buildSessionFactory();
    		} catch (Throwable e) {
    			System.err.println("Initial SessionFactory creation failed. " + e);
    			throw new ExceptionInInitializerError(e);
    		}
    	}
    	
    	public static SessionFactory getSessionFactory() {
    		return sessionFactory;
    	}
    }
    

    App.java

    App.java этот класс с которого будет запускаться приложение.

    package com.dev.blogs.hibernate;
    
    import java.sql.SQLException;
    import java.util.Collection;
    import java.util.Iterator;
    import java.util.Set;
    
    import model.Item;
    import model.Provider;
    import model.Warehouse;
    
    /**
     * hiberante
     *
     */
    public class App {
    	public static void main(String[] args) {
    		try {
    			Collection<Warehouse> warehouses = Factory.getInstance().getWarehouseDAO().getAllWarehouses();
    			Iterator<Warehouse> warehouseIterator = warehouses.iterator();
    			System.out.println("list of warehouses:");
    			while (warehouseIterator.hasNext()) {
    				Warehouse warehouse = (Warehouse) warehouseIterator.next();
    				System.out.println("warehouse number " + warehouse.getId() + ", address is " + warehouse.getAddress());
    				Collection<Item> items = warehouse.getItems();
    				Iterator<Item> itemIterator = items.iterator();
    				while (itemIterator.hasNext()) {
    					Item item = (Item) itemIterator.next();
    					System.out.println("    has " + item.getName() + ", id of this item is " + item.getId());
    					Set<Provider> providers = item.getProviders();
    					Iterator<Provider> providerIterator = providers.iterator();
    					while (providerIterator.hasNext()) {
    						Provider provider = (Provider) providerIterator.next();
    						System.out.println("         which is provided by " + provider.getName() + ", id of this provider is " + provider.getId());
    					}
    				}
    				System.out.println();
    			}
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}
    	}
    }
    

    Так как мы строим приложение в старом стиле то есть доаннатационных времен, то для того, чтобы рассказать хибернейту что с чем будем связывать, воспользуемся xml файлами:

    Item.hbm.xml

    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
    	<class name="model.Item" table="items">
    		<id column="id" name="id" type="java.lang.Long">
    			<generator class="increment" />
    		</id>
    		<property column="name" name="name" type="java.lang.String" />
    
    		<set name="providers" table="items_providers" lazy="false">
    			<key column="item_id" />
    			<many-to-many column="provider_id" class="model.Provider" />
    		</set>
    
    	</class>
    </hibernate-mapping>
    

    Provider.hbm.xml

    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
    	<class name="model.Provider" table="providers">
    		<id column="id" name="id" type="java.lang.Long">
    			<generator class="increment" />
    		</id>
    		<property column="name" name="name" type="java.lang.String" />
    
    		<set name="items" table="items_providers" lazy="false">
    			<key column="provider_id" />
    			<many-to-many column="item_id" class="model.Item" />
    		</set>
    
    	</class>
    </hibernate-mapping>
    

    Warehouse.hbm.xml

    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
    	<class name="model.Warehouse" table="warehouses">
    		<id column="id" name="id" type="java.lang.Long">
    			<generator class="increment" />
    		</id>
    		<property column="address" name="address" type="java.lang.String" />
    
    		<set name="items" lazy="false">
    			<key column="warehouse_id" />
    			<one-to-many class="model.Item" />
    		</set>
    	</class>
    </hibernate-mapping>
    

    И на последок добавам файл hibernate.cfg.xml где пропишим всю необходимые хибернейту конфигурацию, какая будет использоваться база, какой логин и пароль к этой базе и пр.

    hibernate.cfg.xml

    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    <hibernate-configuration>
    
      <session-factory>
        <property name="connection.url">jdbc:mysql://localhost/warehouse</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.username">user</property>
        <property name="connection.password">password</property>
        <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="Item.hbm.xml"/>
        <mapping resource="Provider.hbm.xml"/>
        <mapping resource="Warehouse.hbm.xml"/>
    
      </session-factory>
      
    </hibernate-configuration>
    

    Сборка и запуск проекта

    После того как все готово, последнее, что осталось сделать это собрать и выполнить приложение. Для этого в корень проекта добавляем скрипт build.sh, код которого приводится ниже, назначем его экзекьютэбл командой:

    sudo chmod +x build.sh
    

    Так же не забываем переделать его в батник, если делаете все на Windowsе($):

    build.sh

    PATH_TO_PROJECT=`pwd`
       
    # Удаляем каталог с предыдущим билдом
    if test -d $PATH_TO_PROJECT/build;
    then
        rm -rf $PATH_TO_PROJECT/build
    fi
        
    # Создаем новый каталог, куда будем помещать билд
    mkdir $PATH_TO_PROJECT/build
            
    # Компилируем проект в каталог build
    # Для компиляции необходима библиотека hibernate-3.1.3.jar
    # а так же все библиотеки, от которой она зависит
    javac -d build -cp .:lib/* src/main/java/DAO/impl/*.java
    src/main/java/DAO/*.java
    src/main/java/com/dev/blogs/hibernate/*.java
    src/main/java/model/*.java
    src/main/java/util/*.java
        
    # Выполняем приложение
    java -cp .:build:resources:lib/* com.dev.blogs.hibernate.App
    

    После того как скрипт добавлен и назначен выполняемым, осталось заранить его командой:

    ./build.sh
    

    Если после запуска скрипта вы увидите что-то похожее на это:

    Note: Some input files use unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.
    мар 09, 2015 5:11:12 PM org.hibernate.cfg.Environment <clinit>
    INFO: Hibernate 3.1.3
    мар 09, 2015 5:11:12 PM org.hibernate.cfg.Environment <clinit>
    INFO: hibernate.properties not found
    мар 09, 2015 5:11:12 PM org.hibernate.cfg.Environment <clinit>
    INFO: using CGLIB reflection optimizer
    мар 09, 2015 5:11:12 PM org.hibernate.cfg.Environment <clinit>
    INFO: using JDK 1.4 java.sql.Timestamp handling
    мар 09, 2015 5:11:12 PM org.hibernate.cfg.Configuration configure
    INFO: configuring from resource: /hibernate.cfg.xml
    мар 09, 2015 5:11:12 PM org.hibernate.cfg.Configuration getConfigurationInputStream
    INFO: Configuration resource: /hibernate.cfg.xml
    мар 09, 2015 5:11:12 PM org.hibernate.cfg.Configuration addResource
    INFO: Reading mappings from resource: Item.hbm.xml
    мар 09, 2015 5:11:12 PM org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
    INFO: Mapping class: model.Item -> items
    мар 09, 2015 5:11:12 PM org.hibernate.cfg.HbmBinder bindCollection
    INFO: Mapping collection: model.Item.providers -> items_providers
    мар 09, 2015 5:11:12 PM org.hibernate.cfg.Configuration addResource
    INFO: Reading mappings from resource: Provider.hbm.xml
    мар 09, 2015 5:11:12 PM org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
    INFO: Mapping class: model.Provider -> providers
    мар 09, 2015 5:11:12 PM org.hibernate.cfg.HbmBinder bindCollection
    INFO: Mapping collection: model.Provider.items -> items_providers
    мар 09, 2015 5:11:12 PM org.hibernate.cfg.Configuration addResource
    INFO: Reading mappings from resource: Warehouse.hbm.xml
    мар 09, 2015 5:11:12 PM org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
    INFO: Mapping class: model.Warehouse -> warehouses
    мар 09, 2015 5:11:12 PM org.hibernate.cfg.Configuration doConfigure
    INFO: Configured SessionFactory: null
    мар 09, 2015 5:11:12 PM org.hibernate.cfg.HbmBinder bindCollectionSecondPass
    INFO: Mapping collection: model.Warehouse.items -> items
    мар 09, 2015 5:11:12 PM org.hibernate.connection.DriverManagerConnectionProvider configure
    INFO: Using Hibernate built-in connection pool (not for production use!)
    мар 09, 2015 5:11:12 PM org.hibernate.connection.DriverManagerConnectionProvider configure
    INFO: Hibernate connection pool size: 1
    мар 09, 2015 5:11:12 PM org.hibernate.connection.DriverManagerConnectionProvider configure
    INFO: autocommit mode: false
    мар 09, 2015 5:11:12 PM org.hibernate.connection.DriverManagerConnectionProvider configure
    INFO: using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost/warehouse
    мар 09, 2015 5:11:12 PM org.hibernate.connection.DriverManagerConnectionProvider configure
    INFO: connection properties: {user=zheka, password=****}
    мар 09, 2015 5:11:13 PM org.hibernate.cfg.SettingsFactory buildSettings
    INFO: RDBMS: MySQL, version: 5.5.41-0ubuntu0.14.10.1
    мар 09, 2015 5:11:13 PM org.hibernate.cfg.SettingsFactory buildSettings
    INFO: JDBC driver: MySQL Connector Java, version: mysql-connector-java-5.1.34 ( Revision: jess.balint@oracle.com-20141014163213-wqbwpf1ok2kvo1om )
    мар 09, 2015 5:11:13 PM org.hibernate.dialect.Dialect <init>
    INFO: Using dialect: org.hibernate.dialect.MySQL5Dialect
    мар 09, 2015 5:11:13 PM org.hibernate.transaction.TransactionFactoryFactory buildTransactionFactory
    INFO: Using default transaction strategy (direct JDBC transactions)
    мар 09, 2015 5:11:13 PM org.hibernate.transaction.TransactionManagerLookupFactory getTransactionManagerLookup
    INFO: No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
    мар 09, 2015 5:11:13 PM org.hibernate.cfg.SettingsFactory buildSettings
    INFO: Automatic flush during beforeCompletion(): disabled
    мар 09, 2015 5:11:13 PM org.hibernate.cfg.SettingsFactory buildSettings
    INFO: Automatic session close at end of transaction: disabled
    мар 09, 2015 5:11:13 PM org.hibernate.cfg.SettingsFactory buildSettings
    INFO: JDBC batch size: 15
    мар 09, 2015 5:11:13 PM org.hibernate.cfg.SettingsFactory buildSettings
    INFO: JDBC batch updates for versioned data: disabled
    мар 09, 2015 5:11:13 PM org.hibernate.cfg.SettingsFactory buildSettings
    INFO: Scrollable result sets: enabled
    мар 09, 2015 5:11:13 PM org.hibernate.cfg.SettingsFactory buildSettings
    INFO: JDBC3 getGeneratedKeys(): enabled
    мар 09, 2015 5:11:13 PM org.hibernate.cfg.SettingsFactory buildSettings
    INFO: Connection release mode: auto
    мар 09, 2015 5:11:13 PM org.hibernate.cfg.SettingsFactory buildSettings
    INFO: Maximum outer join fetch depth: 2
    мар 09, 2015 5:11:13 PM org.hibernate.cfg.SettingsFactory buildSettings
    INFO: Default batch fetch size: 1
    мар 09, 2015 5:11:13 PM org.hibernate.cfg.SettingsFactory buildSettings
    INFO: Generate SQL with comments: disabled
    мар 09, 2015 5:11:13 PM org.hibernate.cfg.SettingsFactory buildSettings
    INFO: Order SQL updates by primary key: disabled
    мар 09, 2015 5:11:13 PM org.hibernate.cfg.SettingsFactory createQueryTranslatorFactory
    INFO: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
    мар 09, 2015 5:11:13 PM org.hibernate.hql.ast.ASTQueryTranslatorFactory <init>
    INFO: Using ASTQueryTranslatorFactory
    мар 09, 2015 5:11:13 PM org.hibernate.cfg.SettingsFactory buildSettings
    INFO: Query language substitutions: {}
    мар 09, 2015 5:11:13 PM org.hibernate.cfg.SettingsFactory buildSettings
    INFO: Second-level cache: enabled
    мар 09, 2015 5:11:13 PM org.hibernate.cfg.SettingsFactory buildSettings
    INFO: Query cache: disabled
    мар 09, 2015 5:11:13 PM org.hibernate.cfg.SettingsFactory createCacheProvider
    INFO: Cache provider: org.hibernate.cache.EhCacheProvider
    мар 09, 2015 5:11:13 PM org.hibernate.cfg.SettingsFactory buildSettings
    INFO: Optimize cache for minimal puts: disabled
    мар 09, 2015 5:11:13 PM org.hibernate.cfg.SettingsFactory buildSettings
    INFO: Structured second-level cache entries: disabled
    мар 09, 2015 5:11:13 PM org.hibernate.cfg.SettingsFactory buildSettings
    INFO: Echoing all SQL to stdout
    мар 09, 2015 5:11:13 PM org.hibernate.cfg.SettingsFactory buildSettings
    INFO: Statistics: disabled
    мар 09, 2015 5:11:13 PM org.hibernate.cfg.SettingsFactory buildSettings
    INFO: Deleted entity synthetic identifier rollback: disabled
    мар 09, 2015 5:11:13 PM org.hibernate.cfg.SettingsFactory buildSettings
    INFO: Default entity-mode: pojo
    мар 09, 2015 5:11:13 PM org.hibernate.impl.SessionFactoryImpl <init>
    INFO: building session factory
    мар 09, 2015 5:11:13 PM net.sf.ehcache.config.Configurator configure
    WARNING: No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/home/zheka/practice/temp1/lib/ehcache-1.1.jar!/ehcache-failsafe.xml
    мар 09, 2015 5:11:13 PM org.hibernate.impl.SessionFactoryObjectFactory addInstance
    INFO: Not binding factory to JNDI, no JNDI name configured
    Hibernate: select this_.id as id3_0_, this_.address as address3_0_ from warehouses this_
    Hibernate: select items0_.warehouse_id as warehouse3_1_, items0_.id as id1_, items0_.id as id0_0_, items0_.name as name0_0_ from items items0_ where items0_.warehouse_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select items0_.provider_id as provider2_1_, items0_.item_id as item1_1_, item1_.id as id0_0_, item1_.name as name0_0_ from items_providers items0_ left outer join items item1_ on items0_.item_id=item1_.id where items0_.provider_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select items0_.provider_id as provider2_1_, items0_.item_id as item1_1_, item1_.id as id0_0_, item1_.name as name0_0_ from items_providers items0_ left outer join items item1_ on items0_.item_id=item1_.id where items0_.provider_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select items0_.provider_id as provider2_1_, items0_.item_id as item1_1_, item1_.id as id0_0_, item1_.name as name0_0_ from items_providers items0_ left outer join items item1_ on items0_.item_id=item1_.id where items0_.provider_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select providers0_.item_id as item1_1_, providers0_.provider_id as provider2_1_, provider1_.id as id2_0_, provider1_.name as name2_0_ from items_providers providers0_ left outer join providers provider1_ on providers0_.provider_id=provider1_.id where providers0_.item_id=?
    Hibernate: select items0_.warehouse_id as warehouse3_1_, items0_.id as id1_, items0_.id as id0_0_, items0_.name as name0_0_ from items items0_ where items0_.warehouse_id=?
    Hibernate: select items0_.warehouse_id as warehouse3_1_, items0_.id as id1_, items0_.id as id0_0_, items0_.name as name0_0_ from items items0_ where items0_.warehouse_id=?
    list of warehouses:
    warehouse number 1, address is ul. Moskovskaya, 5
        has red table, id of this item is 1
             which is provided by Sasha, id of this provider is 3
             which is provided by Vasya, id of this provider is 1
        has yellow plates, id of this item is 13
             which is provided by Sasha, id of this provider is 3
        has green table, id of this item is 3
             which is provided by Petya, id of this provider is 2
        has black chair, id of this item is 4
             which is provided by Vasya, id of this provider is 1
        has grey plates, id of this item is 14
             which is provided by Petya, id of this provider is 2
        has red chair, id of this item is 5
             which is provided by Sasha, id of this provider is 3
        has red plates, id of this item is 12
             which is provided by Vasya, id of this provider is 1
        has yellow chair, id of this item is 8
             which is provided by Vasya, id of this provider is 1
        has green chair, id of this item is 7
             which is provided by Sasha, id of this provider is 3
             which is provided by Vasya, id of this provider is 1
             which is provided by Petya, id of this provider is 2
        has green plates, id of this item is 11
             which is provided by Petya, id of this provider is 2
        has blue table, id of this item is 2
             which is provided by Petya, id of this provider is 2
        has black plates, id of this item is 10
             which is provided by Petya, id of this provider is 2
        has blue chair, id of this item is 6
             which is provided by Vasya, id of this provider is 1
        has white chair, id of this item is 9
             which is provided by Vasya, id of this provider is 1
    
    warehouse number 2, address is ul. Kievskaya, 4
        has black fork, id of this item is 24
             which is provided by Petya, id of this provider is 2
        has green fork, id of this item is 25
             which is provided by Vasya, id of this provider is 1
        has green spoon, id of this item is 19
             which is provided by Sasha, id of this provider is 3
        has red spoon, id of this item is 17
             which is provided by Sasha, id of this provider is 3
        has large scissors, id of this item is 15
             which is provided by Vasya, id of this provider is 1
        has yellow fork, id of this item is 22
             which is provided by Vasya, id of this provider is 1
        has blue fork, id of this item is 26
             which is provided by Petya, id of this provider is 2
        has brown fork, id of this item is 27
             which is provided by Sasha, id of this provider is 3
        has grey spoon, id of this item is 18
             which is provided by Vasya, id of this provider is 1
        has small scissors, id of this item is 16
             which is provided by Vasya, id of this provider is 1
        has red fork, id of this item is 23
             which is provided by Petya, id of this provider is 2
        has yellow spoon, id of this item is 20
             which is provided by Sasha, id of this provider is 3
        has white spoon, id of this item is 21
             which is provided by Sasha, id of this provider is 3
    
    warehouse number 3, address is ul. Kurskaya, 7
        has black blinds, id of this item is 31
             which is provided by Vasya, id of this provider is 1
        has white sofa, id of this item is 38
             which is provided by Vasya, id of this provider is 1
        has black sofa, id of this item is 37
             which is provided by Sasha, id of this provider is 3
        has brown blinds, id of this item is 33
             which is provided by Sasha, id of this provider is 3
        has red sofa, id of this item is 35
             which is provided by Petya, id of this provider is 2
        has grey sofa, id of this item is 34
             which is provided by Petya, id of this provider is 2
        has red cupboard, id of this item is 40
             which is provided by Sasha, id of this provider is 3
        has green blinds, id of this item is 30
             which is provided by Sasha, id of this provider is 3
        has blue cupboard, id of this item is 41
             which is provided by Sasha, id of this provider is 3
        has green cupboard, id of this item is 42
             which is provided by Vasya, id of this provider is 1
        has red blinds, id of this item is 29
             which is provided by Vasya, id of this provider is 1
        has white blinds, id of this item is 32
             which is provided by Sasha, id of this provider is 3
        has yellow sofa, id of this item is 36
             which is provided by Sasha, id of this provider is 3
        has yellow blinds, id of this item is 28
             which is provided by Vasya, id of this provider is 1
        has white cupboard, id of this item is 39
             which is provided by Vasya, id of this provider is 1
    

    значит все сделано правильно. После логов, которые хибернейт кидает в поток, будет напечатана площадь окружности.

    Заключение

    В этом посте мы рассмотрели работу приложения с базой данных через hibernate. Для связки джава классов с таблицами в базе данных мы использовали старый стиль через xml файлы hbm. В следующем посте мы проделаем все тоже самое, только для связки классов с таблицами будем использовать аннотации, а так же для построения проекта будем использовать инструмент управления зависимостями maven.

    Линки

    Хорошая статья, которая была использована за основу http://habrahabr.ru/post/29694
    Hibernate – One-to-Many example (XML Mapping)

    Поделиться в социальных сетях

    Опубликовать в Google Plus
    Опубликовать в LiveJournal
    Опубликовать в Мой Мир
    Опубликовать в Одноклассники
    Опубликовать в Яндекс