Arun Gowda
Arun Gowda

Reputation: 3490

Why can't I use same instance to save details in database using JPA repository?

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

Answers (3)

Vitalii Muzalevskyi
Vitalii Muzalevskyi

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

Antoniossss
Antoniossss

Reputation: 32507

You need to create new instance in order to create "new" row.

Upvotes: 1

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

Related Questions