【问题标题】:Hibernate. How to map own class as type of property in entity?休眠。如何将自己的类映射为实体中的属性类型?
【发布时间】:2026-02-02 05:00:01
【问题描述】:

如何将我自己的类与 Hibernate 映射为其他类中的属性类型?例如,我有 Address 类和 User 类。我尝试如下映射:

public class User {
    private Long id;
    private Address address;
    // other fields
}

但在这种情况下我得到了例外:

org.hibernate.MappingException: Could not determine type for: es.myproject.entity.User

如果您提供有关各个示例的任何指导或有用的链接,我将不胜感激。最好使用 Hibernate 注释。提前致谢!

【问题讨论】:

    标签: java hibernate jpa orm hibernate-mapping


    【解决方案1】:

    您需要添加注释说明两个实体之间的关系,例如@ManyToOne@OneToOne@OneToMany

    大概是这样的:

    @Entity
    public class User {
        @Id
        private Long id;
    
        @OneToOne(mappedBy="user")
        private Address address;
        // other fields
    }
    

    【讨论】:

      【解决方案2】:

      看看这些tutorials

      【讨论】: