May 17, 2021 Hibernate
2. The environment settings for Hibernate comments
3. An example of a comment class
So far, you've seen how Hibernate uses XML mapping files to complete data transformations from POJO to database tables, and vice versa. H ibernate comments are the latest way to define a map without using an XML file. You can use additional comments or directly instead of XML mapping metadata.
Hibernate annotations are a powerful way to provide metadata to objects and relationship maps. All metadata is added to the POJO java file code, which allows users to better understand the structure of the table and POJO when developing.
If you want your application to port to other EJB 3 ORM applications, you must use comments to represent mapping information, but if you want more flexibility, you should use XML-based mapping.
First you have to make sure you're using JDK 5.0, otherwise you'll need to upgrade your JDK to JDK 5.0 to enable your console to support annotations.
Second, you need to install hibernate 3.x comment packs, which can be downloaded from sourceforge lines: (download Hibernate comments) and copy hibernate-annotations.jar, lib/hibernate-comons-annotations.jar and lib/ejb3-persistence.jar to your CLASSPATH.
As I mentioned above, all metadata is added to the POJO java file code, which helps users better understand the structure of the table and POJO when developing.
Below we will use the EMPLOYEE table to store objects:
create table EMPLOYEE (
id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default NULL,
PRIMARY KEY (id)
);
Here's how to map objects that use a defined Employee table with an Employee class with comments:
import javax.persistence.*;
@Entity
@Table(name = "EMPLOYEE")
public class Employee {
@Id @GeneratedValue
@Column(name = "id")
private int id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "salary")
private int salary;
public Employee() {}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName( String first_name ) {
this.firstName = first_name;
}
public String getLastName() {
return lastName;
}
public void setLastName( String last_name ) {
this.lastName = last_name;
}
public int getSalary() {
return salary;
}
public void setSalary( int salary ) {
this.salary = salary;
}
}
Hibernate detected @Id comment field and determined that it should access properties on an object directly through the field at runtime. I f you put @Id comments in the getId() method, you can access the properties through the default getter and setter methods. T herefore, all other comments are also placed in the field or getter method, which is determined by the policy selected. The next section explains the comments used in the class above.
Comments for the EJB 3 standard are included in the javax.persistence package, so our first step is to import the package. The second step we use @Entity comments for the Employee class, which marks the class as an entity bean, so it must contain a constructor without arguments and be visible in the protectable range.
@table allows you to clarify the details of the table to ensure that the entity persists in the database.
@table provides four properties that allow you to override the name of the table, the directory, and its patterns, where you can make unique constraints on columns. Now we're using a table name, EMPLOYEE.
Each entity bean has a primary key that you can comment on in a class @Id the entity bean. The primary key can be a field or a combination of multiple fields, depending on the structure of your table.
By default, @Id comment automatically determines the most appropriate primary key generation policy, but you can override it by using @GeneratedValue comment. tegy and generator, I'm not going to discuss here, so we only use the default keys to generate policies. Let Hibernate determine which generator types are used to port code between different databases.
@Column is used to specify the details of a column's mapping with a field or property. You can use the most common properties of the following comments:
Finally, we'll create the application class and run the application using the main() method. We'll use this application to hold some employee records, and then we'll crudd those records.
import java.util.List;
import java.util.Date;
import java.util.Iterator;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class ManageEmployee {
private static SessionFactory factory;
public static void main(String[] args) {
try{
factory = new AnnotationConfiguration().
configure().
//addPackage("com.xyz") //add package if used.
addAnnotatedClass(Employee.class).
buildSessionFactory();
}catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
ManageEmployee ME = new ManageEmployee();
/* Add few employee records in database */
Integer empID1 = ME.addEmployee("Zara", "Ali", 1000);
Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
Integer empID3 = ME.addEmployee("John", "Paul", 10000);
/* List down all the employees */
ME.listEmployees();
/* Update employee's records */
ME.updateEmployee(empID1, 5000);
/* Delete an employee from the database */
ME.deleteEmployee(empID2);
/* List down new list of the employees */
ME.listEmployees();
}
/* Method to CREATE an employee in the database */
public Integer addEmployee(String fname, String lname, int salary){
Session session = factory.openSession();
Transaction tx = null;
Integer employeeID = null;
try{
tx = session.beginTransaction();
Employee employee = new Employee();
employee.setFirstName(fname);
employee.setLastName(lname);
employee.setSalary(salary);
employeeID = (Integer) session.save(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return employeeID;
}
/* Method to READ all the employees */
public void listEmployees( ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
List employees = session.createQuery("FROM Employee").list();
for (Iterator iterator =
employees.iterator(); iterator.hasNext();){
Employee employee = (Employee) iterator.next();
System.out.print("First Name: " + employee.getFirstName());
System.out.print(" Last Name: " + employee.getLastName());
System.out.println(" Salary: " + employee.getSalary());
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
/* Method to UPDATE salary for an employee */
public void updateEmployee(Integer EmployeeID, int salary ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class, EmployeeID);
employee.setSalary( salary );
session.update(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
/* Method to DELETE an employee from the records */
public void deleteEmployee(Integer EmployeeID){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class, EmployeeID);
session.delete(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
}
Now, let's create a hibernate .cfg.xml profile to define database-related parameters.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!-- Assume students is the database name -->
<property name="hibernate.connection.url">
jdbc:mysql://localhost/test
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
cohondob
</property>
</session-factory>
</hibernate-configuration>
Here are the steps to compile and run the application mentioned above. Before you continue compiling and running, you need to make sure that you set the paths and class paths correctly.
You will get the following results, which will be recorded in the EMPLOYEE table.
$java ManageEmployee
.......VARIOUS LOG MESSAGES WILL DISPLAY HERE........
First Name: Zara Last Name: Ali Salary: 1000
First Name: Daisy Last Name: Das Salary: 5000
First Name: John Last Name: Paul Salary: 10000
First Name: Zara Last Name: Ali Salary: 5000
First Name: John Last Name: Paul Salary: 10000
If you look at the EMPLOYEE table, it will have the following records:
mysql> select * from EMPLOYEE;
+----+------------+-----------+--------+
| id | first_name | last_name | salary |
+----+------------+-----------+--------+
| 29 | Zara | Ali | 5000 |
| 31 | John | Paul | 10000 |
+----+------------+-----------+--------+
2 rows in set (0.00 sec
mysql>