This example shows you how to store or save Hibernate object to database. The basic steps in creating application in Hibernate will be:
– Creates the POJO
– Create the Hibernate mapping file
– Register the mapping file in the Hibernate configuration
– Create a simple manager class to store the object
The Label.hbm.xml should be registered in the Hibernate configuration file hibernate.cfg.xml
Label.hbm.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?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.javac.example.hibernate.app.Label" table="LABELS"> <id name="id" column="id"> <generator/> </id> <property name="name" not-null="true"/> <property name="modifiedBy" column="modified_by" length="50"/> <property name="modifiedDate" column="modified_date" type="timestamp"/> </class> </hibernate-mapping> |
Label.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
package org.javac.example.hibernate.app; import java.util.Date; public class Label { private Long id; private String name; private String modifiedBy; private Date modifiedDate; public Label() {} private void setId(Long id) { this.id = id; } public Long getId() { return id; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setModifiedBy(String modifiedBy) { this.modifiedBy = modifiedBy; } public String getModifiedBy() { return modifiedBy; } public void setModifiedDate(Date modifiedDate) { this.modifiedDate = modifiedDate; } public Date getModifiedDate() { return modifiedDate; } @Override public String toString() { StringBuilder sb = new StringBuilder("["); sb.append("id = " + id + "; "); sb.append("name = " + name + ";]"); return sb.toString(); } } |
LabelManager.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
package org.javac.example.hibernate.app; import java.util.Date; import org.hibernate.Session; public class LabelManager { private void saveLabel(Label label) { Session session = SessionFactoryHelper.getSessionFactory().getCurrentSession(); session.beginTransaction(); session.save(label); session.getTransaction().commit(); } public static void main(String[] args) { LabelManager manager = new LabelManager(); /* * Creates a Label object we are going to stored in the database. We * set the name, modified by and modified date information. */ Label label = new Label(); label.setName("Sony Music"); label.setModifiedBy("admin"); label.setModifiedDate(new Date()); // Call the LabelManager saveLabel method. manager.saveLabel(label); } } |