Reputation: 3490
I'm new to java and working on a java spring project. Now I've to make sure my data is being stored in database, I'm inserting some values manually to test this part.
The code looks like this:
Department departmentDetails = new Department();
departmentDetails.setDepartmentName( "cse" );
departmentDetails.setStatus( 1 );
departmentDetails.setModifiedBy( "mehul" );
departmentDetails.setCreatedBy( "mehul" );
departmentDetails.setCreatedOn( new Timestamp( System.currentTimeMillis() ) );
departmentDetails.setModifiedOn( new Timestamp( System.currentTimeMillis() ) );
departmentDetailsRepository.save( departmentDetails );
departmentDetails.setDepartmentName( "ECe" );
departmentDetails.setStatus( 1 );
departmentDetails.setModifiedBy( "xyz" );
departmentDetails.setCreatedBy( "xyz" );
departmentDetails.setCreatedOn( new Timestamp( System.currentTimeMillis() ) );
departmentDetails.setModifiedOn( new Timestamp( System.currentTimeMillis() ) );
departmentDetails = departmentDetailsRepository.save( departmentDetails );
Instead of creating new object, I'm using it again after saving its details (by calling departmentDetailsRepository.save( departmentDetails );
) in the database.
But when i execute this, only the second details, i.e department ECE created by
xyz is saved, but not the first record.
I am using spring data's jpa repository as follows:
public interface DepartmentRepository extends JpaRepository<Department, Long> {}
What have I done wrong here?
Upvotes: 0
Views: 217
Reputation: 662
That's because Hibernate actually trigerring save operation not after calling save
method, it persist your data during commit of transaction. Also if you using the same object it will just update it, you even don't need to call save
second time. To create 2 records in db you should create new object because your current object is in persistent state.
Upvotes: 0
Reputation: 32507
You need to create new instance in order to create "new" row.
Upvotes: 1
Reputation: 12542
You are using it the wrong way.
Try this
Department departmentDetails = new Department();
...
departmentDetailsRepository.save(departmentDetails);
departmentDetails = new Department(); //Create a new object.
...
departmentDetails = departmentDetailsRepository.save(departmentDetails);
Upvotes: 0