Hibernate: Start from Java code the DB layout
Assume the following trivial class:
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;
}
}
For this class I have defined the hibernate-mapping in the Status.hbm.xml
.
hibernate.cfg
I have defined how to connect to my Database (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>
What I do not undertand is the following:
With this configuration when I try to use theorg.hibernate.Session
to save an object of Status
to the database, it complaints that there is no database to connect.
842 [main] ERROR org.hibernate.util.JDBCExceptionReporter - No database select开发者_开发技巧ed
If I add an existing database as part of the URL connection string of hibernate.cfg.xml
i.e.
<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/test</property>
I get a different error complaining that the table test.status
does not exist.
SchemaExport schemaExport = new SchemaExport(cfg);
schemaExport.create(false, true);
So my question is, what is the proper process to use Hibernate and create a schema and a database and its tables starting from Java.
I do not want to manually create a database in MySQL for example from an MySQL client. Is the above approach with theSchemaExport
the correct way?
What is the best option for the start from Java DB design?Having Hibernate create the table structure is fine for testing, but once the application has been deployed to production and is actually running, you will NOT want hibernate to create the database every time you re-deploy because it will wipe out your data. Getting used to creating ALTER
scripts for managing database changes is a good habit to get into, since most development is not new but is updating an existing system.
That being said, yes, the way you have indicated is the correct way to have Hibernate create the database schema. You can also set that to happen in the Hibernate config file, but I don't remember the property off the top of my head.
精彩评论