Home Services Software development IT outsourcing System integration Implementation of solutions AlfaSolutions
Implementation of 1C SAAS for business automation AlfaSolution
Products About us Portfolio Customers Reviews
Articles Contacts
Search...
Search
Categories
Implementation experience
Production management
Automation
Financial management
Architecture, high load systems, programming
Subscribe to our blog: IT technologies for specialists
Tweets of the user @AlfaLaVista1
Main/
Architecture, high load systems, programming
/Java Hibernate
Java Hibernate
Hibernate is a library for the Java programming language designed to solve problems of object relational mapping (ORM).
This library provides an easy to use framework for mapping an object oriented data model to traditional relational databases.
In a nutshell, ORM is the mapping of objects of an object oriented language into relational database structures.
Namely, objects, such as they are, with all fields, values, relationships, and so on.
Java Hibernate.
Part 1 Introduction
Hibernate significantly reduces the development time of applications working with databases, takes care of the connection of Java classes with database tables (and Java data types to SQL data types), provides tools for automatic query construction and data extraction.
Let's write a small application that uses the Hibernate library to store and process an Oracle DBMS table.
First we need to download Hibernate.
At the time of writing, the latest version was Hibernate 4.1 and we will work with it.
Do not be alarmed if the library will weigh a lot, most likely, documentation and various use cases have been inserted into it, among other things.
We will also need to download and install the Oracle DBMS.
In this example, I will use Oracle 10.2, but you can install a newer version, there will not be much difference.
After installing Oracle, create a user and a database with some name, for example, MyDB.
In the database, we will create a simple Student table with three fields:
1) id id
2) name — the name of the student
3) age — his age
For those who do not yet know how to create tables in Oracle:
CREATE TABLE Student(id NUMBER(10) NOT NULL,name varchar2(100) NOT NULL, age NUMBER(3) NOT NULL, CONSTRAINT pk Student PRIMARY KEY(id));
Work with Oracle is finished, let's go to Eclipse.
Create a new java project, give it a name, say, HibernateSimpleExample.
We add our library to it using Build Path -> Configure Build Path -> Add External JARs.
Select all jar files from the lib folder of our library.
Also, Hibernate requires a special jdbc driver to work with Oracle for a specific version, which can be found here.
Download it and add it to the project in the same way.
Get closer to the code!
First, create a logic package.
In it, we will describe our entity class, which we will store in the database:
package logic;
import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity @Table(name="Student") public class Student {
private Long id; private String name; private Long age;
public Student(){ name = null; }
public Student(Student s){ name = s.getName(); }
@Id @GeneratedValue(generator="increment") @GenericGenerator(name="increment", strategy = "increment") @Column(name="id") public Long getId() { return id; }
@Column(name="name") public String getName(){ return name; }
@Column(name="age") public Long getAge(){ return age; }
public void setId(Long i){ id = i; }
public void setName(String s){ name = s; }
public void setAge(Long l){ age = l; } }
Annotations are used here for Mapping Java classes to database tables.
Simply put, in order for Hibernate to know that this class is an entity, that is, we will store objects of this class in the database.
The annotations used here have the following meaning:
@Entity indicates that this class is an entity.
@Table specifies the name of the table in which the objects of the class will be stored
@Id indicates the id field
@GeneratedValue and @GenericGenerator indicates how the id will be generated (in ascending order for us)
@Column indicates the name of the column corresponding to this field.
It is also worth noting that all entity classes must necessarily have getters, setters and a default constructor.
Now let's create the main configuration file hibernate.cfg.xml and put it in the bin folder of our project.
From this file, Hibernate will take all the information it needs:
<!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.driver class">oracle.jdbc.driver.OracleDriver</property> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:MyDB</property> <property name="connection.username">Your Login</property> <property name="connection.password">Your Password</property> <property name="connection.pool size">10</property> <property name="dialect">org.hibernate.dialect.OracleDialect</property> <property name="show sql">true</property> <property name="hbm2ddl.auto">update</property> <property name="hibernate.connection.autocommit">false</property> <property name="current session context class">thread</property>
<mapping class="logic.
Student" />
</session factory> </hibernate configuration>
In principle, everything is clear here.
I will only note that such fields as the driver name, url format, dialect are taken from the official website of the database developers.
The username and password are specified for the user that you created in your DBMS.
The remaining fields are some additional settings that enable/disable some not particularly important options.
Now we will create a util package, and in it the HibernateUtil class, which will be responsible for processing this xml file and establishing a connection with our database:
package util;
import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration;
public class HibernateUtil { private static SessionFactory sessionFactory = null;
static { try { //creates the session factory from hibernate.cfg.xml sessionFactory = new Configuration().configure().buildSessionFactory(); } catch (Exception e) { e.printStackTrace(); } }
public static SessionFactory getSessionFactory() { return sessionFactory; } }
Now it remains for us to deal with the interaction of our application with the database.
Then, for the entity class, we will define the StudentDAO interface from the DAO package, containing a set of necessary methods:
package DAO;
import java.sql.SQLException; import java.util.List;
import logic.
Student;
public interface StudentDAO { public void addStudent(Student student) throws SQLException; //add student public void updateStudent (Student student) throws SQLException;/ / update student public Student getStudentById(Long id) throws SQLException; //get a student by id public List getAllStudents() throws SQLException; //get all students public void deleteStudent (Student student) throws SQLException;//delete student }
Now let's define the implementation of this interface in the SudentDAOImpl class in the DAO.Impl package:
package DAO.Impl;
import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.swing.JOptionPane; import org.hibernate.Session; import util.
HibernateUtil; import DAO.StudentDAO; import logic.
Student;
public class StudentDAOImpl implements StudentDAO {
public void addStudent(Student stud) throws SQLException { Session session = null; try { session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); session. save(stud); session. getTransaction (). commit (); } catch (Exception e) { JOptionPane. showMessageDialog(null, e.
GetMessage (), "I/O error", JOptionPane.OK OPTION); } finally { if (session != null && session.isOpen()) { session.close(); } } }
public void updateStudent(Student stud) throws SQLException { Session session = null; try { session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); session. update(stud); session. getTransaction (). commit (); } catch (Exception e) { JOptionPane. showMessageDialog(null, e.
GetMessage (), "I/O error", JOptionPane.OK OPTION); } finally { if (session != null && session.isOpen()) { session.close(); } } }
public Student getStudentById(Long id) throws SQLException { Session session = null; Student stud = null; try { session = HibernateUtil. getSessionFactory ().
OpenSession(); stud = (Student) session. load(Student.class, id); } catch (Exception e) { JOptionPane. showMessageDialog(null, e.
GetMessage (), "I/O error", JOptionPane.OK OPTION); } finally { if (session != null && session.isOpen()) { session.close(); } } return stud; }
public List<Student> getAllStudents() throws SQLException { Session session = null; List<Student> studs = new ArrayList<Student>(); try { session = HibernateUtil. getSessionFactory (). OpenSession(); studs = session.createCriteria(Student.class). list (); } catch (Exception e) { JOptionPane. showMessageDialog(null, e. GetMessage (), "I/O Error", JOptionPane.OK OPTION) ; } finally { if (session != null && session.isOpen()) { session.close(); } } return studs; }
public void deleteStudent(Student stud) throws SQLException { Session session = null; try { session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); session.delete(stud); session.getTransaction().commit(); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), "Ошибка I/O", JOptionPane.OK OPTION); } finally { if (session != null && session.isOpen()) { session.close(); } } } }
В принципе, интуитивно тут все понятно.
Давайте создадим класс Factory в пакете DAO, к которому будем обращаться за нашими реализациями DAO, от которых и будем вызывать необходимые нам методы:
package DAO;
import DAO.Impl.StudentDAOImpl;
public class Factory {
private static StudentDAO studentDAO = null; private static Factory instance = null;
public static synchronized Factory getInstance(){ if (instance == null){ instance = new Factory(); } return instance; }
public StudentDAO getStudentDAO(){ if (studentDAO == null){ studentDAO = new StudentDAOImpl(); } return studentDAO; } }
Ну вот и все!
Осталось только посмотреть как это работает:
package main;
import java.sql.SQLException; import java.util.List;
import logic.
Student;
import DAO.Factory;
public class Main {
public static void main(String[] args) throws SQLException { //Создадим двух студентов Student s1 = new Student(); Student s2 = new Student();
//Проинициализируем их s1.setName("Ivanov Ivan"); s1.setAge(21l); s2.setName("Petrova Alisa"); s2.setAge(24l);
//Сохраним их в бд, id будут сгенерированы автоматически Factory.getInstance().getStudentDAO().addStudent(s1); Factory.getInstance().getStudentDAO().addStudent(s2);
//Выведем всех студентов из бд List<Student> studs = Factory.getInstance().getStudentDAO().getAllStudents(); System.out.println("========Все студенты========="); for(int i = 0; i < studs.size(); ++i) { System.out.println("Имя студента : " + studs.get(i).getName() + ", Возраст : " + studs.get(i).getAge() +", id : " + studs.get(i).getId()); System.out.println("============================="); } } }
Java Hibernate.
Часть 2 — Запросы
В предыдущей части мы рассмотрели простейший пример использования Hibernate.
В второй части мы рассмотрим виды запросов к базе данных.
Запросы возвращают набор данных из базы данных, удовлетворяющих заданному условию.
Библиотека Hibernate предлагает три вида запросов к БД:
1) Criteria 2) SQL 3) HQL
Начнем по порядку.
Запросы с использованием Criteria
Объект Criteria создается с помощью метода createCriteria экземпляра класса Session:
Criteria crit = session.createCriteria(Student.class); //создаем критерий запроса crit.setMaxResults(50);//ограничиваем число результатов List studs = crit.list();//помещаем результаты в список
В данном примере был создан критерий запроса на основе класса Student из статьи Java Hibernate.
Части 1 — Введение.
Сужение выборки осуществляется следующим образом:
List studs = session.createCriteria(Student.class) .add( Expression.like("name", "Ivanov%") ) .add( Expression.between("age", 18, 25) ) .list();
List studs = session.createCriteria(Student.class) .add( Expression.like("name", "_van%") ) .add( Expression.or( Expression.eq( "age", new Integer(20) ), Expression.isNull("age") ) ) .list();
List studs = session.createCriteria(Student.class) .add( Expression.in( "name", new String[] { "Ivanov Ivan", "Petrov Petia", "Zubin Egor" } ) ) .add( Expression.disjunction() .add( Expression.isNull("age") ) .add( Expression.eq("age", new Integer(20) ) ) .add( Expression.eq("age", new Integer(21) ) ) .add( Expression.eq("age", new Integer(22) ) ) ) ) .list();
Expression.like — указывает шаблон, где ‘_’ — любой один символ, ‘%’ — любое количество символов Expression.isNull — значение поля равно NULL.
Expression.between — ‘age’ — имя поля, 18 — минимальное значение указанного поля, 25 — его максимальное значение Expression.in — указывает диапазон значений конкретного поля Expression.disjunction, Expression.or — дизъюнкция (OR) — объединяет в себе несколько других выражений оператором ИЛИ.
Expression.eq — определяет равенство поля какому то значению.
Результаты также можно отсортировать:
List studs = sess.createCriteria(Student.class) .add( Expression.like("name", "Iv%") .addOrder( Order.asc("name") )//по возрастанию .addOrder( Order.desc("age") )//по убыванию .list();
Также есть возможность запроса по данным экземпляра класса:
Student s = new Student(); s.setName("Ivanov Ivan"); s.setAge(20l); List results = session.createCriteria(Student.class) .add( Example.create(s) ) .list();
Поля объекта, имеющие значение null или являющиеся идентификаторами, будут игнорироваться.
Example также можно настраивать:
Example example = Example.create(s) .excludeZeroes() //исключает поля с нулевыми значениями .excludeProperty("name") //исключает поле "name" .ignoreCase() //задает независимое от регистра сравнение строк .enableLike(); //использует like для сравнения строк List results = session.createCriteria(Student.class) .add(example) .list();
Запросы с использованием SQL
SQL — это универсальный язык, применяемый для создания, модификации и управления данными в реляционных базах данных.
Hibernate позволяет выражать запросы на родном для вашей базы данных диалекте SQL.
Выглядеть это будет, примерно, следующим образом:
sess.createSQLQuery("select * from Student").addEntity(Student.class).list(); sess.createSQLQuery("select id, name, age from Student").addEntity(Student.class).list();
В createSQLQuery вы задаете сам SQL запрос, а с помощью addEntity вы указываете, какая сущность ожидается в результате.
В запросах также можно указывать параметры:
Query query = session.createSQLQuery("select * from Student where name like ?").addEntity(Student.class); List result = query.setString(0, "Ivan%").list();
query = session.createSQLQuery("select * from Student where name like :name").addEntity(Student.class); List result = query.setString("name", "Ivan%").list();
В первом случае с помощью query.setString мы указываем порядковый номер параметра (?) и значение типа String, которое вместо него подставится.
Если значение типа Long, то будет setLong, если Date, то setDate и так далее.
Во втором случае имя параметра задано явно, поэтому значение задается параметру по имени.
Запросы с использованием HQL
Hibernate позволяет производить запросы на HQL(The Hibernate Query Language — Язык запросов Hibernate), который во многом похож на язык SQL, с той разницей, что является полностью объектно ориентированным.
Если запрос с помощью SQL производился методом createSQLQuery, то в HQL будет просто createQuery.
Простой пример:
List<Student> studs = (List<Student>)session.createQuery("from Student order by name").list();
Как видите select в начале запроса можно не указывать.
Поскольку HQL — объектно ориентированный язык, то значение полей можно выбрать и так:
List<String> names = (List<String>)session.createQuery("select stud.name from Student stud order by name").list();
А еще можно и так:
List result = session.createQuery("select new list(stud, name, stud.age) from Student as stud").list();
В общем говоря, язык HQL относительно сложен, но зато богат и дает очень много возможностей.
Java Hibernate.
Часть 3 — Отношения
В Части 1 и Части 2 мы рассматривали создание простейшей таблицы Student, используя Hibernate, а также рассмотрели возможности запросов к данной таблице.
В этой статье мы узнаем как связать между собой несколько таблиц с помощью аннотаций.
Для начала, помимо таблицы Student, давайте создадим еще две таблицы Test и Statistics.
Они будут связаны следующим образом:
Таблица Statistics служит для связи таблиц Student и Test, чтобы избежать отношения многие ко многим.
Создадим эти две таблицы в Oracle:
CREATE TABLE Test(tid NUMBER(10) NOT NULL,tname varchar2(100) NOT NULL, CONSTRAINT pk Test PRIMARY KEY(tid));
CREATE TABLE Statistics(stid NUMBER(10) NOT NULL, id NUMBER(10) NOT NULL, tid NUMBER(10) NOT NULL, CONSTRAINT pk Statistics PRIMARY KEY(stid), CONSTRAINT fk Student FOREIGN KEY(id) REFERENCES Student(id), CONSTRAINT fk Test FOREIGN KEY(tid) REFERENCES Test(tid));
Также не забудем в файл hibernate.cfg.xml добавить маппинги наших новых классов:
<mapping class="logic.
Test" /> <mapping class="logic.
Statistics" />
Перейдем к коду.
Подобно тому как и в Части 1 создаем в пакете logic классы сущности:
Test
package logic;
import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinTable; import javax.persistence.Table; import javax.persistence.JoinColumn;
import org.hibernate.annotations.GenericGenerator;
@Entity @Table(name="Test") public class Test {
private Long tid; private String tname;
public Test(){ tname = null; }
public Test(Test s){ tname = s.getTName(); }
@Id @GeneratedValue(generator="increment") @GenericGenerator(name="increment", strategy = "increment") @Column(name="tid") public Long getTid() { return tid; }
@Column(name="tname") public String getTName(){ return tname; }
public void setId(Long i){ tid = i; }
public void setTName(String s){ tname = s; } }
Statistics
package logic;
import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Ta ble;
import org.hibernate.annotations.GenericGenerator;
@Entity @Table(name="Statistics") public class Statistics {
private Long stid; private Long id; private Long tid;
public Statistics(){ }
@Id @GeneratedValue(generator="increment") @GenericGenerator(name="increment", strategy = "increment") @Column(name="stid") public Long getStid(){ return stid; }
@Column(name="id") public Long getId(){ return id; }
@Column(name="tid") public Long getTid(){ return tid; } }
The TestDAO and TestDAOImpl classes are created in the same way as for the Student entity.
It remains only to show Hibernate how these tables are related to each other.
How is this done?
Again, with the help of annotations.
The following types of annotations are provided for this in Hibernate: @OneToOne, @OneToMany, @ManyToOne, @ManyToMany.
For example, to link the Student and Statistics tables with a many to one relationship, you should add the following code to the Student class:
private Statistics stat;
@ManyToOne @JoinTable(name = "id") public Statistics getStat(){ return stat; }
In the Statistics class, we annotate the one - to many relationship with the Student class:
private Set<Student> studs = new HashSet<Student>(0);
@OneToMany @JoinTable(name = "id") public Set<Student> getStuds() { return studs; }
As you can see, in the Student class, we declared an attribute of the Statistics type and indicated that this table is connected by a many - to one relationship with the table represented by the Statistics entity class.
And in the Statistics class, they indicated a one - to many relationship with the Student class.
Using the @JoinTable annotation, we specify which field is the foreign key to the current table.
In the same way, we denote the relationship of the Test and Statistics tables by simply adding the code to the Test class:
private Statistics stat;
@ManyToOne @JoinTable(name = "id") public Statistics getStat(){ return stat; }
In the Statistics class, we annotate the one - to many relationship with the Test class:
private Set<Test> tests = new HashSet<Test>(0);
@OneToMany @JoinTable(name = "id") public Set<Test> getTests() { return tests; }
Since the Statistics table is not just a table associated with Student and Test, but it breaks the unwanted many to many relationship, we can also show this to Hibernate.
Simply, instead of separately denoting the relationship in each table, we will denote the entire relationship in one, for example, in the Test table by adding the code:
private Student stud;
@ManyToOne @JoinTable(name = "Statistics", joinColumns = @JoinColumn(name = "tid"), inverseJoinColumns = @JoinColumn(name = "id")) public Student getStud(){ return stud; }
Using the name parameter of the @JoinTable annotation, we denote the linking table, joinColumns = @JoinColumn we specify through which key the Test and Statistics tables are connected, inverseJoinColumns = @JoinColumn we specify through which keys Statistics and Student are already connected.
If we denoted this relationship in the Student class:
private Test test;
@ManyToOne @JoinTable(name = "Statistics", joinColumns = @JoinColumn(name = "id"), inverseJoinColumns = @JoinColumn(name = "tid")) public Test getTest(){ return test; }
Java Hibernate.
Part 4 Spring
In previous articles, we looked at how you can create tables for storage in a database using the Hibernate Framework.
We learned how to link these tables together, and also got acquainted with various types of queries to these tables using Hibernate tools.
In this article, we will study the management and configuration of Hibernate using the Spring Framework library.
Using the Spring library, we will set up a connection to the database, establish a connection with it, and also learn how to manage transactions.
Let's create a project of the Maven Project type in Eclipse and call it HibernateSpringExample.
The pom configuration file will be located in the main directory.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven 4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>ru.javaxblog</groupId> <artifactId>HibernateSpringExample</artifactId> <version>0.0.1 SNAPSHOT</version> <build> <testResources> <testResource> <directory>src/main/webapp</directory> </testResource> <testResource> <directory>src/main/resources</directory> </testResource> </testResources> </build>
<dependencies>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring context</artifactId> <version>3.1.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring aop</artifactId> <version>3.1.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring tx</artifactId> <version>3.1.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring orm</artifactId> <version>3.1.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring jdbc</artifactId> <version>3.1.1.RELEASE</version> </dependency> <dependency> <groupId>org.hibernate</groupId>
<artifactId>hibernate entitymanager</artifactId> <version>3.6.0.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate commons annotations </artifactId> <version>3.2.0.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate core </artifactId> <version>3.6.0.Final</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.2</version> </dependency> <dependency> <groupId>antlr</groupId> <artifactId>antlr</artifactId> <version>2.7.7</version> </dependency> <dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>1.0</version>
</dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <dependency> <groupId>commons collections</groupId> <artifactId>commons collections</artifactId> <version>3.2.1</version> </dependency> <dependency> <groupId>commons dbcp</groupId> <artifactId>commons dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>commons logging</groupId> <artifactId>commons logging</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>commons pool</groupId> <artifactId>commons pool</artifactId> <version>1.6</version> </dependency> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version>
</dependency> <dependency> <groupId>javassist</groupId> <artifactId>javassist</artifactId> <version>3.3</version> </dependency> <dependency> <groupId>javax.transaction</groupId> <artifactId>jta</artifactId> <version>1.1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j api</artifactId> <version>1.6.6</version> </dependency> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate jpa 2.0 api</artifactId> <version>1.0.1.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate annotations</artifactId> <version>3.3.0.ga</version> </dependency> <!-- ORACLE database driver --> <dependency> <groupId>com.oracle</groupId> <artifactId>oracle</artifactId> <version>10.2.0.1</version> </dependency>
</dependencies>
</project>
As you can see, there are a lot of dependencies, but Maven will easily download them and add them to our project, thereby making this hard work easier for us.
I want to pay special attention to the last dependency.
This is a jdbc driver for connecting to a database.
You canot download it in the repositories, so to use it in our project, we will first register it.
To do this, download the necessary jdbc driver manually.
Through the command line, go to the directory where our driver is located, and run the command:
mvn install:install file -Dfile=ojdbc14.jar -DgroupId=com.oracle -DartifactId=oracle -Dversion=10.2.0.1 -Dpackaging=jar -DgeneratePom=true
Instead of ojdbc14.jar you will enter the name of your file.
After that, Maven will add it to your local repository and it can be used in a file pom.xml under the registered groupId, artifactId and version.
Now in the package ru.
javaxblog.hibernateSpringExample of the main directory.let's create our Student entity class, whose objects we will store in the database:
package ru.javaxblog.hibernateSpringExample;
import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id;
import org.hibernate.annotations.GenericGenerator;
@Entity public class Student {
private Long id; private String name; private Long age;
public Student(){ name = null; }
public Student(String n, Long a){ name = n; age = a; }
public Student(Student s){ name = s.getName(); }
@Id @GeneratedValue(generator="increment") @GenericGenerator(name="increment", strategy = "increment") @Column(name="id") public Long getId() { return id; }
@Column(name="name") public String getName(){ return name; }
@Column(name="age") public Long getAge(){ return age; }
public void setId(Long i){ id = i; }
public void setName(String s){ name = s; }
public void setAge(Long l){ age = l; } }
In the main.resources directory, create a file hibernate.cfg.xml with mapping of our essence:
<?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> <mapping class="ru.javaxblog.hibernateSpringExample.
Student"/> </session factory> </hibernate configuration>
Now in the package ru.
javaxblog.hibernateSpringExample of the main directory.let's create the StudentDAO interface in java, in which we will describe the main methods of working with our database:
package ru.javaxblog.hibernateSpringExample;
import java.util.Collection;
public interface StudentDAO {
Student get(Long id);
Student save(Student stud);
Collection<Student> find(String text);
}
In the same package, we will create an implementation of this interface StudentHibernateDao:
package ru.javaxblog.hibernateSpringExample;
import java.util.Collection;
import org.hibernate.SessionFactory; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class StudentHibernateDao extends HibernateDaoSupport implements StudentDAO {
public Student get(Long id) { return (Student) getSession().get(Student.class, id); }
@Override protected HibernateTemplate createHibernateTemplate(SessionFactory sessionFactory) { HibernateTemplate result = super.createHibernateTemplate(sessionFactory); result.setAllowCreate(false); return result; }
public StudentHibernateDao() { }
public Student save(Student objectToSave) { getSession().saveOrUpdate(objectToSave); return objectToSave; }
@SuppressWarnings("unchecked") p ublic Collection<Student> find(String name) { return getSession().createQuery("from Student s where s.name like :name").setString("name", name).list(); } }
Стоит также отметить, что данный класс наследуется от класса org.springframework.orm.hibernate3.support.HibernateDaoSupport, который является частью библиотеки SpringDao и в нем уже реализованы методы для удобной работы с БД.
Осталось только для конфигурирования Hibernate в директории main.resources создать файл applicationContext.xml:
<?xml version="1.0" encoding="UTF 8"?
> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring beans 2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring context 2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring tx 2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring aop 2.5.xsd">
<context:annotation config />
<aop:config> <aop:pointcut id="myPointcut" expression="execution(* ru.javaxblog.hibernateSpringExample.*.*(..))" /> <aop:advisor advice ref="txAdvice" pointcut ref="myPointcut" /> </aop:config>
<tx:advice id="txAdvice" transaction manager="transactionManager"> <tx:attributes> <tx:method name="get*" propagation="REQUIRED" read only="true" /> <tx:method name="find*" propagation="REQUIRED" read only="true" /> <tx:method name="save*" propagation="REQUIRED" /> </tx:attributes> </tx:advice>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>oracle.jdbc.driver.OracleDriver</value> </property> <property name="url"> <value>jdbc:oracle:thin:@localhost:1521:MoCoDB</value> </property> <property name="username"> <value>system</value> </property> <property name="password"> <value>orcl</value> </property> </bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:/hibernate.cfg.xml" /> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop> <prop key="hibernate.show sql">true</prop> <prop key="hibernate.hbm2ddl.auto">create</prop> </props> </property> </bean>
<bean id="dataDao" class="ru.javaxblog.hibernateSpringExample.
StudentHibernateDao"> <property name="sessionFactory" ref="sessionFactory" /> </bean>
</beans>
В нем мы описываем: dataSource — параметры подключения к нашей базе данных, sessionFactory — фабрику для работы с подключениями к базе данных и для отображения нашей модели в БД, dataDao — разработанный нами сервис, при конфигурировании которого мы укажем ссылку на sessionFactory, transactionManager — менеджер транзакций, при конфигурировании которого мы укажем ссылку на sessionFactory и также укажем при каких методах следует начинать новую транзакцию.
Напишем в пакете ru.javaxblog.hibernateSpringExample директории main.java небольшой класс Main для того, чтобы опробовать созданное:
package ru.javaxblog.hibernateSpringExample;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( new String[] { "applicationContext.xml" }, true); StudentDAO studDao = (StudentDAO) context.getBean("dataDao"); Student data1 = new Student("Alex",20l); studDao.save(data1); Student data2 = new Student("Bob",22l); studDao.save(data2); Student data3 = new Student("Alice", 19l); studDao.save(data3); System.out.println(studDao.find("A%").size()); }
}
Скачать исходники проекта: HibernateSpringExample.zip http://javaxblog.ru/article/java hibernate 4/
Добавить комментарий
Телефон +7 351 235 00 10 Понедельник - Пятница С 9:00 до 18:00
© 2005-2014 ИТ Компания АльфаЛаВиста.
Разработка программного обеспечения в Челябинске.
Центр разработки программного обеспечения Alfalavista.
Професиональная разработка программного обеспечения и архитектурных решений, ИТ аутсорсинг, автоматизация, web разработка, mobile разработка, Android, SEO, AlfaSolutions, 1С
Twitter
Вверх
