Hi Team
I am unable to achieve a one to many association with map data is getting Saved only to one table with my current implementation
I am trying to get a one to many relation between classes Group and Story , please correct
PFB my implementation
/* Group Class Implementatio*/
public class Group {
private int id;
private
String name;
private Map stories;
public Group(){
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map getStories() {
return stories;
}
public void setStories(Map stories) {
this.stories = stories;
}
}
/* Story Class Implementatio*/
public class Story {
private int id;
private String info;
private Group parent;
public Story(){
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public Group getParent() {
return parent;
}
public void setParent(Group parent) {
this.parent = parent;
}
}
/* hbm for Group*/
<hibernate-mapping package="com.Sampl.One.To.Many.Map" auto-import="false" >
<class name="Group" table="group_table">
<id name="id" unsaved-value="0">
<generator class="increment"/>
</id>
<map name="stories" inverse="true" table="story">
<key column="parent_id" not-null="true"/>
<map-key formula="info" type="string" />
<one-to-many class="Story"/>
</map>
<property name="name" type="string"/>
</class>
</hibernate-mapping>
/* hbm for Story*/
<hibernate-mapping package="com.Sampl.One.To.Many.Map" auto-import="false">
<class name="Story" table="story">
<id name="id" unsaved-value="0">
<generator class="increment"/>
</id>
<property name="info"/>
<many-to-one name="parent" column="parent_id" not-null="true"/>
</class>
</hibernate-mapping>
/*Table Schemas*/
CREATE TABLE `group_table` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(200) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `story` (
`id` int(11) NOT NULL auto_increment,
`info` varchar(200) NOT NULL,
`parent_id` int(11) NOT NULL,
`idx` int(11) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*Data Insertion Code*/
public class oneToManyBasedOnMap {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
Group sp = new Group();
sp.setName("Group 5");
HashMap map = new HashMap();
Story s1 = new Story();
s1.setInfo("Story1");
s1.setParent(sp);
Story s2 = new Story();
s2.setInfo("Story2");
s2.setParent(sp);
map.put(s1.getInfo(),s1);
map.put(s2.getInfo(),s2);
sp.setStories(map);
Transaction txn = session.beginTransaction();
session.save(sp);
txn.commit();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}