How to map persistent classes in Hibernate?

In Hibernate, there are two ways to map persistent classes: using annotations or XML configuration files.

  1. Using annotation method:
  2. Use the @Entity annotation on the persistence class to mark it as an entity class.
  3. Use the @Id annotation to mark the primary key property.
  4. Mark attributes with the @Column annotation to specify the mapping relationship between attributes and columns in the database table.
  5. Use annotations such as @OneToMany, @ManyToOne, @OneToOne, @ManyToMany to mark the relationships between entity classes.
  6. Annotate the details of the relationship using annotations such as @JoinTable and @JoinColumn.
  7. Mark the properties that do not need to be persisted to the database with the @Transient annotation.
  8. Use the @Enumerated annotation to mark properties of enumerated types.
  9. The example code is as follows:
  10. @Entity annotation class named Student is defined to represent a table in the database with the name “student”. It includes an Id generated using the GenerationType.IDENTITY strategy, a name column of type String, and a list of courses associated with the student.
  11. By using the XML configuration file method:
  12. Create a configuration file named hibernate.cfg.xml to set up database connection and other Hibernate-related configurations.
  13. Create an XML file named mapping.hbm.xml, and encapsulate the mapping information using tags.
  14. Persistent classes are defined using tags under the mapping tag, with attributes and associations of the class defined using tags such as , , and .
  15. Use the tag in hibernate.cfg.xml to import the mapping.hbm.xml file.
  16. The code example is as follows:
  17. In the Hibernate mapping file, we have defined a mapping for the “Student” class with properties like id, name, and one-to-many relationship with the “Course” class.

The above is the basic way to map persistent classes in Hibernate, specific mapping details and configurations can be adjusted according to actual situations.

广告
Closing in 10 seconds
bannerAds