休眠:多对一关系失败

Posted

技术标签:

【中文标题】休眠:多对一关系失败【英文标题】:Hibernate: Failed ManyToOne relationship 【发布时间】:2014-02-26 05:59:58 【问题描述】:

我在尝试创建多对一映射时遇到以下错误

Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: org.hibernate.MappingException: Could not determine type for: edu.cs157b.hibernate.Specialty, at table: DOCTOR_INFO, for columns: [org.hibernate.mapping.Column(specialty)]

这是我要映射的两个类

医生

package edu.cs157b.hibernate;

import java.util.ArrayList;

import javax.persistence.*;

@Entity
@Table(name="DOCTOR_INFO")
@NamedQueries (
    
        @NamedQuery(name = "Doctor.getAll", query = "from Doctor"),
        @NamedQuery(name = "Doctor.findByName", query = "from Doctor where name = :name")
    
)
public class Doctor implements Person 

    private int id;
    private String name;
    private int appointment_id;

    @ManyToOne (fetch = FetchType.EAGER) 
     @JoinColumn(name="specialty_id") 
    private Specialty specialty; 

    @Id
    @GeneratedValue
    public int getId() 
        return id;
    

    public void setId(int id) 
        this.id = id;
    

    @Column(unique=true)
    public String getName() 
        return name;
    

    public void setName(String name) 
        this.name = name;
    

    public Specialty getSpecialty() 
        return specialty;
    

    public void setSpecialty(Specialty specialty) 
        this.specialty = specialty;
    

    public int getAppointment_id() 
        return appointment_id;
    

    public void setAppointment_id(int appointment_id) 
        this.appointment_id = appointment_id;
    

专业

package edu.cs157b.hibernate;

import java.util.ArrayList;

import javax.persistence.*;

@Entity
@Table(name="SPECIALTY_INFO")
@NamedQueries (
    
        @NamedQuery(name = "Specialty.getAll", query = "from Specialty"),
        @NamedQuery(name = "Specialty.findByName", query = "from Specialty where name = :name")
    
)
public class Specialty 

    private ArrayList<Doctor> doctors;

    private int id;
    private String name;

    @Id
    @GeneratedValue
    public int getId() 
        return id;
    
    public void setId(int id) 
        this.id = id;
    

    @Column(unique=true)
    public String getName() 
        return name;
    
    public void setName(String name) 
        this.name = name;
    

    public ArrayList<Doctor> getDoctors() 
        return doctors;
    
    public void setDoctors(ArrayList<Doctor> doctors) 
        this.doctors = doctors;
        


【问题讨论】:

【参考方案1】:

Specialty 中的getDoctors() 应使用@OneToMany(mappedBy = "specialty") 注释

【讨论】:

以上是关于休眠:多对一关系失败的主要内容,如果未能解决你的问题,请参考以下文章

mysql外键违反2级多对一关系

flask 定义数据关系(多对一)

MyBatis之多对一关系

没有主键或连接表的休眠多对一关系

Hibernate 多对一关联查询

Hibernate中一对多和多对一关系