Logo
Force Routing

Force Routing #

Introduction #

DBPlusEngine uses ThreadLocal to manage master database routing flags for forced routing. The master database routing marks can be added to the HintManager programmatically, and this value only takes effect in the current thread. DBPlusEngine can also enforce routing by adding comments in SQL.

The Hint is mainly used to force certain data operations in the master database in the read-write splitting scenario.

Operation Steps #

  1. Call HintManager.getInstance() to get the HintManager instance;

  2. Call the HintManager.setWriteRouteOnly() method to set the master database routing marks;

  3. Execute SQL statements to complete routing and execution;

  4. Call HintManager.close to clean up the content of ThreadLocal.

Configuration Example #

Use Hint To Force Master Routing #

Using Manual Programming #

Obtain HintManager #

Same as Hint-based data sharding.

Set Up the Master Database Routing #

Use hintManager.setWriteRouteOnly to set the master database routing.

Clear Sharding Key Value #

Same as Hint-based data sharding.

Complete code example #
String sql = "SELECT * FROM t_order";
try (HintManager hintManager = HintManager.getInstance();
     Connection conn = dataSource.getConnection();
     PreparedStatement preparedStatement = conn.prepareStatement(sql)) {
    hintManager.setWriteRouteOnly();
    try (ResultSet rs = preparedStatement.executeQuery()) {
        while (rs.next()) {
            // ...        }
    }
}

Use SQL Comments Method #

Terms of Use #

The SQL Hint function requires the user to enable the configuration of parsing comments in advance and set sqlCommentParseEnabled to true. The comment format currently only supports /* */. The content needs to start with SHARDINGSPHERE_HINT:, and the property name is WRITE_ROUTE_ONLY.

Complete example #
/* SHARDINGSPHERE_HINT: WRITE_ROUTE_ONLY=true */
SELECT * FROM t_order;