【问题标题】:Generate Database Tables From Entity Classes using hibernate in Intellij Idea (Not using Spring)在 Intellij Idea 中使用 hibernate 从实体类生成数据库表(不使用 Spring)
【发布时间】:2020-05-12 17:29:37
【问题描述】:

请问,有什么方法可以在 Intellij Idea 中使用 hibernate 从实体类生成数据库表?我在网上看到的只是从数据库模式生成实体类。但是当我修改任何实体类时,我需要相反的方式来轻松更新我的数据库。

这是我的 hibernate.cfg.xml 文件

<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/my_db?useSSL=false</property>


<property name="connection.username">username</property>
<property name="connection.password">password</property>


<property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>

<property name="show_sql">true</property>

<property name="current_session_context_class">thread</property>

<property name="hbm2ddl.auto">create</property>


<property name="connection.pool_size">1</property>
<property name="hibernate.dbcp.initialSize">5</property>
<property name="hibernate.dbcp.maxTotal">20</property>
<property name="hibernate.dbcp.maxIdle">10</property>
<property name="hibernate.dbcp.minIdle">5</property>
<property name="hibernate.dbcp.maxWaitMillis">-1</property>


<!--Declaring entity classes to be mapped to the database-->
<mapping class="com.softpager.estores.entities.Order" />
<mapping class="com.softpager.estores.entities.Customer" />
<mapping class="com.softpager.estores.entities.Users" />
<mapping class="com.softpager.estores.entities.Product" />   

这是我的 persistence.xml 文件

 <persistence-unit name="EStores">
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    <properties>
        <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/my_db?useSSL=false"/>
        <property name="hibernate.connection.driver_class" value="com.mysql.cj.jdbc.Driver"/>
        <property name="hibernate.connection.username" value="username"/>
        <property name="hibernate.connection.password" value="password"/>
        <property name="hibernate.archive.autodetection" value="class"/>
        <property name="hibernate.show_sql" value="true"/>
        <property name="hibernate.format_sql" value="true"/>
        <property name="hibernate.hbm2ddl.auto" value="create"/>

        <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
        <property name="javax.persistence.schema-generation.create-source" value="metadata"/>
        <property name="javax.persistence.schema-generation.drop-source" value="metadata"/>
        <property name="javax.persistence.sql-load-script-source" value="META-INF/load.sql"/>
    </properties>

</persistence-unit>

这是我的 Main.class

public class Main {
public static void main(String[] args) {
    EntityManagerFactory factory = createEntityManagerFactory("EStores");
    EntityManager entityManager = factory.createEntityManager();

}

}

示例实体类

@Data
@Entity
@Table(name = "customer")
public class Customer {

@Id
@GeneratedValue
@Column(name = "customer_id")
private long id;

@Column(name = "first_name", nullable = false)
private String firstName;

@Column(name = "last_name", nullable = false)
private String lastName;

@Embedded
private Contact contact;

@Embedded
private Address address;

@OneToMany(fetch = FetchType.LAZY, mappedBy = "customer")
private Set<Review> reviews;

@OneToMany(fetch = FetchType.LAZY, mappedBy = "customer")
private Set<Product> products;


 public Customer(String firstName, String lastName, Contact contact,              
                                                  Address address) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.contact = contact;
    this.address = address;
    this.products = new HashSet<>();
    this.reviews = new HashSet<>();
}

}

【问题讨论】:

  • 如果您使用 JPA,那么您可以根据需要将应用程序属性中的“spring.jpa.hibernate.ddl-auto”属性设置为“创建”或“更新”。你可以在这里阅读更多关于它的信息docs.spring.io/autorepo/docs/spring-boot/1.1.0.M1/reference/…
  • 是的,这将使用 spring 框架和 Eclipse IDE 轻松工作,但在这种情况下,我没有使用 spring,它是一个普通的 Java hibernate 应用程序,我使用的是 Intellij。
  • 我刚刚更新了我的问题,请看一下。谢谢
  • 您是否正在寻找 intellij idea 中的选项/功能?我不明白,您的 hbm 中有 ddlauto,应该在您启动应用程序时创建/更新表
  • 当然,我实际上希望 Intellij 在我第一次运行应用程序时从实体类创建表,但我注意到它做不到,所以我必须先创建我的数据库表并要求 Intellij从它所做的数据库表中生成实体类。因此,Intellij 仅在应用程序后续运行中检测到实体类列中的任何更改时,才使用我的休眠配置文件来更新我的数据库。感谢您的跟进。

标签: java hibernate jpa intellij-idea


【解决方案1】:

我建议against using hbm2ddl.auto,您可以将Liquibase 添加到您的项目中。它允许您使用更改日志管理所有数据库架构修改,并且您可以独立于应用启动运行表生成/更新。

这确实在您修改模型和正在更新的数据库之间增加了一个额外的步骤,因为您必须将所有更改添加到更改日志中。我建议使用 JPA Buddy 插件,它可以通过将您的 Java 模型与当前数据库进行比较来生成更改日志, here is how it looks

【讨论】:

    【解决方案2】:

    如果我说得对,您想从 Java 类生成数据库表,对吗?如果是这样,这就是 ORM 的主要概念。每当您创建一个新的 POJO 并使用 @Entity 对其进行注释时,您就是在告诉 hibernate 使用该类中的数据创建一个表(如果不存在的话)。在下面找到一个可以做到这一点的示例:

    package com.test.simple_crud_application.models;
    
    import org.hibernate.annotations.CreationTimestamp;
    import org.hibernate.annotations.GenericGenerator;
    import org.hibernate.annotations.UpdateTimestamp;
    
    import javax.persistence.*;
    import java.io.Serializable;
    import java.time.LocalDateTime;
    
    @Entity
    @Table(name = "users")
    public class User implements Serializable
    {
        @CreationTimestamp
        @Column(name = "created_at", updatable = false, nullable = false)
        private LocalDateTime createdAt;
        @UpdateTimestamp
        @Column(name = "updated_at", updatable = true, nullable = false)
        private LocalDateTime modifiedAt;
    
        @Id
        @GeneratedValue(generator="system-uuid")
        @GenericGenerator(name="system-uuid", strategy = "uuid")
        @Column(name = "uid", unique = true, nullable = false)
        private String uid;
    
        @Column(name = "username", nullable = false)
        private String username;
    
        @Column(name = "password", nullable = false)
        private String password;
    }
    

    【讨论】:

    • 当然,我的所有类都已经这样注释了,它在带有 Spring 的 Eclipse 中运行良好。但它在 Intellij 中不起作用。我只能选择从数据库表生成实体类,而不是从实体类生成数据库表。
    • 我刚刚更新了我的问题,请看一下。谢谢
    【解决方案3】:

    使用 JPA Buddy 一个 IntelliJ IDEA 插件,它是免费的。

    JPA 结构 视图中右键单击您的实体,然后单击显示 DDL。

    【讨论】:

      猜你喜欢
      • 2016-08-27
      • 2014-05-10
      • 1970-01-01
      • 1970-01-01
      • 2019-05-16
      • 1970-01-01
      • 2023-02-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多