问题
I'm trying to test some POJOs with hibernate annotations and I'm getting the same error on and on. I used the same configuration in another project and it all worked fine. I tested the jdbc connection that is used when the hib objects are tested - and the connction works fine.
I have found a few other questions asked about the same error but nothing was helpful.
The code in testing class with main method:
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();
The POJO with hibernate annotations:
@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;
}
Below there are getters and setters for each entity.
The file hibernate.cfg.xml has the same configuration as the same file in another project where the connection and hibernate code work perfectly fine - as wrote abobe, the connection was tested in a separate class.
The jars I'm using (all added to class path):
- 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
The error that I mentioned in the title mentions a line in my code which is a line in the first code snipet where .buildSessionFactory() occurs.
回答1:
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.
来源:https://stackoverflow.com/questions/50573767/hibernate-5-java-lang-nosuchmethoderror-javax-persistence-table-indexes