Hibernate无法在MySql数据库中创建表

时间:2018-09-22 19:16:14

标签: java mysql hibernate

我正在尝试使用Hibernate将某些内容保存在数据库中。这是我尝试执行的操作:

    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();

这是我的Entity类:

@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;
}
}

这是我的配置文件(资源目录下的hibernate.cfg.xml

<?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>

这是我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在Docker容器中运行。这是docker-compose文件的样子:

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

当我手动创建表并更改hibernate.hbm2ddl.auto属性以进行更新时,它可以工作。

我想自动创建表。我可以连接到数据库,所以这不是Docker的问题。我应该改变什么? 错误沟通看起来像这样:

 Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'hibernate_db.MyEvent' doesn't exist

1 个答案:

答案 0 :(得分:0)

使用spring数据摆脱所有thos配置问题