creating an Employee entity class using Hibernate annotations, along with sample
data insertion:
Step 1: Create a Maven Project
You can create a Maven project using your preferred IDE or by running the following
command in your terminal:
bash
mvn archetype:generate -DgroupId=com.example -DartifactId=hibernate-example -
DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
Step 2: Add Dependencies in pom.xml
Add the necessary dependencies for Hibernate and your database driver in the
pom.xml file:
xml:
<dependencies>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.5.7.Final</version>
</dependency>
<!-- Database Driver -->
<!-- Add the appropriate driver based on your database (e.g., MySQL,
PostgreSQL, etc.) -->
</dependencies>
Step 3: Create hibernate.cfg.xml
Create hibernate.cfg.xml in the src/main/resources directory. This file contains
Hibernate configuration properties and connection settings. Here's a sample
configuration for MySQL:
XML
<?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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property
name="connection.url">jdbc:mysql://localhost:3306/your_database</property>
<property name="connection.username">your_username</property>
<property name="connection.password">your_password</property>
<!-- Hibernate dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Mapping files -->
<!-- Add mapping files here if using XML mapping -->
</session-factory>
</hibernate-configuration>
Step 4: Create Employee Entity Class
Create a Java class Employee in the package com.example.model with Hibernate
annotations:
java
package com.example.model;
import javax.persistence.*;
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "salary")
private double salary;
// Constructors, getters, setters
}
Step 5: Insert Sample Data
To insert sample data, you can write a sample Java application or use Hibernate's
built-in functionality to insert data. Here's an example of inserting sample data
using Hibernate:
java
package com.example;
import com.example.model.Employee;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class App {
public static void main(String[] args) {
// Create session factory
SessionFactory factory = new
Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
// Create session
Session session = factory.openSession();
// Begin transaction
Transaction transaction = session.beginTransaction();
// Create and insert sample data
Employee employee1 = new Employee();
employee1.setName("John Doe");
employee1.setSalary(50000);
session.save(employee1);
Employee employee2 = new Employee();
employee2.setName("Jane Smith");
employee2.setSalary(60000);
session.save(employee2);
// Commit transaction
transaction.commit();
// Close session
session.close();
// Close session factory
factory.close();
}
}
Step 6: Run the Application
Compile and run the application. Make sure your database server is running and
accessible.
Step 4: Create Department Entity Class
Create a Java class Department in the package com.example.model with Hibernate
annotations:
java
package com.example.model;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "department")
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@OneToMany(mappedBy = "department", cascade = CascadeType.ALL)
private List<Employee> employees = new ArrayList<>();
// Constructors, getters, setters
}
Step 5: Update Employee Entity Class
Update the Employee class to include a ManyToOne relationship with Department:
java
package com.example.model;
import javax.persistence.*;
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "salary")
private double salary;
@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
// Constructors, getters, setters
}
Step 6: Insert Sample Data with Relationships
Update the sample data insertion code to include relationships between Department
and Employee:
java
public class App {
public static void main(String[] args) {
// Create session factory
SessionFactory factory = new
Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
// Create session
Session session = factory.openSession();
// Begin transaction
Transaction transaction = session.beginTransaction();
// Create departments
Department department1 = new Department();
department1.setName("Engineering");
Department department2 = new Department();
department2.setName("Marketing");
session.save(department1);
session.save(department2);
// Create employees and assign them to departments
Employee employee1 = new Employee();
employee1.setName("John Doe");
employee1.setSalary(50000);
employee1.setDepartment(department1);
Employee employee2 = new Employee();
employee2.setName("Jane Smith");
employee2.setSalary(60000);
employee2.setDepartment(department1);
Employee employee3 = new Employee();
employee3.setName("Mike Johnson");
employee3.setSalary(55000);
employee3.setDepartment(department2);
session.save(employee1);
session.save(employee2);
session.save(employee3);
// Commit transaction
transaction.commit();
// Close session
session.close();
// Close session factory
factory.close();
}
}
Step 7: CRUD Operations
You can now perform CRUD operations on Employee and Department entities. For
example, to retrieve all employees in a department:
java
// Assuming departmentId is the ID of the department
Department department = session.get(Department.class, departmentId);
List<Employee> employees = department.getEmployees();
for (Employee employee : employees) {
System.out.println("Employee Name: " + employee.getName());
}
Similarly, you can perform operations like updating and deleting entities as
needed.
With these additions, your application now includes multiple entities,
relationships between them, and basic CRUD operations.
SK
includes multiple entities, relationships between them, and basic CRUD operations.
ChatGPT
Certainly! Let's expand the example to include multiple entities, relationships
between them, and basic CRUD operations for Employee, Department, and User.
Step 4: Create User Entity Class
Create a Java class User in the package com.example.model with Hibernate
annotations:
java
package com.example.model;
import javax.persistence.*;
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "username")
private String username;
@Column(name = "email")
private String email;
// Constructors, getters, setters
}
Step 5: Update Employee Entity Class
Update the Employee class to include a OneToOne relationship with User:
java
package com.example.model;
import javax.persistence.*;
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "salary")
private double salary;
@OneToOne
@JoinColumn(name = "user_id")
private User user;
// Constructors, getters, setters
}
Step 6: Update Department Entity Class
Update the Department class to include a OneToMany relationship with Employee:
java
package com.example.model;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "department")
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@OneToMany(mappedBy = "department", cascade = CascadeType.ALL)
private List<Employee> employees = new ArrayList<>();
// Constructors, getters, setters
}
Step 7: CRUD Operations
Now, let's perform CRUD operations on Employee, Department, and User entities.
java
public class App {
public static void main(String[] args) {
// Create session factory
SessionFactory factory = new
Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
// Create session
Session session = factory.openSession();
// Begin transaction
Transaction transaction = session.beginTransaction();
// Create and save a user
User user = new User();
user.setUsername("john_doe");
user.setEmail("john@example.com");
session.save(user);
// Create and save a department
Department department = new Department();
department.setName("Engineering");
session.save(department);
// Create and save an employee associated with the user and department
Employee employee = new Employee();
employee.setName("John Doe");
employee.setSalary(50000);
employee.setUser(user);
employee.setDepartment(department);
session.save(employee);
// Commit transaction
transaction.commit();
// Retrieve an employee by ID
transaction = session.beginTransaction();
Employee retrievedEmployee = session.get(Employee.class, employee.getId());
System.out.println("Retrieved Employee: " + retrievedEmployee.getName());
// Update employee details
retrievedEmployee.setSalary(55000);
session.update(retrievedEmployee);
transaction.commit();
// Delete an employee
transaction = session.beginTransaction();
session.delete(retrievedEmployee);
transaction.commit();
// Close session
session.close();
// Close session factory
factory.close();
}
}