我正在尝试使用 hibernate 注解测试一些 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();
带有 hibernate 注释的 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 与另一个项目中的相同文件具有相同的配置,其中连接和 hibernate 代码工作得非常好 - 正如 abobe 所写,连接是在一个单独的类中测试的。
我正在使用的 jar (全部添加到类路径):
- antlr-2.7.7.jar byte-buddy-1.8.0.jar
- classmate-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() 的一行。
最佳答案
您的类路径中有冲突的 jar:
hibernate-jpa-2.0-api-1.0.0.Final.jar
javax.persistence-api-2.2.jar
javax.persistence.Table.indexes是 JPA 2.1 中添加的功能。
因此,您应该丢弃 hibernate-jpa-2.0-api-1.0.0.Final.jar jar,因为它只描述了 JPA 2.0 API。
当您有多个版本的相同类可供应用程序使用时,很难预测哪个版本将首先加载,这就是它有时似乎可以工作的原因。但这基本上是一种彩票,所以你永远不应该在实践中这样做。
关于java - hibernate 5 - java.lang.NoSuchMethodError : javax. persistence.Table.indexes(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50573767/