ImplicitNamingStrategy 是在 JPA 之外 Hibernate 特有的方式。也可以处理 Multiple embeddable types 。
使用 org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl
package org.example.demo.hibernate;
import javax.persistence.Embeddable;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
public class Test {
public static void main(String[] args) {
ServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
.applySetting("hibernate.connection.url", "jdbc:p6spy:postgresql://localhost:5432/test")
.applySetting("hibernate.connection.username", "postgres")
.applySetting("hibernate.connection.password", "postgres")
.applySetting("hibernate.hbm2ddl.auto", "create").build();
Metadata metadata = new MetadataSources(standardRegistry).addAnnotatedClass(Contact.class).getMetadataBuilder()
.applyImplicitNamingStrategy(ImplicitNamingStrategyComponentPathImpl.INSTANCE).build();
SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build();
Session session = sessionFactory.openSession();
session.beginTransaction();
Contact contact = new Contact();
contact.home = new Address();
contact.home.addr = "Beijing";
contact.home.zipcode = "100000";
contact.work = new Address();
contact.work.addr = "Shanghai";
contact.work.zipcode = "200000";
session.persist(contact);
session.getTransaction().commit();
session.close();
sessionFactory.close();
}
@Entity(name = "Contact")
public static class Contact {
@Id
@GeneratedValue
Integer id;
@Embedded
Address home;
@Embedded
Address work;
}
@Embeddable
public static class Address {
String addr;
String zipcode;
}
}
生成 SQL
drop table if exists Contact cascade
drop sequence if exists hibernate_sequence
create sequence hibernate_sequence start 1 increment 1
create table Contact (id int4 not null, home_addr varchar(255), home_zipcode varchar(255), work_addr varchar(255), work_zipcode varchar(255), primary key (id))
select nextval ('hibernate_sequence')
insert into Contact (home_addr, home_zipcode, work_addr, work_zipcode, id) values ('Beijing', '100000', 'Shanghai', '200000', 1)