How to implement mapping of Hibernate array objects?
In Hibernate, you can use the @ElementCollection annotation to map an array object to the database.
Firstly, you need to define an array object property in the entity class and annotate it with @ElementCollection. Additionally, you must specify the @CollectionTable and @Column annotations to define the name of the collection table and column.
For example, consider a User entity class with an array object addresses of type String, which can be mapped in the following way:
@Entity
public class User {
@Id
private Long id;
@ElementCollection
@CollectionTable(name = "user_addresses", joinColumns = @JoinColumn(name = "user_id"))
@Column(name = "address")
private String[] addresses;
// getters and setters
}
In the above code, the @ElementCollection annotation is used to indicate that the property is a collection type, the @CollectionTable annotation is used to specify the name of the collection table as “user_addresses”, and the joinColumns attribute is used to specify the associated field with the User table. The @Column annotation is used to specify the column name in the collection table as “address”.
In this way, when saving a User entity object, the addresses array will be mapped to a collection table named “user_addresses”, where each address will be saved in a row of that table.