How to use Set in Hibernate Example ?
How to use Set in Hibernate Example ?
Set is a collection which stores only unique values, if you like to store the duplicates then you can go with List.
As we know creating a session factory is the mandatory basic one for any hibernate, creating a hibernate session factory now,
[java]
package in.javadomain;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateConfig {
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if(sessionFactory==null){
try {
// do not forget to add hibernate-jpa-2.1 [which is required jar for
// hibernate 4.3.6+]
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder standardSrvcRgstryBuilder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(standardSrvcRgstryBuilder.build());
} catch (HibernateException e) {
e.printStackTrace();
System.out.println(“Problem while creating a sessionfactory!”);
}
}
return sessionFactory;
}
}
[/java]
I have shared only the session factory creation part above. If you like to learn more about session factory, then visit here.
Table of Contents
Releated Articles for better knowledge:
How to create a session factory ?
Difference between session and session factory ?
Difference between Session.get() and session.load()
How to connect hibernate with mySql in eclipse example ?
Hibernate configuration XML [hibernate.cfg.xml]:
[xml]
<?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>
<!– MySQL JDBC Driver class –>
<property name=”hibernate.connection.driver_class”>com.mysql.jdbc.Driver</property>
<!– Enter database password –>
<property name=”hibernate.connection.password”>DB_PASSWORD</property>
<!– Entry for the mysql –>
<property name=”hibernate.connection.url”>jdbc:mysql://localhost:3306</property>
<!– username of the database –>
<property name=”hibernate.connection.username”>DB_USERNAME</property>
<!– name of the schema or database –>
<property name=”hibernate.default_schema”>SCHEMA_DB_NAME</property>
<!– MySQL dialect –>
<property name=”hibernate.dialect”>org.hibernate.dialect.MySQLDialect</property>
<!– If you make this show_sql value as true then it will print the queries in the console –>
<property name=”hibernate.show_sql”>true</property>
<!– When you add the below entry tables will be created automatically,
but remember it will drop and create each time you run –>
<property name=”hibernate.hbm2ddl.auto”>create</property>
<!– Adding the hibernate mapping file entry –>
<mapping resource=”in/javadomain/Author.hbm.xml” />
</session-factory>
</hibernate-configuration>
[/xml]
hibernate configuration file will be read in the above MainHibernate.java file when you execute new Configuration().configure(). Since we are having the hibernate.cfg.xml in the classpath, new Configuration().configure() will able load all the details from the file directly.
If you are having the file in the different path or different directory or instead of “hibernate.cfg.xml”, if you are keeping the file name as “hibernate_javadomain.cfg.xml” then we need to pass the path and the file name to the configure to create the session factory.
Code Snippet:
[java]
Configuration configuration = new Configuration().configure(“/in/javadomain/hibernate/hibernate_javadomain.cfg.xml”);
[/java]
Author Hibernate Mapping XML file: [Author.hbm.xml]
[xml]
<?xml version=”1.0″?>
<!DOCTYPE hibernate-mapping PUBLIC “-//Hibernate/Hibernate Mapping DTD 3.0//EN”
“http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd”>
<!– Generated Sep 10, 2015 7:17:40 PM by Hibernate Tools 3.4.0.CR1 –>
<hibernate-mapping>
<class name=”in.javadomain.Author” table=”AUTHOR”>
<id name=”authorID” type=”int”>
<column name=”AUTHORID” />
<generator class=”assigned” />
</id>
<property name=”authorName” type=”java.lang.String”>
<column name=”AUTHORNAME” />
</property>
<property name=”siteName” type=”java.lang.String”>
<column name=”SITENAME” />
</property>
<property name=”sitePurpose” type=”java.lang.String”>
<column name=”SITEPURPOSE” />
</property>
<set name=”sitePosts” table=”SITE_POSTS”>
<key column=”ID” />
<composite-element class=”in.javadomain.SitePosts”>
<property name=”postName” column=”POST_NAME” type=”string”></property>
<property name=”postedDate” column=”POSTED_DATE” type=”date”></property>
</composite-element>
</set>
</class>
</hibernate-mapping>
[/xml]
Since we are using set to store set of values below block should be included in the hibernate mapping file.
[xml]
<set name=”sitePosts” table=”SITE_POSTS”>
<key column=”ID” />
<composite-element class=”in.javadomain.SitePosts”>
<property name=”postName” column=”POST_NAME” type=”string”></property>
<property name=”postedDate” column=”POSTED_DATE” type=”date”></property>
</composite-element>
</set>
[/xml]
here, sitePosts is the set name given in the Author.java class, which is also shared below and SITE_POSTS is the table name which will store the multiple entry with the same ID. Composite elements are given to separate the models. Set will contain the SitePosts object, which has the postname and postdate.
Do remember to override the hashcode() and equals() method in the SitePosts.
Why we want to override hashcode() and equals() in set hibernate ?
SitePosts.java:
[java]
package in.javadomain;
import java.util.Date;
public class SitePosts {
public SitePosts(){
}
public SitePosts(String postName, Date postedDate) {
super();
this.postName = postName;
this.postedDate = postedDate;
}
private String postName;
private Date postedDate;
public String getPostName() {
return postName;
}
public void setPostName(String postName) {
this.postName = postName;
}
public Date getPostedDate() {
return postedDate;
}
public void setPostedDate(Date postedDate) {
this.postedDate = postedDate;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((postName == null) ? 0 : postName.hashCode());
result = prime * result + ((postedDate == null) ? 0 : postedDate.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SitePosts other = (SitePosts) obj;
if (postName == null) {
if (other.postName != null)
return false;
} else if (!postName.equals(other.postName))
return false;
if (postedDate == null) {
if (other.postedDate != null)
return false;
} else if (!postedDate.equals(other.postedDate))
return false;
return true;
}
}
[/java]
Author.java
[java]
package in.javadomain;
import java.util.HashSet;
import java.util.Set;
public class Author {
private int authorID;
private String authorName;
private String siteName;
private String sitePurpose;
/* using set to store site posts details */
private Set<SitePosts> sitePosts = new HashSet<SitePosts>();
public Set<SitePosts> getSitePosts() {
return sitePosts;
}
public void setSitePosts(Set<SitePosts> sitePosts) {
this.sitePosts = sitePosts;
}
public int getAuthorID() {
return authorID;
}
public void setAuthorID(int authorID) {
this.authorID = authorID;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
public String getSitePurpose() {
return sitePurpose;
}
public void setSitePurpose(String sitePurpose) {
this.sitePurpose = sitePurpose;
}
public String getSiteName() {
return siteName;
}
public void setSiteName(String siteName) {
this.siteName = siteName;
}
}
[/java]
Thanks for reading how to use set in hibernate.