Advertisements
You can choose different strategies for building a Hibernate application. For example, you could start building Java classes and map files from scratch, and then let Hibernate generate the database schema accordingly. You can also start from a database schema and reverse engineer it into Java classes and Hibernate mapping files. We will choose the latter option, which is also the fastest. Here's an overview of our application.
In this example, we will design an employee agenda divided into departments. The persistence model will be developed with Hibernate, using the reverse engineering facet of JBoss tools. We will then need an interface for recording our employees and departments, and to query them as well.
The web interface will be developed using a simple Model-View-Controller (MVC) pattern and basic JSP 2.0 and servlet features.
The overall architecture of this system resembles the AppStore application that has been used to introduce JPA. As a matter of fact, this example can be used to compare the two persistence models and to decide which option best suits your project needs. We have added a short section at the end of this example to stress a few important points about this choice.
Setting up the database schema
As our first step, we are going to create the necessary tables for our example. Launch a MySQL client and issue the following DDL:
CREATE schema hibernate;
GRANT ALL PRIVILEGES ON hibernate.* TO 'jboss'@'localhost' WITH GRANT
OPTION;
CREATE TABLE `hibernate`.`department` (
`department_id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`department_name` VARCHAR(45) NOT NULL,
PRIMARY KEY (`department_id`)
)
ENGINE = InnoDB;
CREATE TABLE `hibernate`.`employee` (
`employee_id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`employee_name` VARCHAR(45) NOT NULL,
`employee_salary` INTEGER UNSIGNED NOT NULL,
`employee_department_id` INTEGER UNSIGNED NOT NULL,
PRIMARY KEY (`employee_id`),
CONSTRAINT `FK_employee_1` FOREIGN KEY `FK_employee_1` (`employee_
department_id`)
REFERENCES `department` (`department_id`)
ON DELETE CASCADE
ON UPDATE CASCADE
)
ENGINE = InnoDB;
With the first Data Definition Language (DDL) command, we have created a schema named Hibernate that will be used to store our tables. Then, we have assigned the necessary privileges on the Hibernate schema to the user jboss (created in Chapter 5, Developing JPA Entities).
Finally, we created a table named department that contains the list of company units, and another table named employee that contains the list of workers. The employee table references the department with a foreign key constraint.