#3125 Add query.usingMaster() for query beans

This commit is contained in:
Rob Bygrave
2023-07-03 23:30:02 +12:00
parent 262a7f9bab
commit ac466ecd79
2 changed files with 24 additions and 1 deletions
@@ -12,6 +12,7 @@ import io.ebean.text.PathProperties;
import io.ebeaninternal.api.SpiQueryFetch;
import io.ebeaninternal.server.util.ArrayStack;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.Timestamp;
import java.util.*;
@@ -1560,6 +1561,21 @@ public abstract class TQRootBean<T, R> {
return root;
}
/**
* Ensure that the master DataSource is used if there is a read only data source
* being used (that is using a read replica database potentially with replication lag).
* <p>
* When the database is configured with a read-only DataSource via
* say {@link io.ebean.config.DatabaseConfig#setReadOnlyDataSource(DataSource)} then
* by default when a query is run without an active transaction, it uses the read-only data
* source. We we use {@code usingMaster()} to instead ensure that the query is executed
* against the master data source.
*/
public R usingMaster() {
query.usingMaster();
return root;
}
/**
* Execute the query returning true if a row is found.
* <p>
@@ -276,8 +276,15 @@ public class QCustomerTest {
}
@Test
public void usingTransaction() {
public void usingMaster() {
new QCustomer()
.registered.isNull()
.usingMaster()
.findList();
}
@Test
public void usingTransaction() {
try (Transaction transaction = DB.getDefault().createTransaction()) {
new QCustomer()