I have UserObject which contains a list of SearchLog objects. This search log list size is defined to be at max 5.
Now whenever I add a search log to the UserObject in SearchLog list I want it to be added in the first position. The SearchLog object has a sequence number which I want to be automatically generated by hibernate. So if the searchLog list contains 3 elements on adding 4th searchLog in first position, the sequence number of previously persistent objects should automatically change.
While trying to save the UserObject with a new SearchLog object in the searchLog list, I get the exception that the sequence number of Search log should be specified (its not null field in DB). If I set the sequence number explicitly it works fine, but what I want is that hibernate should automatically handle this.Can this be done? Or is setting sequence number manually the only way.
Here's what I have been trying-
public class UserObject {
private Integer id;
private String firstName;
private List<SearchLog> searchLogs = new ArrayList<SearchLog>();
}
public class SearchLog {
private Integer id;
private String searchQuery;
private Integer sequenceNumber;
private Integer userObjectId;
}
And the corresponding hbm files-
UserObject.hbm.xml
<hibernate-mapping package="com.xxx.admin.bo">
<class name="UserObject " table="USER" dynamic-update="true" dynamic-insert="true" discriminator-value="AT">
<id name="id" type="java.lang.Integer" column="ID" >
<generator class="identity"/>
</id>
<property name="firstName" type="java.lang.String" column="FIRST_NAME" length="30"/>
<list name="searchLogs" table="SEARCH_LOG" cascade="all-delete-orphan" lazy="true" inverse="true" >
<key column="USER_OBJECT_ID" />
<index column="SEQUENCE_NUMBER" />
<one-to-many class="SearchLog" />
</list>
</class>
</hibernate-mapping>
SearchLog.hbm.xml
<hibernate-mapping package="com.xxx.admin.bo">
<class name="SearchLog" table="SEARCH_LOG" dynamic-update="true" dynamic-insert="true" discriminator-value="AT">
<id name="id" type="java.lang.Integer" column="ID">
<generator class="identity"/>
</id>
<property name="searchQuery" type="java.lang.String" column="SEARCH_QUERY" length="250"/>
<property name="sequenceNumber" type="java.lang.Integer" column="SEQUENCE_NUMBER" not-null="true" />
<property name="userObjectId" type="java.lang.Integer" column="USER_OBJECT_ID"/>
</class>
</hibernate-mapping>
Code block of save method
userObject.getSearchLogs().add(0, searchLog);
getUserDao().save(userObject);