当一个 entity 中包含一个 embeddable type 多次时, JPA 需要显式定义列名。

package org.example.demo.hibernate;

import javax.persistence.Embeddable;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Persistence;

public class Test {
    public static void main(String[] args) {
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("test");
        EntityManager em = factory.createEntityManager();

        em.getTransaction().begin();
        Contact person = new Contact();
        person.home = new Address();
        person.home.addr = "Beijing";
        person.home.zipcode = "100000";
        person.work = new Address();
        person.work.addr = "Shanghai";
        person.work.zipcode = "200000";
        em.persist(person);
        em.getTransaction().commit();

        em.close();
        factory.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;
    }
}

将抛异常 org.hibernate.MappingException: Repeated column in mapping for entity: org.example.demo.hibernate.Test$Contact column: addr (should be mapped with insert="false" update="false")

results matching ""

    No results matching ""