Hibernate / Hibernate 7 Basics Interview Questions
What is Hibernate 7's @Struct mapping for database composite types?
Hibernate 7 adds @Struct for mapping Java records to database composite/structured types (native types in PostgreSQL, Oracle, DB2) stored as a single column value.
import org.hibernate.annotations.Struct; @Embeddable @Struct(name="address_type") // maps to the DB composite type public record AddressType( String street, String city, String postcode, String countryCode ) {} @Entity public class Customer { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; private String name; @Column(name="shipping_address") // single column of type address_type! private AddressType shippingAddress; } // PostgreSQL DDL: // CREATE TYPE address_type AS ( // street VARCHAR(255), // city VARCHAR(100), // postcode VARCHAR(10), // country_code VARCHAR(2) // ); // CREATE TABLE customer ( // id BIGINT PRIMARY KEY, // name VARCHAR(255), // shipping_address address_type -- single composite column! // ); // HQL querying the struct: List<Customer> london = session .createQuery("FROM Customer c WHERE c.shippingAddress.city = :city", Customer.class) .setParameter("city", "London").getResultList(); // Generated: WHERE (shipping_address).city = 'London'
More Related questions...