Writing Hibernate Configuration Files

In the previous section we completed the database setup and created required table and populated with the data. In this section we will write required hibernate configuration files.

For this tutorial we need following Hibernate configuration files:

Hibernate Configuration File

Hibernate configuration file (hibernate.cfg.xml) is used to provide the information which is necessary for making database connections. The mapping details for mapping the domain objects to the database tables are also a part of Hibernate configuration file.

Here is the code of our Hibernate Configuration File:


"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">



com.mysql.jdbc.Driver
jdbc:mysql://localhost/struts-hibernate
root

10
true
org.hibernate.dialect.MySQLDialect
update




Place hibernate.cfg.xml file in the source directory e.g. "C:\Struts-Hibernate-Integration\code\src\java"

The tag is used to specify the mapping file:


Code of Tutorial.hbm.xml:


"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">



name="roseindia.net.dao.hibernate.Tutorial"
table="tutorials"
>

name="id"
type="java.lang.Integer"
column="id"
>



name="shortdesc"
type="java.lang.String"
column="shortdesc"
not-null="true"
length="50"
/>
name="longdesc"
type="java.lang.String"
column="longdesc"
not-null="true"
length="250"
/>
name="pageurl"
type="java.lang.String"
column="pageurl"
not-null="true"
length="100"
/>



Place Tutorial.hbm.xml file in the source directory e.g. "C:\Struts-Hibernate-Integration\code\src\java\roseindia\net\dao\hibernate\"

POJO Object


Here is the code of Java Bean object (Tutorial.java) used to store and retrieve the data from database.
package roseindia.net.dao.hibernate;

import java.io.Serializable;


public class Tutorial implements Serializable {

/** identifier field */
private Integer id;

/** persistent field */
private String shortdesc;

/** persistent field */
private String longdesc;

/** persistent field */
private String pageurl;

/** full constructor */
public Tutorial(Integer id, String shortdesc, String longdesc, String pageurl) {
this.id = id;
this.shortdesc = shortdesc;
this.longdesc = longdesc;
this.pageurl = pageurl;
}

/** default constructor */
public Tutorial() {
}

public Integer getId() {
return this.id;
}

public void setId(Integer id) {
this.id = id;
}

public String getShortdesc() {
return this.shortdesc;
}

public void setShortdesc(String shortdesc) {
this.shortdesc = shortdesc;
}

public String getLongdesc() {
return this.longdesc;
}

public void setLongdesc(String longdesc) {
this.longdesc = longdesc;
}

public String getPageurl() {
return this.pageurl;
}

public void setPageurl(String pageurl) {
this.pageurl = pageurl;
}

}

In this section we have created all the Hibernate related stuffs.

0 comments:

Post a Comment