Java Hibernate is an open-source Java framework that simplifies the process of working with relational databases. It provides an object-oriented approach to database operations, allowing developers to work with Java objects instead of writing tedious SQL queries.Hibernate, a popular object-relational mapping (ORM) framework for Java.

Before We start lets make sure we have data base created and configured in application.properties if not please refer here

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Table(name="book")
@Entity
public class Book{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", updatable = false, nullable = false)
    private Long id;

    @Column(name = "name", nullable = false)
    private String name;

    @Column(name = "code", nullable = false)
    private String code;

    @Column(name = "description")
    private String description;
}
  1. Mapping Entities to Tables : To create a table in Hibernate you need to map entity class to corresponding table using @Table annotation, and you can use name keyword to define table name. In above example we have defined @Table(name="book"), here entity class is Book.java and table name is book.

  2. Defining Columns:  Each attribute of an entity class represents a column in the table. To define a column, you can use annotations such as @Column and provide additional properties like the column name, data type, and constraints. @Column(name = "code", nullable = false) name of column is code and nullable false means we can not have null value which is not null in mysql, and private String code; here data type of code column is String which is nothing but varchar in mysql.

  3. Mapping Relationships: Tables often have relationships with other tables, such as one-to-one, one-to-many, or many-to-many relationships. Hibernate provides annotations like @OneToOne, @OneToMany, and @ManyToMany to establish these relationships.

 

Before Starting application change this properties spring.jpa.hibernate.ddl-auto=update and also make sure we have data base created, I have created data base as book_store. Login to mysql using root userid and password,

Run command :

        create database your_db_name; (create database book_store)

      use your_db_name;  ( use book_store);

Right click on main class and run as java application, now you should see table created, Run show tables command to see tables.

Mysql table using java hibernate

Here we see whatever we have defined in Book.java same column has been created. Now we can easily store and retrieve data from table using services.

 

 

4 Replies to “Java Hibernate Magic: Create MySQL Tables with Ease and Efficiency”

Leave a Reply

Your email address will not be published. Required fields are marked *