我决定学习冬眠。一切都从小开始,所以我创建了最简单的程序,但是我得到了这个错误:
线程"main"异常org.hibernate.HibernateException: No CurrentSessionContext configured!org.hibernate.internal.SessionFactoryImpl.getCurrentSession (SessionFactoryImpl.java: 498)ua.com.auvin.Main.main (Main.java: 13)
我使用hibernate.properties。它位于:src/main/resources:
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost:3306/test?
hibernate.connection.username=root
hibernate.connection.password=
hibernate.show_sql=true
hibernate.dialect=org.hibernate.dialect.MySQLDialect
主程序:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Main {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration().buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Product product = new Product("name", 10, "name2");
System.out.println(product);
session.save(product);
System.out.println(product);
session.getTransaction().commit();
sessionFactory.close();
}
}
类:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.transaction.Transactional;
@Entity
@Table(name = "products")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
@Column(name = "price")
private int price;
@Column(name = "description")
private String description;
public Product() {
}
public Product(String name, int price, String description) {
this.name = name;
this.price = price;
this.description = description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return "Product [id=" + id + ", name=" + name + ", price=" + price + ", description=" + description + "]";
}
}
pom.xml中的依赖项:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.5.6</version>
</dependency>
使用以下版本的hibernate,同样的错误:5.6.5。最后,5.6.9.Final
试试这个:
Session session = sessionFactory.openSession();