Yogesh Ghimire
Yogesh Ghimire

Reputation: 442

Create an database entity in one thread and try to retrieve the same entity in another thread gives different result

I am trying to create a scenario where I create an entity in main thread and then use another thread to query the same entity that was just created. However, if I execute the query to fetch the entity outside of the thread, it returns value. However, if I query it inside the thread, I get null. I have attached the source code with comments and tried to make it simple. I would appreciate if anyone can help me point out the issue. I am using JPA and Spring framework. For database, I am using postgresql. Thank you. Here is the sample program:

    @Test
    public void test() {
        Employee generatedEmployee = employeeService.createEmployee(passEmployeeInfo()); // CREATE TEST EMPLOYEE.. passEmployeeInfo() just sets name, phone etc.
        System.out.println(generatedEmployee.getReferenceId()); //Output is: 20

        generatedEmployee.setReferenceId(30L); //update the referenceId here...
        long refId = generatedEmployee.getReferenceId();

        Employee employeeFromDB = employeeQuery.getEmployeeByReferenceId(refId); //Use refId to get Employee from table
        System.out.println(employeeFromDB);  //Output is:  Employee [id=2, refId=30, ...]

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                Employee employee = employeeQuery.getEmployeeByReferenceId(refId);
                System.out.println("The employee inside run method is: " + employee); //Output is NULL here.. This is what I am trying to understand.
            }
        });
        thread.start();
}

Upvotes: 1

Views: 201

Answers (1)

Alan Hay
Alan Hay

Reputation: 23226

Points to Note:

  • Spring will apply a transaction to your test method and will by default roll the transaction back when the method completes.

https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#rollback

  • Spring transactions do not propagate to new threads.

https://dzone.com/articles/spring-and-threads-transactions

So therefore the method completes and rolls back the transaction before the lookup in the new Thread executes.

If you add the @Commit annotation to your test method the record should be found.

Upvotes: 1

Related Questions