Подтвердить что ты не робот

Org.hibernate.MappingException: Не удалось определить тип для: java.util.List, at table: College, для столбцов: [org.hibernate.mapping.Column(students)]

Я использую Hibernate для всех операций CRUD в моем проекте. Это не работает для отношений один-ко-многим и многие-к-одному. Это дает мне ошибку ниже.

org.hibernate.MappingException: Could not determine type for: java.util.List, at table: College, for columns: [org.hibernate.mapping.Column(students)]

Затем я снова прошел этот видеоурок. Это очень просто для меня, в начале. Но я не могу заставить это работать. Это также сейчас, говорит

org.hibernate.MappingException: Could not determine type for: java.util.List, at table: College, for columns: [org.hibernate.mapping.Column(students)]

Я провел несколько поисков в Интернете, где кто-то говорит об ошибке в Hibernate, а некоторые говорят, что добавив @GenereatedValue, эта ошибка будет очищена, но она не работает для меня.

College.java

@Entity
public class College {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int collegeId;
private String collegeName;


private List<Student> students;

@OneToMany(targetEntity=Student.class, mappedBy="college", fetch=FetchType.EAGER)
public List<Student> getStudents() {
    return students;
}
public void setStudents(List<Student> students) {
    this.students = students;
}//Other gettters & setters omitted

Student.java

@Entity
public class Student {


@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int studentId;
private String studentName;


private College college;

@ManyToOne
@JoinColumn(name="collegeId")
public College getCollege() {
    return college;
}
public void setCollege(College college) {
    this.college = college;
}//Other gettters & setters omitted

Main.java:

public class Main {

private static org.hibernate.SessionFactory sessionFactory;

  public static SessionFactory getSessionFactory() {
    if (sessionFactory == null) {
      initSessionFactory();
    }
    return sessionFactory;
  }

  private static synchronized void initSessionFactory() {
    sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();

  }

  public static Session getSession() {
    return getSessionFactory().openSession();
  }

  public static void main (String[] args) {
                Session session = getSession();
        Transaction transaction = session.beginTransaction();
        College college = new College();
        college.setCollegeName("Dr.MCET");

        Student student1 = new Student();
        student1.setStudentName("Peter");

        Student student2 = new Student();
        student2.setStudentName("John");

        student1.setCollege(college);
        student2.setCollege(college);



        session.save(student1);
        session.save(student2);
        transaction.commit();
  }


}

Приставка:

 Exception in thread "main" org.hibernate.MappingException: Could not determine type  for: java.util.List, at table: College, for columns:  [org.hibernate.mapping.Column(students)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:306)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:290)
at org.hibernate.mapping.Property.isValid(Property.java:217)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:463)
at org.hibernate.mapping.RootClass.validate(RootClass.java:235)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1330)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1833)
at test.hibernate.Main.initSessionFactory(Main.java:22)
at test.hibernate.Main.getSessionFactory(Main.java:16)
at test.hibernate.Main.getSession(Main.java:27)
at test.hibernate.Main.main(Main.java:43)

XML:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
    <!-- Database connection settings -->
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/dummy</property>
    <property name="connection.username">root</property>
    <property name="connection.password">1234</property>
    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>
    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <!-- Enable Hibernate automatic session context management -->
    <property name="current_session_context_class">thread</property>
    <!-- Disable the second-level cache -->
    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>
    <!-- Drop and re-create the database schema on startup -->
    <property name="hbm2ddl.auto">update</property>

    <mapping class="test.hibernate.Student" />
    <mapping class="test.hibernate.College" />
</session-factory>

4b9b3361

Ответ 1

Вы используете стратегию доступа к (определяется аннотацией @Id). Поместите любую аннотацию, связанную с JPA, прямо над каждым полем вместо свойства getter

@OneToMany(targetEntity=Student.class, mappedBy="college", fetch=FetchType.EAGER)
private List<Student> students;

Ответ 2

Добавление поля @ElementCollection в список позволило решить эту проблему:

    @Column
    @ElementCollection(targetClass=Integer.class)
    private List<Integer> countries;

Ответ 3

Проблема со стратегиями доступа

Как поставщик JPA, Hibernate может анализировать как атрибуты объекта (поля экземпляра), так и методы доступа (свойства экземпляра). По умолчанию размещение аннотации @Id дает стратегию доступа по умолчанию. При размещении в поле Hibernate будет использовать полевой доступ. Помещенный в метод получения идентификатора, Hibernate будет использовать доступ на основе свойств.

Полевой доступ

При использовании доступа на основе полей добавление других методов уровня объекта является гораздо более гибким, поскольку Hibernate не учитывает эти части состояния постоянства.

@Entity
public class Simple {

@Id
private Integer id;

@OneToMany(targetEntity=Student.class, mappedBy="college", 
fetch=FetchType.EAGER)
private List<Student> students;

//getter +setter
}

Недвижимость на основе доступа

При использовании доступа на основе свойств Hibernate использует средства доступа для чтения и записи состояния объекта.

@Entity
public class Simple {

private Integer id;
private List<Student> students;

@Id
public Integer getId() {
    return id;
}

public void setId( Integer id ) {
    this.id = id;
}
@OneToMany(targetEntity=Student.class, mappedBy="college", 
fetch=FetchType.EAGER)
public List<Student> getStudents() {
   return students;
}
public void setStudents(List<Student> students) {
    this.students = students;
}

}

Но вы не можете использовать доступ как на основе полей, так и на основе свойств одновременно. Это покажет вам эту ошибку

Для большей идеи следуйте этому

Ответ 4

@Access(AccessType.PROPERTY)
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name="userId")
public User getUser() {
    return user;
}

У меня те же проблемы, я решил это, добавив @Access(AccessType.PROPERTY)

Ответ 5

Не волнуйся! Эта проблема возникает из-за аннотации. Вместо доступа на основе полей доступ на основе свойств решает эту проблему. Код следующим образом:

package onetomanymapping;

import java.util.List;

import javax.persistence.*;

@Entity
public class College {
private int collegeId;
private String collegeName;
private List<Student> students;

@OneToMany(targetEntity = Student.class, mappedBy = "college", 
    cascade = CascadeType.ALL, fetch = FetchType.EAGER)
public List<Student> getStudents() {
    return students;
}

public void setStudents(List<Student> students) {
    this.students = students;
}

@Id
@GeneratedValue
public int getCollegeId() {
    return collegeId;
}

public void setCollegeId(int collegeId) {
    this.collegeId = collegeId;
}

public String getCollegeName() {
    return collegeName;
}

public void setCollegeName(String collegeName) {
    this.collegeName = collegeName;
}

}

Ответ 6

Хотя я новичок в спящем режиме, но с небольшими исследованиями (методом проб и ошибок мы можем сказать) я обнаружил, что это связано с непоследовательностью в аннотировании методов/полей.

когда вы аннотируете @ID для переменной, убедитесь, что все другие аннотации также выполняются только для переменной, и когда вы аннотируете это для метода get, убедитесь, что вы аннотируете только все другие методы getter, а не их соответствующие переменные.

Ответ 7

проблема в том, что вы объявили аннотацию после объявления переменной. Убедитесь, что вы объявили аннотацию до объявления переменной