To map, is to create a xml file which tells Hibernate how our Class is constructed.
First, our User.java class need to be updated to have a 'id' property.
Hibernate needs this to create a primary key for the table.
So, your User.java class should now look like this:
package org.confucius;
public class User {
private long id;
private String firstName;
private String lastName;
public void setId(long id) {
this.id = id;
}
public long getId() {
return id;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
}
In your /classes folder, create a folder 'hibernate-beans'.
In this folder, create a file User.hbm.xml, like this:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.confucius.User">
<id name="id" type="long">
<generator class="identity" />
</id>
<property name="firstName" type="string" />
<property name="lastName" type="string" />
</class>
</hibernate-mapping>
This is the hibernate mapping fir the User class.
It tells Hibernate to use the 'id' field as the primary (id) key.
It specifies the built-in Hibernate generator 'identity' for generating the ids - this means that Hibernate will automatically generate a unique id for each object.
Then it tells Hibernate the properties of User class that we want to persist.
Now we want to tell Hibernate to load this mapping.
Update your hibernate.cfg.xml to make it aware of this mapping file, like this:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/confuciusDB</property>
<property name="hibernate.connection.username">confucius</property>
<property name="hibernate.connection.password">changeit</property&http://www.blogger.com/img/blank.gifgt;
<property name="hibernate.hbm2ddl.auto">create</property>
<mapping resource="hibernate-beans/User.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>
Note the property "hibernate.hbm2ddl.auto" - this is a very useful developer facility. Setting it to 'create' tells Hibernate to automatically create all the necessary database tables. The other options for this property are 'update', 'validate', 'create-drop'.
You can find a brief explanation of these options here.
No comments:
Post a Comment