簡體   English   中英

* 未知實體上的 @OneToOne 或 @ManyToOne

[英]@OneToOne or @ManyToOne on * an unknown entity

當我嘗試將數據保存到表時出現此錯誤。 我知道有很多像我這樣的問題,但沒有一個是真正描述我遇到的問題。

我正在使用注釋並將我的類標記為實體。 這是我遇到的錯誤。

@OneToOne or @ManyToOne on hibernate_test.entity.Employee.detail references an unknown entity.

還有兩個實體(getter、setter 和 consturctors 被省略以獲得更易讀的代碼(它們是由 IDEA 創建的)

第一的:

    @Entity
    @Table(name = "details")
    public class Detail {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "id")
        private int id;
        @Column(name = "city")
        private String city;
        @Column(name = "phone_number")
        private String phoneNumber;
        @Column(name = "email")
        private String email;

第二個

@Entity
@Table(name="employees")
public class Employee {
    
        @Column(name = "id")
         @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private int id;
        @Column(name = "name")
        private String name;
        @Column(name = "surname")
        private String surname;
        @Column(name = "department")
        private String department;
        @Column(name = "salary")
        private int salary;
    
        @OneToOne(cascade = CascadeType.ALL)
        @JoinColumn(name = "details_id")
        private Detail detail;

我的主要方法

SessionFactory sessionFactory = new Configuration() 
      .configure("hibernate.cfg.xml")
      .addAnnotatedClass(Employee.class) 
      .buildSessionFactory();
    
   try {
      Session session = sessionFactory.getCurrentSession();
      Employee employee = new Employee("Mark", "Bulkovsky", "PR", 5324);
            Detail detail = new Detail("Munich", "189432132", "John@gmail.com");
      employee.setDetail(detail);
      session.beginTransaction();
      session.save(employee);
      session.getTransaction().commit();
   } finally {
       sessionFactory.close();
   }

當我一直在嘗試解決這個問題時,我感到絕望,而 Stackoverflow 的答案都沒有幫助我。 我想知道問題是否與錯誤創建的表有關。 所以我有我的屏幕。 我非常感謝您的幫助!

我的桌子

嘗試以這種方式更正您的SessionFactory定義:

SessionFactory sessionFactory = new Configuration() 
   .configure("hibernate.cfg.xml")
   .addAnnotatedClass(Employee.class) 
   .addAnnotatedClass(Detail.class) 
   .buildSessionFactory();

問題出在 Main 方法中。 您應該始終添加帶注釋的 class。 .addAnnotatedClass(Detail.class)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM