简体   繁体   English

org.hibernate.MappingException:无法确定类型:java.util.List,在表:大学,列:[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)]

I'm using Hibernate for all CRUD operations in my project.我正在将 Hibernate 用于我项目中的所有 CRUD 操作。 It doesn't work for One-To-Many and Many-To-One relationships.它不适用于一对多和多对一关系。 It gives me the below error.它给了我以下错误。

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

Then again i went through this video tutorial .然后我又看了这个视频教程 It is very simple to me, in the beginning.一开始对我来说很简单。 But, i cant make it work.但是,我不能让它工作。 It also now, says它现在也说

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

I have ran some searches in the internet, there someone telling its a bug in Hibernate , and some says, by adding @GenereatedValue this error ll be cleared, but it doesn't work for me.我在互联网上进行了一些搜索,有人告诉它 Hibernate 中的一个错误,有人说,通过添加@GenereatedValue这个错误将被清除,但它对我不起作用。

College.java大学.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学生.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:主.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();
  }


}

Console:安慰:

 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)

The XML: 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's 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>

You are using field access strategy (determined by @Id annotation).您正在使用字段访问策略(由 @Id 注释确定)。 Put any JPA related annotation right above each field instead of getter property将任何与 JPA 相关的注释放在每个字段的正上方,而不是 getter 属性

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

Adding the @ElementCollection to the List field solved this issue:@ElementCollection添加到 List 字段解决了这个问题:

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

Problem with Access strategies访问策略的问题

As a JPA provider, Hibernate can introspect both the entity attributes (instance fields) or the accessors (instance properties).作为 JPA 提供者,Hibernate 可以内省实体属性(实例字段)或访问器(实例属性)。 By default, the placement of the @Id annotation gives the default access strategy.默认情况下, @Id注释的位置给出了默认访问策略。 When placed on a field, Hibernate will assume field-based access.当放置在一个字段上时,Hibernate 将承担基于字段的访问。 Placed on the identifier getter, Hibernate will use property-based access.放置在标识符 getter 上,Hibernate 将使用基于属性的访问。

Field-based access基于字段的访问

When using field-based access, adding other entity-level methods is much more flexible because Hibernate won't consider those part of the persistence state使用基于字段的访问时,添加其他实体级方法要灵活得多,因为 Hibernate 不会考虑持久状态的那些部分

@Entity
public class Simple {

@Id
private Integer id;

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

//getter +setter
}

Property-based access基于属性的访问

When using property-based access, Hibernate uses the accessors for both reading and writing the entity state当使用基于属性的访问时,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;
}

}

But you can't use both Field-based and Property-based access at the same time.但是您不能同时使用基于字段和基于属性的访问。 It will show like that error for you它会为你显示类似的错误

For more idea follow this有关更多想法,请遵循

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

I have the same problems, I solved it by add @Access(AccessType.PROPERTY)我有同样的问题,我通过添加@Access(AccessType.PROPERTY)解决了它

Just insert the @ElementCollection annotation over your array list variable, as below:只需在数组列表变量上插入 @ElementCollection 注释,如下所示:

@ElementCollection
private List<Price> prices = new ArrayList<Price>();

I hope this helps我希望这有帮助

Though I am new to hibernate but with little research (trial and error we can say) I found out that it is due to inconsistency in annotating the methods/fileds.虽然我是 hibernate 的新手,但经过很少的研究(我们可以说是反复试验),我发现这是由于注释方法/文件的不一致造成的。

when you are annotating @ID on variable make sure all other annotations are also done on variable only and when you are annotating it on getter method same make sure you are annotating all other getter methods only and not their respective variables.当你在变量上注释@ID 时,确保所有其他注释也只对变量进行,当你在 getter 方法上注释它时,确保你只注释所有其他 getter 方法而不是它们各自的变量。

在我的情况下,@OneToOne 注释的缺失是愚蠢的,我设置了 @MapsId 没有它

Don't worry!别担心! This problem occurs because of the annotation.出现此问题的原因是注释。 Instead of Field based access, Property based access solves this problem.代替基于字段的访问,基于属性的访问解决了这个问题。 The code as follows:代码如下:

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

} }

In case anyone else lands here with the same issue I encountered.万一其他人遇到我遇到的同样问题。 I was getting the same error as above:我遇到了与上面相同的错误:

Invocation of init method failed; init 方法调用失败; nested exception is org.hibernate.MappingException: Could not determine type for: java.util.Collection, at table:嵌套异常是 org.hibernate.MappingException:无法确定类型:java.util.Collection,在表中:

Hibernate uses reflection to determine which columns are in an entity. Hibernate 使用反射来确定实体中的哪些列。 I had a private method that started with 'get' and returned an object that was also a hibernate entity.我有一个以“get”开头的私有方法,并返回一个也是休眠实体的对象。 Even private getters that you want hibernate to ignore have to be annotated with @Transient.即使您希望休眠忽略的私有 getter 也必须使用 @Transient 进行注释。 Once I added the @Transient annotation everything worked.添加 @Transient 注释后,一切正常。

@Transient 
private List<AHibernateEntity> getHibernateEntities() {
   ....
}

Add the schema name to the entity and it will find it.将架构名称添加到实体,它会找到它。 Worked for me!为我工作!

Neither of the listed solutions worked for me and here is why: I am using entity inheritance with property-access strategy.列出的解决方案都不适合我,原因如下:我将实体继承与属性访问策略一起使用。

@Entity(name = "spec")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorFormula(value = "type")
public abstract class Spec extends BasicEntity { ... }

Two inheritors have a property which is not presented in the super class.两个继承者有一个在超类中没有的属性。 One of the inheritor has JoinColumn and OneToOne annotations to consolidate Basic attribute type usage (actually Intellij IDEA highlights the field if it has not appropriate getter with JoinColumn annotation).继承者之一具有JoinColumnOneToOne注释以整合Basic属性类型用法(实际上,Intellij IDEA 会突出显示该字段,如果它没有合适的带有JoinColumn注释的 getter)。

@Data
@Entity
@DiscriminatorValue("data")
public class DataSpec extends Spec {

    private Payload payload;

    @OneToOne
    @NotFound(action = NotFoundAction.IGNORE)
    @JoinColumn(name = "payload_id")
    public Payload getPayload() {
        return payload;
    }

However, the second inheritor doesn't have any annotations for this new property and somehow IDEA doesn't highlight it to warn me about the issue!但是,第二个继承者没有这个新属性的任何注释,而且 IDEA没有突出显示它来警告我这个问题!

@Data
@Entity
@DiscriminatorValue("blob")
public class BlobSpec extends Spec {

    private Payload payload;
  //^^^^^^^^^^^^^^^^^^^^^^^^ No getter with @JoinColumn! Should be highlighted with static code check!

I was only able to triage the issue by debuging hibernate classes.我只能通过调试休眠类来对问题进行分类。 I found out that my entity doesn't pass validation in MetadataImpl.validate method.我发现我的实体在MetadataImpl.validate方法中没有通过验证。 The exception doesn't tell you about it.例外不会告诉你这件事。 It only prints the error occurred in the spec table, which is not a detailed message.它只打印spec表中发生的错误,而不是详细消息。

Just remove只需删除

mappedBy="college" in @OneToMany(targetEntity=Student.class, mappedBy="college", fetch=FetchType.EAGER)的mappedBy = “大学”在@OneToMany(targetEntity = Student.class,的mappedBy = “大学”,取= FetchType.EAGER)

This solve my issue.这解决了我的问题。 ;) ;)

Had the same problem, my issue was that I didn't specify the @Id annotation on the the id field.有同样的问题,我的问题是我没有在 id 字段上指定 @Id 注释。

When I annotated it, everything ran smoothly.当我注释它时,一切都运行得很顺利。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 org.hibernate.MappingException:无法确定类型:java.util.List,在表:user处,用于列:[org.hibernate.mapping.Column(events)] - org.hibernate.MappingException: Could not determine type for: java.util.List, at table: user, for columns: [org.hibernate.mapping.Column(events)] org.hibernate.MappingException:无法确定类型:java.util.Set,在表:Company中,用于列:[org.hibernate.mapping.Column(users)] - org.hibernate.MappingException: Could not determine type for: java.util.Set, at table: Company, for columns: [org.hibernate.mapping.Column(users)] org.hibernate.MappingException:无法确定类型:java.util.Collection,用于列:[org.hibernate.mapping.Column(lisOfAddresses)] - org.hibernate.MappingException: Could not determine type for: java.util.Collection, for columns: [org.hibernate.mapping.Column(lisOfAddresses)] org.hibernate.MappingException:无法确定以下类型:表:对于列:[org.hibernate.mapping.Column(plant) - org.hibernate.MappingException: Could not determine type for: at table: for columns: [org.hibernate.mapping.Column(plant) org.hibernate.MappingException:无法确定类型:在表中:列:[org.hibernate.mapping.Column(卖家)] - org.hibernate.MappingException: Could not determine type for: at table: for columns: [org.hibernate.mapping.Column(seller)] 无法确定类型:java.util.List,在表:file_post,列:[org.hibernate.mapping.Column(file)] - Could not determine type for: java.util.List, at table: file_post, for columns: [org.hibernate.mapping.Column(file)] 引起:org.hibernate.MappingException:无法确定类型:时间戳,列:[org.hibernate.mapping.Column(***)] - Caused by: org.hibernate.MappingException: Could not determine type for: Timestamp, for columns: [org.hibernate.mapping.Column(***)] org.hibernate.MappingException:无法确定类型:java.util.List,在表:Schedule_assignedRoles,对于列:AssignedRoles - org.hibernate.MappingException: Could not determine type for: java.util.List, at table: Schedule_assignedRoles, for columns: assignedRoles 使用@ElementCollection时出错:org.hibernate.MappingException:无法确定类型:java.util.Set,在表:对于列 - Error while using @ElementCollection: org.hibernate.MappingException: Could not determine type for: java.util.Set, at table: for columns 无法确定以下表的类型:org.json.JSONObject,在表:ordersinfo中,用于列:[org.hibernate.mapping.Column(items)] - Could not determine type for: org.json.JSONObject, at table: ordersinfo, for columns: [org.hibernate.mapping.Column(items)]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM