Hi
I have a basic doubt
For student and address table, following code would insert rows in both the tables
MANY TO ONE MAPPING IN XML
Code:
<class name="com.mypackage.student.Student" table="STUDENT">
<meta attribute="class-description">This class contains student details.</meta>
<id name="studentId" type="long" column="STUDENT_ID">
<generator class="native" />
</id>
<property name="studentName" type="string" not-null="true" length="100" column="STUDENT_NAME" />
<many-to-one name="studentAddress" class="com.mypackage.student.Address" column="STUDENT_ADDRESS" not-null="true" cascade="all" unique="true" />
</class>
Code:
public class Main {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try
{
transaction = session.beginTransaction();
Address address1 = new Address("OMR Road", "Chennai", "TN", "600097");
Address address2 = new Address("Ring Road", "Banglore", "Karnataka", "560000");
Student student1 = new Student("Eswar2", address1);
Student student2 = new Student("Joe2", address2);
//Test Object
Student student3 = new Student("Joe", address2);
session.save(student1);
session.save(student2);
transaction.commit(); // If this line is commented and program is ran 2 times and then uncommented, the ID is still getting incremented
} catch (HibernateException e)
{
transaction.rollback();
e.printStackTrace();
} finally
{
Integer count = ( (Integer) session.createQuery("select count(*) from Address").iterate().next() ).intValue();
System.out.println(count);
session.close();
}
//Integer count = (Integer) session.createCriteria("select count(*) from Address").uniqueResult();
}
}
Can someone tell me if I comment the transaction.commit and run the program twice then the insert happens from the last session ID
For eg, if Max for student id and address id is 2, 2 respectively and I run the above program twice with transaction.commit and then run it again un-commenting that line, then value = 5,5 is inserted and not 3,3
So in the database the ID is
1,2,5 ( with 3 and 4 missing)
Is it expected behavior? can someone explain why its happening this way and how to avoid it?