I decided to learn hibernate. Everything starts small, so I created the simplest program, but I got this error:
Exception in thread "main" org.hibernate.HibernateException: No CurrentSessionContext configured! at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:498) at ua.com.auvin.Main.main(Main.java:13)
I use hibernate.properties. It is located in: 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
Main program:
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();
}
}
Class:
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 + "]";
}
}
Dependencies in 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>
with the following versions of hibernate, the same error: 5.6.5.Final, 5.6.9.Final