I'm trying to save something in database using Hibernate. Here is how I'm trying do this:
MyEvent event = new MyEvent();
event.setEventName("Sample event!!!");
Configuration configuration = new Configuration().configure();
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.save(event);
session.flush();
transaction.commit();
session.close();
sessionFactory.close();
Here is my Entity class:
@Entity
public class MyEvent {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String eventName;
public MyEvent() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
}
And here is my config file (hibernate.cfg.xml under the resources directory
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:8877/hibernate_db</property>
<property name="hibernate.connection.username">hiber</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="hibernate.show_sql">true</property>
<mapping class="com.smola.MyEvent"/>
</session-factory>
</hibernate-configuration>
Here are dependencies from my pom.xml:
<dependencies>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.14.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.6.Final</version>
</dependency>
</dependencies>
Mysql is running in the Docker container. Here is how the docker-compose file looks like:
version: "3"
services:
db:
image: mysql:5.7
restart: always
environment:
- MYSQL_ROOT_PASSWORD=root
- MYSQL_DATABASE=hibernate_db
- MYSQL_USER=hiber
- MYSQL_PASSWORD=root
ports:
- 8877:3306
When I've created the table manually and change the hibernate.hbm2ddl.auto property to update, it works.
I want to create tables automatically. I can connect to the database, so it isn't the problem with the Docker. What should I change? The error communicate looks like this:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'hibernate_db.MyEvent' doesn't exist