Java.Hibernate.Beginner.How do you map a Java class to a database table in Hibernate?

You can map a Java class to a database table in Hibernate in two main ways:


🔹 1) Using JPA annotations (modern, recommended)
Add annotations directly to your Java class:

import javax.persistence.*;

@Entity                    // Marks the class as a persistent entity
@Table(name = "users")     // Maps the class to the 'users' table
public class User {

    @Id                    // Marks this field as the primary key
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "username") // Maps 'username' field to 'username' column
    private String username;

    @Column(name = "email")    // Maps 'email' field to 'email' column
    private String email;

    // getters and setters
}

✅ With annotations:

  • @Entity: tells Hibernate this class should be persisted.
  • @Table: specifies the table name (optional if it matches class name).
  • @Id: defines the primary key.
  • @Column: customizes the column name, type, etc.

🔹 2) Using XML mapping files (older approach)
Create an XML file (e.g., User.hbm.xml):

<!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="com.example.User" table="users">
    <id name="id" column="id">
      <generator class="native"/>
    </id>
    <property name="username" column="username"/>
    <property name="email" column="email"/>
  </class>
</hibernate-mapping>

✅ In hibernate.cfg.xml, include the mapping:

<mapping resource="com/example/User.hbm.xml"/>

🔹 Key differences:

  • Annotations keep mappings close to your code (easier to read and maintain).
  • XML mappings let you change the mapping without modifying Java source code (useful for certain legacy or dynamic scenarios).

Key takeaway:
You map a Java class to a database table in Hibernate by defining:

  • The class as an @Entity (or XML <class> element),
  • The table name with @Table or table="" in XML,
  • The fields with @Column or <property> in XML.
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.