3

我正在尝试使用休眠注释测试一些 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 与另一个项目中的相同文件具有相同的配置,其中连接和休眠代码工作得非常好——正如上面所写,连接是在一个单独的类中测试的。

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

  • antlr-2.7.7.jar byte-buddy-1.8.0.jar
  • 同学-1.3.0.jar
  • dom4j-1.6.1.jar
  • hibernate-commons-annotations-5.0.3.Final.jar
  • hibernate-core-5.3.0.Final.jar
  • hibernate-jpa-2.0-api-1.0.0.Final.jar
  • jandex-2.0.3.Final.jar
  • javassist-3.22.0-GA.jar
  • javax.persistence-api-2.2.jar
  • jboss-logging-3.3.2.Final.jar
  • jboss-transaction-api_1.2_spec-1.0.1.Final.jar
  • mysql-connector-java-8.0.11.jar

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

4

2 回答 2

7

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.

于 2018-05-31T06:34:41.670 回答
0

我有这个错误是因为我们使用了树脂服务器并升级了休眠

树脂具有 JPA 2.0

并且 Web 应用程序具有 hibernate-jpa-2.1-api-1.0.2.Final.jar

Steve C如答案中所述,这就是造成冲突罐子的原因

要解决这种情况,您需要按照https://www.caucho.com/resin-4.0/admin/database.xtp#Hibernate中的说明进行操作

在树脂配置文件中将新的 api lib 添加到树脂类路径中,如下所示

<server-default>
    <jvm-classpath>path/to/lib/hibernate-jpa-2.1-api-1.0.2.Final.jar</jvm-classpath>
    ...
<server-default>
于 2021-08-15T10:06:19.960 回答