首页 > 解决方案 > 休眠 5 - java.lang.NoSuchMethodError: javax.persistence.Table.indexes()

问题描述

我正在尝试使用休眠注释测试一些 POJO,并且我不断地遇到相同的错误。我在另一个项目中使用了相同的配置,一切正常。我测试了测试 hib 对象时使用的 jdbc 连接 - 并且连接工作正常。

我发现了一些其他关于相同错误的问题,但没有任何帮助。

使用 main 方法测试类中的代码:

public static void main(String[] args) {

    SessionFactory factory = new Configuration()
            .configure("hibernate.cfg.xml")
            .addAnnotatedClass(Item.class)
            .buildSessionFactory();

    //create session
    Session session = factory.getCurrentSession();

    try {

        session.beginTransaction();

        List<Item> items = session.createQuery("from items").list();

带有休眠注释的 POJO:

@Entity
@Table(name="items")
public class Item {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private int id;

    @Column(name="name")
    private String name;

    @Column(name="price")
    private double price;

    @Column(name="stock")
    private int stock;

    public Item() {
    }

    public Item(String name, double price) {
    this.name = name;
    this.price = price;
    }

下面是每个实体的 getter 和 setter。

文件 hibernate.cfg.xml 与另一个项目中的相同文件具有相同的配置,其中连接和休眠代码工作得非常好——正如上面所写,连接是在一个单独的类中测试的。

我正在使用的罐子(全部添加到类路径):

我在标题中提到的错误提到了我的代码中的一行,这是第一个代码片段中发生 .buildSessionFactory() 的一行。

标签: javahibernatejakarta-eejpa-2.2

解决方案


You have conflicting jars in your class path:

  • hibernate-jpa-2.0-api-1.0.0.Final.jar

  • javax.persistence-api-2.2.jar

javax.persistence.Table.indexes is a feature that was added in JPA 2.1.

Therefore you should discard the hibernate-jpa-2.0-api-1.0.0.Final.jar jar because it only describes the JPA 2.0 API.

When you have multiple versions of the same classes available to an application it is difficult to predict which version will be loaded first, which is why it will sometimes appear to work. But it's basically a lottery so you should never do this in practice.


推荐阅读