简体   繁体   中英

@OneToOne or @ManyToOne on * an unknown entity

I have this error when I try to save a data to a table. I know there are a bunch of questions like mine, but none of them are really describing the problem I have.

I am using Annotations and mark my classes as Entities. Here is the error I have.

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

And two Entities ( getters, setters and consturctors are omitted for more readable code ( they are created by IDEA anyway)

First:

    @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;

And second

@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;

And my main method

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();
   }

I am feeling desperate as I've been trying to solve this problem and none of the Stackoverflow answers helped me. I wonder if the problem can be connected with incorrectly created tables. So I have a screen of mine. I do appreciate your help a lot!

我的桌子

Try to correct your SessionFactory definition in this way:

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

The problem was in Main method. You should always add annotated class. .addAnnotatedClass(Detail.class)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM