Skip to content

Commit 2cffa45

Browse files
committed
Hibernate with annotation mapping
1 parent 48a5c2f commit 2cffa45

13 files changed

Lines changed: 465 additions & 0 deletions

File tree

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<classpath>
3+
<classpathentry kind="src" output="target/classes" path="src">
4+
<attributes>
5+
<attribute name="optional" value="true"/>
6+
<attribute name="maven.pomderived" value="true"/>
7+
</attributes>
8+
</classpathentry>
9+
<classpathentry kind="src" path="resources"/>
10+
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
11+
<attributes>
12+
<attribute name="maven.pomderived" value="true"/>
13+
</attributes>
14+
</classpathentry>
15+
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
16+
<attributes>
17+
<attribute name="maven.pomderived" value="true"/>
18+
</attributes>
19+
</classpathentry>
20+
<classpathentry kind="output" path="target/classes"/>
21+
</classpath>
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<projectDescription>
3+
<name>HibernateAnnotation</name>
4+
<comment></comment>
5+
<projects>
6+
</projects>
7+
<buildSpec>
8+
<buildCommand>
9+
<name>org.eclipse.jdt.core.javabuilder</name>
10+
<arguments>
11+
</arguments>
12+
</buildCommand>
13+
<buildCommand>
14+
<name>org.eclipse.m2e.core.maven2Builder</name>
15+
<arguments>
16+
</arguments>
17+
</buildCommand>
18+
<buildCommand>
19+
<name>org.hibernate.eclipse.console.hibernateBuilder</name>
20+
<arguments>
21+
</arguments>
22+
</buildCommand>
23+
</buildSpec>
24+
<natures>
25+
<nature>org.eclipse.m2e.core.maven2Nature</nature>
26+
<nature>org.eclipse.jdt.core.javanature</nature>
27+
<nature>org.hibernate.eclipse.console.hibernateNature</nature>
28+
</natures>
29+
</projectDescription>
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
eclipse.preferences.version=1
2+
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
3+
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
4+
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
5+
org.eclipse.jdt.core.compiler.compliance=1.8
6+
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
7+
org.eclipse.jdt.core.compiler.debug.localVariable=generate
8+
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
9+
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
10+
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
11+
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
12+
org.eclipse.jdt.core.compiler.source=1.8
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
activeProfiles=
2+
eclipse.preferences.version=1
3+
resolveWorkspaceProjects=true
4+
version=1
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
default.configuration=HibernateAnnotation
2+
eclipse.preferences.version=1
3+
hibernate3.enabled=true
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3+
<modelVersion>4.0.0</modelVersion>
4+
<groupId>com.javahelps</groupId>
5+
<artifactId>HibernateAnnotation</artifactId>
6+
<version>0.0.1-SNAPSHOT</version>
7+
<build>
8+
<sourceDirectory>src</sourceDirectory>
9+
<plugins>
10+
<plugin>
11+
<artifactId>maven-compiler-plugin</artifactId>
12+
<version>3.1</version>
13+
<configuration>
14+
<source>1.8</source>
15+
<target>1.8</target>
16+
</configuration>
17+
</plugin>
18+
</plugins>
19+
</build>
20+
21+
<dependencies>
22+
<dependency>
23+
<groupId>org.hibernate</groupId>
24+
<artifactId>hibernate-core</artifactId>
25+
<version>4.3.10.Final</version>
26+
</dependency>
27+
28+
<dependency>
29+
<groupId>org.slf4j</groupId>
30+
<artifactId>slf4j-log4j12</artifactId>
31+
<version>1.7.12</version>
32+
</dependency>
33+
34+
<dependency>
35+
<groupId>org.javassist</groupId>
36+
<artifactId>javassist</artifactId>
37+
<version>3.20.0-GA</version>
38+
</dependency>
39+
40+
<dependency>
41+
<groupId>mysql</groupId>
42+
<artifactId>mysql-connector-java</artifactId>
43+
<version>5.1.36</version>
44+
</dependency>
45+
</dependencies>
46+
</project>
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<!DOCTYPE hibernate-configuration PUBLIC
3+
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
4+
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
5+
<hibernate-configuration>
6+
<session-factory>
7+
<!-- Create table if not exists -->
8+
<property name="hibernate.hbm2ddl.auto">update</property>
9+
<!-- The JDBC driver of your database -->
10+
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
11+
<!-- Indicate the database to generate suitable SQL -->
12+
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
13+
<!-- The JDBC URL to the database instance -->
14+
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/javahelps</property>
15+
<!-- The database username -->
16+
<property name="hibernate.connection.username">root</property>
17+
<!-- The database password -->
18+
<property name="hibernate.connection.password">root</property>
19+
<!-- Mapping class -->
20+
<mapping class="com.javahelps.hibernate.Student"></mapping>
21+
</session-factory>
22+
</hibernate-configuration>
Lines changed: 197 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
1+
package com.javahelps.hibernate;
2+
3+
import java.util.List;
4+
import java.util.Properties;
5+
6+
import org.hibernate.HibernateException;
7+
import org.hibernate.Session;
8+
import org.hibernate.SessionFactory;
9+
import org.hibernate.Transaction;
10+
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
11+
import org.hibernate.cfg.Configuration;
12+
import org.hibernate.service.ServiceRegistry;
13+
14+
public class Main {
15+
// Create the SessionFactory when you start the application.
16+
private static final SessionFactory SESSION_FACTORY;
17+
18+
/**
19+
* Initialize the SessionFactory instance.
20+
*/
21+
static {
22+
// Create a Configuration object.
23+
Configuration config = new Configuration();
24+
// Configure using the application resource named hibernate.cfg.xml.
25+
config.configure();
26+
// Extract the properties from the configuration file.
27+
Properties prop = config.getProperties();
28+
29+
// Create StandardServiceRegistryBuilder using the properties.
30+
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
31+
builder.applySettings(prop);
32+
33+
// Build a ServiceRegistry
34+
ServiceRegistry registry = builder.build();
35+
36+
// Create the SessionFactory using the ServiceRegistry
37+
SESSION_FACTORY = config.buildSessionFactory(registry);
38+
}
39+
40+
public static void main(String[] args) {
41+
// Create two Students
42+
create(1, "Alice", 22); // Alice will get an id 1
43+
create(2, "Bob", 20); // Bob will get an id 2
44+
create(3, "Charlie", 25); // Charlie will get an id 3
45+
46+
// Update the age of Bob using the id
47+
upate(2, "Bob", 25);
48+
49+
// Delete the Alice from database
50+
delete(1);
51+
52+
// Print all the Students
53+
List<Student> students = readAll();
54+
if (students != null) {
55+
for (Student stu : students) {
56+
System.out.println(stu);
57+
}
58+
}
59+
60+
// NEVER FORGET TO CLOSE THE SESSION_FACTORY
61+
SESSION_FACTORY.close();
62+
}
63+
64+
/**
65+
* Create a new Student.
66+
*
67+
* @param name
68+
* @param age
69+
*/
70+
public static void create(int id, String name, int age) {
71+
// Create a session
72+
Session session = SESSION_FACTORY.openSession();
73+
Transaction transaction = null;
74+
try {
75+
// Begin a transaction
76+
transaction = session.beginTransaction();
77+
Student stu = new Student();
78+
stu.setId(id);
79+
stu.setName(name);
80+
stu.setAge(age);
81+
// Save the student
82+
session.save(stu);
83+
// Commit the transaction
84+
transaction.commit();
85+
} catch (HibernateException ex) {
86+
// If there are any exceptions, roll back the changes
87+
if (transaction != null) {
88+
transaction.rollback();
89+
}
90+
// Print the Exception
91+
ex.printStackTrace();
92+
} finally {
93+
// Close the session
94+
session.close();
95+
}
96+
}
97+
98+
/**
99+
* Read all the Students.
100+
*
101+
* @return a List of Students
102+
*/
103+
public static List<Student> readAll() {
104+
List<Student> students = null;
105+
// Create a session
106+
Session session = SESSION_FACTORY.openSession();
107+
Transaction transaction = null;
108+
try {
109+
// Begin a transaction
110+
transaction = session.beginTransaction();
111+
students = session.createQuery("FROM Student").list();
112+
// Commit the transaction
113+
transaction.commit();
114+
} catch (HibernateException ex) {
115+
// If there are any exceptions, roll back the changes
116+
if (transaction != null) {
117+
transaction.rollback();
118+
}
119+
// Print the Exception
120+
ex.printStackTrace();
121+
} finally {
122+
// Close the session
123+
session.close();
124+
}
125+
return students;
126+
}
127+
128+
/**
129+
* Delete the existing Student.
130+
*
131+
* @param id
132+
*/
133+
public static void delete(int id) {
134+
// Create a session
135+
Session session = SESSION_FACTORY.openSession();
136+
Transaction transaction = null;
137+
try {
138+
// Begin a transaction
139+
transaction = session.beginTransaction();
140+
// Get the Student from the database.
141+
Student stu = (Student) session.get(Student.class,
142+
Integer.valueOf(id));
143+
// Delete the student
144+
session.delete(stu);
145+
// Commit the transaction
146+
transaction.commit();
147+
} catch (HibernateException ex) {
148+
// If there are any exceptions, roll back the changes
149+
if (transaction != null) {
150+
transaction.rollback();
151+
}
152+
// Print the Exception
153+
ex.printStackTrace();
154+
} finally {
155+
// Close the session
156+
session.close();
157+
}
158+
}
159+
160+
/**
161+
* Update the existing Student.
162+
*
163+
* @param id
164+
* @param name
165+
* @param age
166+
*/
167+
public static void upate(int id, String name, int age) {
168+
// Create a session
169+
Session session = SESSION_FACTORY.openSession();
170+
Transaction transaction = null;
171+
try {
172+
// Begin a transaction
173+
transaction = session.beginTransaction();
174+
// Get the Student from the database.
175+
Student stu = (Student) session.get(Student.class,
176+
Integer.valueOf(id));
177+
// Change the values
178+
stu.setName(name);
179+
stu.setAge(age);
180+
// Update the student
181+
session.update(stu);
182+
183+
// Commit the transaction
184+
transaction.commit();
185+
} catch (HibernateException ex) {
186+
// If there are any exceptions, roll back the changes
187+
if (transaction != null) {
188+
transaction.rollback();
189+
}
190+
// Print the Exception
191+
ex.printStackTrace();
192+
} finally {
193+
// Close the session
194+
session.close();
195+
}
196+
}
197+
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package com.javahelps.hibernate;
2+
3+
import java.io.Serializable;
4+
5+
import javax.persistence.Column;
6+
import javax.persistence.Entity;
7+
import javax.persistence.Id;
8+
import javax.persistence.Table;
9+
10+
@Entity
11+
@Table(name = "student")
12+
public class Student implements Serializable {
13+
@Id
14+
@Column(name = "student_id", unique = true)
15+
private int id;
16+
17+
@Column(name = "student_name", nullable = false)
18+
private String name;
19+
20+
@Column(name = "student_age", nullable = false)
21+
private int age;
22+
23+
public int getId() {
24+
return id;
25+
}
26+
27+
public void setId(int id) {
28+
this.id = id;
29+
}
30+
31+
public String getName() {
32+
return name;
33+
}
34+
35+
public void setName(String name) {
36+
this.name = name;
37+
}
38+
39+
public int getAge() {
40+
return age;
41+
}
42+
43+
public void setAge(int age) {
44+
this.age = age;
45+
}
46+
47+
@Override
48+
public String toString() {
49+
return id + "\t" + name + "\t" + age;
50+
}
51+
}

0 commit comments

Comments
 (0)