Skip to content

Commit 1035ce7

Browse files
committed
Added hibernate tutorials
1 parent 001e4d0 commit 1035ce7

3 files changed

+276
-0
lines changed

java-hibernate-annotated-mappings.md

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
title: Java: Hibernate p3: annotations
2+
date: 2012-03-28 20:30:13
3+
tags: java,java-hibernate
4+
5+
Instead of using a mapping XML file, we can use Java annotations. First make sure you have the dependencies for annotations and the simple logging facade used by hibernate when using annotations. You need:
6+
7+
* hibernate-annotations
8+
* slf4j-api
9+
10+
Previously in the hibernate.cfg.xml file we had a reference to a mappings file. Remove that.
11+
12+
Now set up your hibernate configuration differently in your main java file. Now we now use AnnotationConfiguration, and add two files for annotation. There are different ways to add files for annotation, in XML etc.
13+
14+
factory = new AnnotationConfiguration()
15+
.addAnnotatedClass(Employee.class)
16+
.addAnnotatedClass(Certificate.class)
17+
.configure()
18+
.buildSessionFactory();
19+
20+
Finally Annotate the class files. In Employee we say it's an @Entity, and state the @Table it belongs to. The @Id and @GenerateValue correspond to what we put in the XML file previously. The @Column annotation states its column name in the table.
21+
22+
...
23+
import javax.persistence.*;
24+
25+
@Entity
26+
@Table(name="employee")
27+
public class Employee {
28+
@Id @GeneratedValue
29+
@Column(name = "id")
30+
private long id = 1L;
31+
32+
@Column(name = "name")
33+
private String name;
34+
35+
36+
@OneToMany(cascade=CascadeType.ALL, targetEntity=model.Certificate.class)
37+
@JoinColumn(name="employee_id")
38+
private Set certificates;
39+
...
40+
41+
The final variable says there'll be a one-to-many linkage. We state the targetEntity (we wouldn't need this if we we're using generics). Then we state the join column name in the Certificates table.
42+
43+
The rest of the file is the same as before. The Certificate file only differs as above:
44+
45+
...
46+
import javax.persistence.*;
47+
48+
@Entity
49+
@Table(name="certificate")
50+
public class Certificate {
51+
52+
@Id @GeneratedValue
53+
@Column(name = "id")
54+
private long id = 1L;
55+
56+
@Column(name = "cert_name")
57+
private String name;
58+
59+
Et Voila.

java-hibernate-mappings.md

+91
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
title: Java: Hibernate p2: mappings
2+
date: 2012-03-28 18:30:13
3+
tags: java,java-hibernate
4+
5+
6+
To create a mapping, a one to many in this case, we first need to edit the src/main/resources/Employee.hbm.xml file to state the mapping.
7+
8+
<class name="model.Employee" table="employee">
9+
<id name="id" column="id" type="long">
10+
<generator class="native"></generator>
11+
</id>
12+
<property name="name" column="name" type="string"></property>
13+
<set name="certificates" cascade="all">
14+
<key column="employee_id"/>
15+
<one-to-many class="model.Certificate"/>
16+
</set>
17+
</class>
18+
19+
<class name="model.Certificate" table="certificate">
20+
<id name="id" type="long" column="id">
21+
<generator class="native"/>
22+
</id>
23+
<property name="name" column="cert_name" type="string"/>
24+
</class>
25+
26+
Note the new set tag. This means we'll store the new classes in a java Set. We give it a name that will relate to the name in the Certificate class we'll make. cascade=all means that we'll persist the Certificates as the same time as Employee. We then set the key column in our to-be-created certificate table, and the fact it's going to be a one-to-many table using the class as model.Certificate. We finally create a new class tag that is the same as the one we created in the previous tutorial.
27+
28+
The Employee class we defined before only changes in that we create a new Set of the Certificate classes, and make the setters and getters.
29+
30+
...
31+
private Set certificates;
32+
...
33+
public Set getCertificates() {
34+
return certificates;
35+
}
36+
public void setCertificates(Set certificates) {
37+
this.certificates = certificates;
38+
}
39+
...
40+
41+
42+
Now here's the Certificate class:
43+
44+
package model;
45+
46+
public class Certificate {
47+
48+
private long id = 1L;
49+
50+
private String name;
51+
52+
public Certificate() {
53+
}
54+
55+
public Certificate(String fname) {
56+
name = fname;
57+
}
58+
59+
public long getId() {
60+
return id;
61+
}
62+
63+
public void setId(Long id) {
64+
this.id = id;
65+
}
66+
67+
public String getName() {
68+
return name;
69+
}
70+
71+
public void setName(String name) {
72+
this.name = name;
73+
}
74+
}
75+
76+
It's possible that you may need to implement compareTo() and hashCode() in some instances.
77+
78+
Now in the main class file, First create a Set with the certificates in, then you can add them to the Employee, and then save the employee.
79+
80+
HashSet set = new HashSet();
81+
Certificate cert = new Certificate("some python shit");
82+
Certificate cert1 = new Certificate("some go shit");
83+
set.add(cert); set.add(cert1);
84+
85+
...
86+
87+
Employee employee = new Employee("name");
88+
employee.setCertificates(set);
89+
employeeID = (Long) session.save(employee);
90+
91+
When you delete an employee, it will also delete its certificates.

java-hibernate-sqlite.md

+126
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
title: Java: Hibernate p1: with SQLite
2+
date: 2012-03-26 18:30:13
3+
tags: java,java-hibernate
4+
5+
First hibernate needs a small army of jars. You need:
6+
7+
* hibernatesqlite
8+
* hibernate-entitymanager
9+
* sqlite-jdbc
10+
11+
Now create a sqlite3 database in your current directory. Give it an id for the primary key and a text name column. Call them 'id' and 'name'. Name the table employee. Name the file dby.db.
12+
13+
Then in src/main/resources create your hibernate.cfg.xml file. This states you're going to use a sqlite db, your using it the reference to the db your previously created, and your specifying a mapping that we'll get to next.
14+
15+
<?xml version="1.0" encoding="utf-8"?>
16+
<!DOCTYPE hibernate-configuration SYSTEM
17+
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
18+
19+
<hibernate-configuration>
20+
<session-factory>
21+
22+
<property name="hibernate.dialect">
23+
com.applerao.hibernatesqlite.dialect.SQLiteDialect
24+
</property>
25+
<property name="hibernate.connection.driver_class">
26+
org.sqlite.JDBC
27+
</property>
28+
<property name="hibernate.connection.url">
29+
jdbc:sqlite:dby.db
30+
</property>
31+
32+
<mapping resource="Employee.hbm.xml"/>
33+
34+
</session-factory>
35+
</hibernate-configuration>
36+
37+
In the same directory we're going to create that mapping between your DB and a java class.
38+
39+
<?xml version="1.0" encoding="UTF-8"?>
40+
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
41+
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
42+
<hibernate-mapping>
43+
<class name="model.Employee" table="employee">
44+
<id name="id" column="id" type="long">
45+
<generator class="native"></generator>
46+
</id>
47+
<property name="name" column="name" type="string"></property>
48+
</class>
49+
</hibernate-mapping>
50+
51+
It's saying we have a class called employee in Employee, which relates to the employee take in the database. It say it has both a id and a name property, which are of the type long and string respectively. The id tag uses the generator native to say make it autoincrement.
52+
53+
Now we need to actually create that class, src/main/java/model/Employee.java. It a Plain Old Java Object.
54+
55+
package model;
56+
57+
public class Employee {
58+
59+
private long id = 1L;
60+
61+
private String name;
62+
63+
public Employee() {
64+
}
65+
66+
public Employee(String fname) {
67+
name = fname;
68+
}
69+
70+
public long getId() {
71+
return id;
72+
}
73+
74+
public void setId(Long id) {
75+
this.id = id;
76+
}
77+
78+
public String getName() {
79+
return name;
80+
}
81+
82+
public void setName(String name) {
83+
this.name = name;
84+
}
85+
}
86+
87+
Now we need to create our class that actually deals with that. We first create a SessionFactory. This allows us to make session requests that actually talk to the DB:
88+
89+
try{
90+
mFctory = new Configuration().configure().buildSessionFactory();
91+
}catch (Throwable ex) {
92+
System.err.println("Couldn't create session factory." + ex);
93+
throw new ExceptionInInitializerError(ex);
94+
}
95+
96+
Now we have that we can use it to save an Employee we make.
97+
98+
Session session = mFactory.openSession();
99+
Transaction tx = null;
100+
Long employeeID = null;
101+
try{
102+
tx = session.beginTransaction();
103+
Employee employee = new Employee(fname);
104+
employeeID = (Long) session.save(employee);
105+
tx.commit();
106+
}catch (HibernateException e) {
107+
if (tx!=null) tx.rollback();
108+
e.printStackTrace();
109+
}finally {
110+
session.close();
111+
}
112+
113+
We first get open a session via the factory, then begin a transaction, save your employee to that session, and commit it. The Employee should not be saved to the database.
114+
115+
Getting objects from the database is very much the same:
116+
117+
List employees = session.createQuery("FROM Employee").list();
118+
119+
We're create a query with HQL that gets everything from 'Employee'.
120+
121+
Updating a query is a matter of getting the object from the session variable, and then setting that to update:
122+
123+
Employee employee = (Employee)session.get(Employee.class, itsID);
124+
session.update(employee);
125+
126+
Deleting is the same, except you run session.delete() in place of session.update().

0 commit comments

Comments
 (0)