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.
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 we 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 error", JOptionPane.OK OPTION); } finally { if (session != null && session.isOpen()) { session.close(); } } } }
In principle, everything is intuitively clear here.
Let's create a Factory class in the DAO package, to which we will refer for our DAO implementations, from which we will call the methods we need:
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; } }
Well, that's it!
It remains only to see how it works:
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 { //Creating two students Student s1 = new Student(); Student s2 = new Student();
// Initialize them s1.
setName ("Ivanov Ivan"); s1.setAge(21l); s2.
setName ("Petrova Alisa"); s2.
setAge(24l);
//We will save them in the database, the ids will be generated automatically by Factory.
getInstance().getStudentDAO().addStudent(s1); Factory.getInstance().getStudentDAO().addStudent(s2);
// Output all students from the database List<Student> studs = Factory.
getInstance().getStudentDAO().getAllStudents(); System.out.println("========All students========="); for (int i = 0; i < studs. size (); ++i) { System.out. println ("Student name:" + studs.get(i).getName ()+", Age : "+ studs.get (i).getAge() +", id : " + studs.get(i).getId()); System.out.println("============================="); } } }
Java Hibernate.
Part 2 Requests
In the previous part, we looked at the simplest example of using Hibernate.
In the second part, we will look at the types of queries to the database.
Queries return a set of data from the database that meets the specified condition.
The Hibernate library offers three types of database queries:
1) Criteria 2) SQL 3) HQL
Let's start in order.
Queries using Criteria
The Criteria object is created using the createCriteria method of an instance of the Session class:
Criteria crit = session.createCriteria(Student.class); //creating a query criterion crit.
setMaxResults(50);/ / limiting the number of results List studies = crit.
list ();//putting the results in the list
In this example, a query criterion was created based on the Student class from the Java Hibernate article.
Part 1 Introduction.
The narrowing of the sample is carried out as follows:
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 specifies a pattern where ‘ _ ’ is any one character, ' % ’ is any number of characters Expression.isNull the field value is NULL.
Expression.between — ' age’ — the name of the field, 18 — the minimum value of the specified field, 25 — its maximum value Expression.in -specifies the range of values of a specific field Expression.
disjunction, Expression.
or disjunction (OR) - combines several other expressions with the OR operator.
Expression.eq determines whether the field is equal to some value.
The results can also be sorted:
List studies = sess.createCriteria(Student.class).
add( Expression.like ("name", " Iv%").
addOrder( Order.asc ("name")) //ascending.
addOrder( Order. desc ("age")) //descending.
list();
There is also the possibility of a query based on the data of an instance of the class:
Student s = new Student(); s.setName("Ivanov Ivan"); s.setAge(20l); List results = session.createCriteria(Student.class) .add( Example.create(s) ) .list();
Object fields that have a null value or are identifiers will be ignored.
Example can also be customized:
Example example = Example.
create(s).
excludeZeroes () //excludes fields with null values .excludeProperty ("name") / / excludes the "name" field.
IgnoreCase () //sets a case independent string comparison.
enableLike (); //uses like to compare strings List results = session.
createCriteria(Student.class).
add(example).
list();
Queries using SQL
SQL is a universal language used for creating, modifying and managing data in relational databases.
Hibernate allows you to express queries in the native SQL dialect.
It will look like something like this:
sess.createSQLQuery("select * from Student").addEntity(Student.class).list(); sess.createSQLQuery("select id, name, age from Student").addEntity(Student.class).list();
In CreateSQLQuery, you specify the SQL query itself, and with addEntity, you specify which entity is expected as a result.
You can also specify parameters in requests:
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();
In the first case, using query.
setString, we specify the ordinal number of the parameter (?) and the String type value that will be substituted instead.
If the value is of type Long, it will be setLong, if Date, then setDate, and so on.
In the second case, the parameter name is set explicitly, so the value is set to the parameter by name.
Hibernate allows you to make queries in HQL(The Hibernate Query Language), which is very similar to the SQL language, with the difference that it is completely object oriented.
If the query using SQL was made using the CreateSQLQuery method, then in HQL it will simply be createQuery.
A simple example:
List<Student> studs = (List<Student>)session.createQuery("from Student order by name").list();
As you can see, select can be omitted at the beginning of the request.
Since HQL is an object oriented language, the value of the fields can be selected as follows:
List<String> names = (List<String>)session.createQuery("select stud.name from Student stud order by name").list();
And you can also do this:
List result = session.createQuery("select new list(stud, name, stud.age) from Student as stud").list();
In general, the HQL language is relatively complex, but it is rich and gives a lot of features.
In Part 1 and Part 2, we looked at creating the simplest Student table using Hibernate, and also looked at the possibilities of querying this table.
In this article, we will learn how to link several tables together using annotations.
To begin with, in addition to the Student table, let's create two more tables, Test and Statistics.
They will be linked as follows: The Statistics table is used to link the Student and Test tables to avoid a many - to many relationship.
Let's create these two tables in 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));
Also, do not forget to add to the file hibernate.cfg.xml add mappings of our new classes:
<mapping class="logic.
Test" /> <mapping class="logic.
Statistics" />
Let's move on to the code.
Just like in Part 1, we create entity classes in the logic package:
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.Table;
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 configuration file will be located in the main directory pom.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 java interface, 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") public Collection<Student> find(String name) { return getSession().createQuery("from Student s where s.name like :name").setString("name", name).list(); } }
It is also worth noting that this class inherits from the org.springframework.orm.hibernate3.support.HibernateDaoSupport class, which is part of the SpringDao library and already implements methods for convenient working with the database.
It remains only to configure Hibernate in the main.resources directory to create a file 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>
In it, we describe: dataSource connection parameters to our database, SessionFactory a factory for working with database connections and for displaying our model in the database, dataDao — a service developed by us, when configuring which we will specify a link to the SessionFactory, TransactionManager — a transaction manager, when configuring which we will specify a link to the SessionFactory and also specify which methods should start a new transaction.
Let's write in the package ru.
javaxblog.hibernateSpringExample of the main directory.java is a small Main class in order to try out the created:
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()); }
}
Download the source code of the project: HibernateSpringExample.zip http://javaxblog.ru/article/java hibernate 4/
Add a comment
Phone number +7 351 235 00 10 Monday Friday From 9: 00 to 18: 00
© 2005-2014 IT Company Alfalavista.
Software development in Chelyabinsk.
Alfalavista Software Development Center.
Professional software and architectural solutions development, IT outsourcing, automation, web development, mobile development, Android, SEO, AlfaSolutions, 1C
Twitter
Up
