【问题标题】:Use of @OneToMany or @ManyToMany targeting an unmapped class Exception in hibernate在休眠中使用@OneToMany 或@ManyToMany 针对未映射的类异常
【发布时间】:2016-04-21 15:11:33
【问题描述】:

请原谅我,因为我是休眠的菜鸟,类似问题的其他答案并没有完全解决这个问题(我相信我的问题很基本)。我试图在我的持久性类中有一个 OneToMany 和 ManyToOne 映射。 我有以下表格:

city (
    id INT AUTO_INCREMENT,
    name VARCHAR(255),
)

pincode (
    id INT AUTO_INCREMENT,
    pincode VARCHAR(6),
    city_id INT FOREIGN KEY fk_city_id ON city(id)
)

area (
    id INT AUTO_INCREMENT,
    name VARCHAR(255),
    pincode_id INT FOREIGN KEY fk_pincode_id ON pincode(id)
)

我编写的以下持久性类: 对于城市:

@Table(name="city")
@Entity
City {
    @Id
    private Integer id;

    @Column(name="name")
    private String name;
}

对于密码:

@Table(name="pincode")
@Entity
PinCode {
    @Id
    private Integer id;

    @Column(name = "pincode")
    private String pinCode;

    @ManyToOne
    @JoinColumn(name = "city_id")
    private City city;  //Multiple pincodes may be mapped to one city

    //One pincode may have multiple areas
    @OneToMany(fetch = FetchType.EAGER, mappedBy = "pincode_mapping")
    @Fetch(value = FetchMode.SELECT)
    private List<Area> area;
}

对于地区:

@Entity
Area {
    @Id
    private Integer id;

    @Column(name = "name")
    private String name;

    @ManyToOne(fetch = FetchType.EAGER, targetEntity = PinCode.class)
    @Column(name = "pincode_id")
    private PinCode pinCode;    //Multiple areas may be mapped to one pincode

}

面临以下异常:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with
name 'sessionFactory' defined in class path resource [applicationContext-resources.xml]: Invocation of init method failed; 
nested exception is org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: com.mycompany.model.PinCode.area[com.mycompany.model.Area]

【问题讨论】:

    标签: java hibernate


    【解决方案1】:

    您必须在 Area 实体的多对一注释中定义您的连接列:

    @ManyToOne(fetch = FetchType.EAGER, targetEntity = PinCode.class)
    @JoinColumn(name = "pincode_id", nullable = false)
    

    另外,在您的 Pincode 实体中,您应该在 mappedBy 属性中指明正确的字段:

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "pincode")
    

    【讨论】:

      【解决方案2】:

      我想你的休眠配置中有这样的东西

      <mapping class="com.mycompany.model.PinCode" /> 
      

      或者,如果您使用的是 java 配置

      .addAnnotatedClass(PinCode.class);
      

      确保将所有@Entity 类声明为映射类,或将其配置为自动扫描

      【讨论】:

      • 谢谢。除了注释错误之外,这也丢失了。
      【解决方案3】:

      问题是您使用 mappedBy 错误:您在数据库中添加了列名,但是它必须是 PinCode 映射的 Area 实体中的属性名称:

      @OneToMany(fetch = FetchType.EAGER, mappedBy = "pinCode")
      @Fetch(value = FetchMode.SELECT)
      private List<Area> area;
      

      mappedBy 的 JavaDoc 告诉你同样的:

      拥有关系的字段。除非关系是单向的,否则是必需的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-30
        • 1970-01-01
        • 2020-10-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多