Reputation: 136
I am trying to create new Event objects to be persisted in the database via Hibernate. The below code successfully creates one event, but when session.save(evt) is called, I get a return value of 0 (which I think is the equivalent of null). Can anyone identify what the issue is below? If you need more information in regards to classes or hibernate mapping files involved, please request what you need.
Note: Assume an events table exists in the database.
public class ScheduleUnitOfWork {
private Map<Service, Employee> assignments;
private Date startDate;
private Date endDate;
private String customerName;
public ScheduleUnitOfWork(Map<Service, Employee> assignments, Date startDate,
Date endDate, String customerName) {
super();
this.assignments = assignments;
this.startDate = startDate;
this.endDate = endDate;
this.customerName = customerName;
}
public boolean scheduleEmployees(){
Session session = SessionFactoryUtil.getInstance().getCurrentSession();
Transaction tx = null;
boolean retVal = true;
try {
tx = session.beginTransaction();
for(Service s : assignments.keySet()){
Employee e = assignments.get(s);
Event evt = new Event();
evt.setAssignedService(s);
evt.setCustomerName(this.customerName);
evt.setEndDate(endDate);
evt.setStartDate(startDate);
System.out.println(session.save(evt));
}
tx.commit();
}catch(RuntimeException ex){
ex.printStackTrace();
if(tx != null){
tx.rollback();
}
session.close();
retVal = false;
}
return retVal;
}
}
<class name="Event" table="Events">
<id name="ID" column="ID" type="int">
<generator class="assigned"/>
</id>
<property name="startDate" column="startDate" type="timestamp"/>
<property name="endDate" column="endDate" type="timestamp"/>
<property name="customerName" column="customerName" type="string"/>
<many-to-one name="assignedService" column="serviceID"
class="org.hibernate.service.Service"
unique="true" not-null="true"/>
</class>
Upvotes: 1
Views: 428
Reputation: 100806
Your generator class is "assigned" meaning Hibernate will take the ID "as is" - e.g. it will assume you are setting it.
Take a look at various generator classes supported by Hibernate. If you want your ID to be auto-generated, most common approaches are "identity" (if your database supports it) or "sequence".
Upvotes: 2