Hibernate Example using JPA and MySQL

Hibernate Example using JPA and MySQL

Let's walk through a simple example of setting up a Hibernate project with JPA (Java Persistence API) and MySQL.

1. Setup

Dependencies: You'll need the following Maven dependencies:

<!-- MySQL JDBC Driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.26</version> <!-- Use the latest version --> </dependency> <!-- Hibernate ORM and JPA --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.5.6.Final</version> <!-- Use the latest version --> </dependency> <!-- JPA API --> <dependency> <groupId>javax.persistence</groupId> <artifactId>javax.persistence-api</artifactId> <version>2.2</version> </dependency> 

2. Entity Creation

Let's create a simple Book entity.

@Entity @Table(name = "book") public class Book { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "title") private String title; @Column(name = "author") private String author; // Constructors, getters, setters... } 

3. Persistence Configuration

Create a persistence.xml file under src/main/resources/META-INF/.

<?xml version="1.0" encoding="UTF-8"?> <persistence version="2.2" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd"> <persistence-unit name="book_pu"> <!-- Entity classes --> <class>com.example.Book</class> <!-- Provider and DataSource --> <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL8Dialect"/> <property name="hibernate.hbm2ddl.auto" value="update"/> <property name="hibernate.show_sql" value="true"/> <property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test_db"/> <property name="javax.persistence.jdbc.user" value="root"/> <property name="javax.persistence.jdbc.password" value="password"/> </properties> </persistence-unit> </persistence> 

Note: Update the database connection details (URL, user, password) as per your MySQL setup.

4. CRUD Operations

You can perform CRUD operations using the EntityManager.

public class BookService { private EntityManagerFactory emf = Persistence.createEntityManagerFactory("book_pu"); private EntityManager em = emf.createEntityManager(); public Book addBook(String title, String author) { Book book = new Book(); book.setTitle(title); book.setAuthor(author); em.getTransaction().begin(); em.persist(book); em.getTransaction().commit(); return book; } public Book findBook(Long id) { return em.find(Book.class, id); } // You can add update and delete methods in a similar fashion. } 

5. Running the Application

Here's a simple main class to add a book:

public class Main { public static void main(String[] args) { BookService bookService = new BookService(); Book book = bookService.addBook("Hibernate in Action", "Christian Bauer"); System.out.println("Book ID: " + book.getId()); Book foundBook = bookService.findBook(book.getId()); System.out.println("Found Book Title: " + foundBook.getTitle()); } } 

When you run this, Hibernate will interact with MySQL using JPA, creating the book table (if it doesn't exist) and adding a new entry.

Remember, this is a basic example to get you started. In a real-world scenario, you'd integrate dependency injection, handle exceptions, and potentially integrate with a framework like Spring.

Examples

  1. Hibernate JPA configuration with MySQL:

    • Description: Configure the persistence.xml file to set up the JPA configuration, including the database connection details for MySQL.
    • Code:
      <!-- persistence.xml --> <persistence-unit name="example-unit" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider> <properties> <property name="hibernate.connection.driver_class" value="com.mysql.cj.jdbc.Driver"/> <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/your_database"/> <property name="hibernate.connection.username" value="your_username"/> <property name="hibernate.connection.password" value="your_password"/> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/> <!-- other properties --> </properties> </persistence-unit> 
  2. Creating entities for Hibernate JPA with MySQL:

    • Description: Define JPA entities that map to the corresponding MySQL database tables. Use annotations such as @Entity, @Table, @Id, etc.
    • Code:
      @Entity @Table(name = "employee") public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String firstName; private String lastName; // Getters and setters } 
  3. Mapping relationships in Hibernate JPA with MySQL:

    • Description: Use JPA annotations such as @ManyToOne, @OneToMany, etc., to map relationships between entities in MySQL.
    • Code:
      @Entity @Table(name = "department") public class Department { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @OneToMany(mappedBy = "department") private List<Employee> employees; // Getters and setters } 
  4. Hibernate JPA query examples for MySQL:

    • Description: Use JPQL (Java Persistence Query Language) or native queries to retrieve data from MySQL using Hibernate and JPA.
    • Code:
      // JPQL example TypedQuery<Employee> query = entityManager.createQuery("SELECT e FROM Employee e WHERE e.firstName = :firstName", Employee.class); query.setParameter("firstName", "John"); List<Employee> employees = query.getResultList(); 

More Tags

pojo hessian gdal distinct-values multiclass-classification shoutcast colorbar masm cp1252 connection-pooling

More Programming Guides

Other Guides

More Programming Examples