Scrivio Interview library
CodingIntermediate7 min read · updated 12 November 2026

Call a database function from Spring Data JPA in two ways: with @Procedure on a repository method, and with a native query. Then explain how you would test this code, and what can go wrong with transaction boundaries.

We can declare @Procedure(procedureName = "open_total") BigDecimal openTotal(Long customerId) on a Spring Data JPA repository, which calls it through JPA's StoredProcedureQuery, or write @Query(value = "select open_total(:id)", nativeQuery = true); for full control over IN, OUT and REF_CURSOR parameters, we use StoredProcedureQuery directly. We test against the real database engine with Testcontainers and the real migrations, since H2 cannot run PL/pgSQL, and we watch transactions: a procedure that commits cannot run inside a Spring transaction, and rows it changes are not seen by entities already in the persistence context, so we flush before the call and clear after.

Why this question is asked

Spring Data JPA makes calling database code look like any other repository method, which is convenient and also hides two things that bite in production: how the call is executed, and how it interacts with the transaction and Hibernate's first-level cache. Interviewers ask this to see whether we can write both styles, test them properly, and reason about transaction boundaries. In this answer, we will write the @Procedure and native query versions, look at StoredProcedureQuery for harder cases, set up a Testcontainers test, and then work through what can go wrong with transactions and the persistence context.

1The Database Function

We call the open_total function from an earlier example: it returns the sum of a customer's open invoices as numeric. Functions return a value inside SQL; procedures are called with CALL and may return OUT parameters. Spring Data supports both, but the details differ, which is worth keeping in mind as we go.

SQL
CREATE FUNCTION open_total(p_customer bigint) RETURNS numeric
LANGUAGE sql STABLE AS $$
SELECT coalesce(sum(amount), 0) FROM invoice
WHERE customer_id = p_customer AND status = 'OPEN'
$$;
SELECT open_total(42); -- 150.50

2Way 1: @Procedure on a Repository Method

@Procedure tells Spring Data that a repository method calls stored database code. With procedureName, the method parameters are passed in order and the single OUT value or return value becomes the method's result. Behind the scenes, Spring Data creates a JPA StoredProcedureQuery and Hibernate turns it into a JDBC call. Alternatively, we can define the call once with @NamedStoredProcedureQuery on an entity, listing each parameter with its mode and type, and refer to it by name.

Java
public interface InvoiceRepository extends JpaRepository<Invoice, Long> {
@Procedure(procedureName = "open_total")
BigDecimal openTotal(Long customerId);
}
// Or, defined on an entity:
@NamedStoredProcedureQuery(name = "Invoice.openTotal", procedureName = "open_total",
parameters = {
@StoredProcedureParameter(mode = ParameterMode.IN, name = "p_customer", type = Long.class),
@StoredProcedureParameter(mode = ParameterMode.OUT, name = "total", type = BigDecimal.class)})
@Entity class Invoice { ... }
// in the repository: @Procedure(name = "Invoice.openTotal") BigDecimal openTotal(@Param("p_customer") Long id);
invoiceRepository.openTotal(42L); // 150.50

Notice that PostgreSQL makes this route slightly delicate, because open_total is a function, not a procedure, and how Hibernate calls a function through StoredProcedureQuery on PostgreSQL has changed between Hibernate versions and depends on the declared parameters. It works well for real procedures; for a function, test it on your Hibernate version, or use the next way, which is simpler.

3Way 2: A Native Query

Since a function is just part of a SELECT, a native query is often the most direct way to call it. Spring Data runs the SQL as written, binds the named parameter, and converts the single column of the single row into the return type.

Java
public interface InvoiceRepository extends JpaRepository<Invoice, Long> {
@Query(value = "select open_total(:id)", nativeQuery = true)
BigDecimal openTotal(@Param("id") Long id);
}
invoiceRepository.openTotal(42L); // 150.50
invoiceRepository.openTotal(7L); // 0

This version works the same on every Hibernate version and makes the SQL visible to the reader. Its limit is that it only handles a return value; OUT parameters and procedures need the stored procedure APIs.

4Full Control With StoredProcedureQuery

When a call has several OUT parameters or returns a cursor, we use the JPA API directly, usually in a custom repository fragment. registerStoredProcedureParameter declares each parameter with its position or name, Java type and mode: IN, OUT, INOUT or REF_CURSOR. A REF_CURSOR parameter returns a result set, which on PostgreSQL only lives inside the transaction, so the call must run in one.

Java
@Transactional(readOnly = true)
public List<Object[]> openInvoices(long customerId) {
StoredProcedureQuery q = em.createStoredProcedureQuery("open_invoices")
.registerStoredProcedureParameter(1, Long.class, ParameterMode.IN)
.registerStoredProcedureParameter(2, void.class, ParameterMode.REF_CURSOR)
.setParameter(1, customerId);
q.execute();
return q.getResultList(); // rows read from the cursor before the transaction ends
}

5Testing With Testcontainers

H2 and other in-memory databases cannot run PL/pgSQL, and even for SQL functions their behaviour differs from PostgreSQL, so a test that passes on H2 proves little. Testcontainers starts a real PostgreSQL in Docker for the test, and Spring Boot's @ServiceConnection wires the DataSource to it. Flyway or Liquibase then apply the real migrations, including the function, so the test runs the same code as production.

Java
@SpringBootTest
@Testcontainers
class InvoiceRepositoryTest {
@Container @ServiceConnection
static PostgreSQLContainer<?> db = new PostgreSQLContainer<>("postgres:17");
@Autowired InvoiceRepository repo;
@Autowired JdbcTemplate jdbc;
@Test
void sumsOnlyOpenInvoices() {
jdbc.update("insert into invoice (customer_id, amount, status) values (42, 100.00, 'OPEN'), (42, 50.50, 'OPEN'), (42, 999.00, 'PAID')");
assertThat(repo.openTotal(42L)).isEqualByComparingTo("150.50");
assertThat(repo.openTotal(7L)).isEqualByComparingTo("0");
}
}

Notice isEqualByComparingTo for BigDecimal: equals() would treat 150.50 and 150.5 as different because of their scale. Test classes with the same container configuration can share one container instance to keep the suite fast.

6What Can Go Wrong With Transaction Boundaries

The first problem is procedures that commit. A PostgreSQL procedure may COMMIT inside its body only when CALL is not inside an explicit transaction. A Spring @Transactional method always has one open, so such a call fails with invalid transaction termination. Either the procedure leaves transaction control to the caller, which is usually best, or the Java code calls it outside any Spring transaction on an autocommit connection, and accepts that it is no longer part of the caller's unit of work.

The second problem is the persistence context, Hibernate's first-level cache of entities loaded in the current transaction. Hibernate does not know which rows a procedure or a native update changes. If we loaded Invoice 5, then call a procedure that marks it paid, the Invoice object in memory still says OPEN, and if we later change and save it, we may overwrite the procedure's change. In the other direction, changes we made to entities but have not flushed yet are invisible to the procedure, which reads the database. So we flush before the call, to make pending changes visible, and clear after it, or refresh the affected entities, so we read fresh state.

Java
@Transactional
public void settle(long invoiceId) {
Invoice inv = invoiceRepo.findById(invoiceId).orElseThrow();
inv.setNote("settling");
em.flush(); // the UPDATE for the note reaches the database first
invoiceRepo.markPaid(invoiceId); // @Procedure that updates status in the database
em.clear(); // drop stale entities from the persistence context
invoiceRepo.findById(invoiceId).get().getStatus(); // PAID, read fresh
}
// Without flush and clear: getStatus() returns OPEN from the cached entity
Step throughFlush before, clear after
ServicePersistence contextDatabase
findById(5): Invoice status OPEN, cached
setNote(...): change pending in memory
flush: UPDATE invoice note
markPaid(5): procedure sets status PAID
clear: forget cached Invoice
findById(5): reads PAID

6 messages in order. Play them, or step through them one at a time.

Flushing shows our changes to the procedure; clearing shows the procedure's changes to us.

A third detail: if the repository method runs in a read-only transaction and the database code writes, PostgreSQL rejects the write with an error saying it cannot execute the statement in a read-only transaction. Check which transaction settings apply to the method, and mark write calls with @Transactional explicitly.

7Follow-up questions

Should the @Procedure method be @Transactional?

It runs in the caller's transaction if there is one, which is what we want for consistency. If the database code writes, make sure the surrounding transaction is not read-only. Calls that return a REF_CURSOR need a transaction on PostgreSQL, because the cursor is closed at commit.

Is a @Modifying annotation needed for a native query that calls a writing function?

@Modifying is for native or JPQL statements that return an update count, such as UPDATE or DELETE. A SELECT that calls a function returns a value, so it is a normal query; the important part is that it runs in a read-write transaction and that we clear the persistence context if it changed rows we hold as entities.

8Conclusion

In this answer, we called a database function from Spring Data JPA with @Procedure, or a @NamedStoredProcedureQuery on an entity, and with a native @Query that selects the function, which is often simpler for functions on PostgreSQL. StoredProcedureQuery with registerStoredProcedureParameter gives full control over IN, OUT and REF_CURSOR parameters. We tested with Testcontainers and the real migrations, since H2 cannot run PL/pgSQL. Finally we saw that procedures which commit cannot run inside a Spring transaction, and that we should flush before and clear after a call that changes rows held in the persistence context.

What to say in the interviewAbout 90 seconds aloud

Open with

The first way is @Procedure on a repository method, for example @Procedure with procedureName open_total on a method that takes the customer id and returns BigDecimal. Spring Data turns that into a JPA StoredProcedureQuery.

Then, if they want more

I can also define the call with @NamedStoredProcedureQuery on an entity and refer to it by name. On PostgreSQL, open_total is a function rather than a procedure, and how Hibernate calls functions through that API depends on the version, so I would test it.

The second way is a native query, @Query with select open_total of :id and nativeQuery true, which is the simplest for a function returning one value. For multiple OUT parameters or a REF_CURSOR, I would use StoredProcedureQuery directly with registerStoredProcedureParameter.

For testing, I would use Testcontainers with a real PostgreSQL and the real Flyway migrations, because H2 cannot run PL/pgSQL and its SQL differs anyway, and assert BigDecimals with compareTo. On transactions, three things. A procedure that commits internally cannot run inside a Spring transaction, so I keep transaction control in Java.

Hibernate's persistence context does not know what the database code changed, so I flush before the call so it sees my pending changes, and clear or refresh after it so I do not read or overwrite stale entities. And if the code writes, the transaction must not be read-only.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Call a database function from Spring Data JPA in two ways: with @Procedure on a...": https://scrivio-interview-library.netlify.app/databases/stored-code/d4b2417099/