How to map persistent classes in Hibernate?
In Hibernate, there are two ways to map persistent classes: using annotations or XML configuration files.
- Using annotation method:
- Use the @Entity annotation on the persistence class to mark it as an entity class.
- Use the @Id annotation to mark the primary key property.
- Mark attributes with the @Column annotation to specify the mapping relationship between attributes and columns in the database table.
- Use annotations such as @OneToMany, @ManyToOne, @OneToOne, @ManyToMany to mark the relationships between entity classes.
- Annotate the details of the relationship using annotations such as @JoinTable and @JoinColumn.
- Mark the properties that do not need to be persisted to the database with the @Transient annotation.
- Use the @Enumerated annotation to mark properties of enumerated types.
- The example code is as follows:
- @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.
- By using the XML configuration file method:
- Create a configuration file named hibernate.cfg.xml to set up database connection and other Hibernate-related configurations.
- Create an XML file named mapping.hbm.xml, and encapsulate the mapping information using tags.
- Persistent classes are defined using tags under the mapping tag, with attributes and associations of the class defined using tags such as
, , and . - Use the
tag in hibernate.cfg.xml to import the mapping.hbm.xml file. - The code example is as follows:
- 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.