Hi, I'm fairly new to Hibernate and I'm trying to solve the following:
Essentially, what I need to do is to map an "Action" object to a "Device" object, where one Action can have many devices and one Device can be in many Actions. You would normally do a simple many-to-many mapping. The problem is, that for every Action-to-Device mapping, I need a property(column) "Status". So the table in the database would look like: ACTION_ID(int), DEVICE_ID(int), STATUS(varchar). To do that I introduced a new object called ActionLink that has a property called "status" and device(instance of Device). My thinking then was that an Action will have a list of ActionLinks.
Code:
public class Action {
private int actionId;
private String name;
private int houseId;
private List<ActionLink> links = new ArrayList<ActionLink>();
//getter and setters
}
<class name="Action" table="actions">
<id name="actionId" column="actionid">
<generator class="increment"></generator>
</id>
<property name="houseId" column="houseid" />
<property name="name" column="Name" />
<bag name="links" table="actionLinks" cascade="all">
<key column="actionid" not-null="true"/>
<many-to-many column="linkid" class="ActionLink"/>
</bag>
</class>
public class ActionLink {
private int linkId;
private Device device;
private String status;
//getters and setters
}
<class name="ActionLink" table="actionLinks">
<id name="linkId" column="linkid">
<generator class="increment"></generator>
</id>
<many-to-one name="device" class="Device" fetch="select">
<column name="deviceId" not-null="true" />
</many-to-one>
<property name="status" column="status" />
</class>
and then:
Device device = dao.getDevice(1);
Device device2 = dao.getDevice(2);
Action action = new Action();
action.setHouseId(1);
action.setName("Wakeup");
ActionLink link = new ActionLink();
link.setStatus("On");
link.setDevice(device);
ActionLink link2 = new ActionLink();
link2.setStatus("Off");
link2.setDevice(device2);
action.getLinks().add(link);
action.getLinks().add(link2);
SessionFactory factory = HibernateConnection.getSessionFactory();
Session session = HibernateConnection.getSessionFactory().openSession();
Transaction transaction = null;
boolean success = false;
try {
transaction = session.beginTransaction();
session.save(action);
session.save(link);
session.save(link2);
transaction.commit();
Now, when I run the code, Hibernate does the following:
Hibernate: insert into actions (houseid, Name, actionid) values (?, ?, ?)
Hibernate: insert into actionLinks (deviceId, status, linkid) values (?, ?, ?)
org.hibernate.exception.GenericJDBCException: Field 'actionid' doesn't have a default value
So it doesn't insert the actionId into the actionLinks table(even though it created that column in the database). Couple anyone please tell me that what I'm trying to do is doable this way and what I'm doing wrong here?
Thank you