gpt4 book ai didi

java - Hibernate:从 Java 代码开始数据库布局

转载 作者:行者123 更新时间:2023-12-01 05:39:49 24 4
gpt4 key购买 nike

假设有以下简单的类:

package Sample;  

public class Status {

private Long id;
private String status;

public Status() {}

public Status(String status) {
this.status = status;
}

public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}

对于这个类,我在 Status.hbm.xml 中定义了 hibernate-mapping。
该文件向 Hibernate 描述了如何将类映射到表。
在 hibernate.cfg 中,我定义了如何连接到我的数据库 (MySQL)。

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.username">root</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>

<mapping resource="sample/Status.hbm.xml"/>
</session-factory>
</hibernate-configuration>

我不明白的是:
使用此配置,当我尝试使用 org.hibernate.Session 将 Status 对象保存到数据库时,它提示没有可连接的数据库。

842 [main] ERROR org.hibernate.util.JDBCExceptionReporter - No database selected

如果我添加现有数据库作为 hibernate.cfg.xml 的 URL 连接字符串的一部分,即

<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/test</property>  

我收到另一个错误,提示表 test.status 不存在。
我期待 Hibernate 会创建它。
仅当我这样做时,代码才会成功:

SchemaExport schemaExport = new SchemaExport(cfg);
schemaExport.create(false, true);

所以我的问题是,使用 Hibernate 并从 Java 开始创建架构、数据库及其表的正确过程是什么。
我不想在 MySQL 中手动创建数据库,例如从 MySQL 客户端。
上述使用 SchemaExport 的方法是否正确?
从 Java DB 设计开始的最佳选择是什么?

最佳答案

让 Hibernate 创建表结构对于测试来说很好,但是一旦应用程序部署到生产环境并实际运行,您将希望 Hibernate 创建表结构每次重新部署时都会删除数据库,因为它会清除您的数据。习惯创建ALTER脚本来管理数据库更改是一个好习惯,因为大多数开发都不是新的,而是更新现有系统。

话虽这么说,是的,您所指出的方式是让 Hibernate 创建数据库模式的正确方式。您还可以在 Hibernate 配置文件中设置这种情况,但我不记得这个属性了。

关于java - Hibernate:从 Java 代码开始数据库布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7449573/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com