dawdler-mybatis-core
Module introduction
The MyBatis core module.
1. Add the dependency to the pom
<groupId>club.dawdler</groupId>
<artifactId>dawdler-mybatis-core</artifactId>
2. mybatis-config.xml configuration (optional)
mybatis-config.xml is the configuration file officially supported by MyBatis. Refer to the official documentation for the other settings; an example is given below:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<!-- Package scanning: entity classes scanned this way are aliased to their class name with a lowercase first letter (for example, Bean -> bean) -->
<!-- <package name="com.anywide.shop.order.entity"/> -->
<!-- Declare aliases one by one -->
<typeAlias alias="Order" type="com.anywide.shop.order.entity.Order" />
</typeAliases>
<mappers>
<!-- Add a mapper -->
<mapper resource="com/anywide/shop/order/mapper/xml/Order.xml" />
</mappers>
</configuration>
3. Inject Mapper
In the service layer, inject the mapper with @Repository and it is ready to use.
Example:
public class OrderServiceImpl implements OrderService{
@Repository
OrderMapper orderMapper;
@Override
@DBTransaction
public boolean createOrder(Integer userId,Integer productId, BigDecimal amount) {
Order order = new Order();
order.setAddtime((int)(System.currentTimeMillis()/1000));
order.setAmount(amount);
order.setProductId(productId);
order.setUserId(userId);
return orderMapper.insert(order) > 0;
}
}
4. Cursor and ResultHandler
Mapper methods can either return a Cursor<T> or declare a ResultHandler<T> parameter; both query styles are routed to a read connection just like ordinary queries.
Note: a Cursor must be fully consumed within the scope of the @DBTransaction method; do not return it outside the transaction method and iterate it later. When the transaction ends, the read connection is returned and closed, so iterating the cursor after leaving the transaction scope fails because the connection is already closed.
@Override
@DBTransaction
public int countOrder() {
int count = 0;
try (Cursor<Order> cursor = orderMapper.selectAll()) {
for (Order order : cursor) {
count++;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return count;
}
5. Horizontal sharding configuration
dawdler supports horizontal sharding, configured through the combination of the SubTable annotation and the @SubParam annotation.
Note: you need to create the tables that the sharding rules map to, otherwise the corresponding table cannot be found. For example, t_user_0, t_user_1, t_user_2.
/**
* @author jackson.song
* @version V1.0
* Sharding annotation, used to mark a MyBatis interface method
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SubTable {
String expression();
String[] tables();
String configPath();
Class<? extends SubRule> subRuleType();
}
/**
* @author jackson.song
* @version V1.0
* Sharding parameter annotation, used to mark a method parameter of a MyBatis interface
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface SubParam {
}
Parameter description:
expression: specifies the sharding expression. For example, if the sharding field is id, the parameter name is id; object parameters are also supported -- for example, if the sharding field is the id of the object user, the expression is user.id.
tables: specifies the table names to shard, and supports multiple table names.
configPath: specifies the path of the sharding rule configuration file. The file is in yml format (a unified configuration center is supported).
subRuleType: specifies the implementation class of the sharding rule, which must implement the SubRule interface.
dawdler provides the following sharding rule implementations: ConsistentHashSubRule and RemainderSubRule. You can extend them for other requirements.
Startup-time validation
A MyBatis statement id (fully qualified interface name.method name) does not include the parameter signature, so methods with the same name share a single statement and the statement side cannot tell which overload is being called. dawdler builds a statement id -> mapper method binding table while the SqlSessionFactory is being constructed and validates it (in the scenario where SubTableInterceptor is registered manually, the same validation is performed on first execution). The following shapes fail validation and refuse to start, rather than silently skipping table-name rewriting at runtime or rewriting with the wrong rule:
- A mapper method has an executable same-name overload (same name, different parameters) and any overload is annotated with @SubTable: the statement id cannot distinguish the overloads, so please rename the methods. default/static overloads hold no statement and are unaffected; "@SubTable abstract method + default same-name overload" can still bind to the abstract declaring method normally.
- @SubTable is placed on a default or static method: such a method does not produce a statement execution, so the annotation has no effect.
- A @SubTable method has no corresponding MyBatis statement (for example, the statement id has been renamed in the XML): the annotation and the statement have drifted apart.
ConsistentHashSubRule: a sharding rule implemented with the consistent hashing algorithm. It requires configuring the number of virtual nodes and the node list. Each physical node is expanded into numberOfReplicas virtual nodes on the hash ring, 160 by default (the Ketama convention); too few virtual nodes lead to skewed load and more key migration than expected when nodes are added or removed.
Example:
numberOfReplicas: 160
nodes:
- 0
- 1
- 2
RemainderSubRule: a sharding rule implemented with the modulo algorithm. It requires configuring the divisor.
Example:
divisor: 3
The following demonstrates sharding by user id using modulo 3.
userById.yml
divisor: 3
/**
* Query the [user table] with horizontal sharding by user id
* @version 1.0
* @param id user id
*/
@SubTable(configPath = "userById", tables = {"t_user"}, subRuleType = RemainderSubRule.class, expression = "id")
User selectByPrimaryKey(@SubParam @Param("id")Integer id);
/**
* Query the [user table] with horizontal sharding by reading the id from the user object expression
* @version 1.0
* @param user the user object
*/
@SubTable(configPath = "userById", tables = {"t_user"}, subRuleType = RemainderSubRule.class, expression = "user.id")
User selectByPrimaryKey(@SubParam @Param("user") User user);
6. Printing SQL logs
Add the following configuration to mybatis-config.xml to print SQL logs:
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
Add the following configuration to logback.xml:
<logger name="org.apache.ibatis.logging.jdbc">
<level value="DEBUG"/>
</logger>