Spring-Data-JDBC + Mybatis-plus 实现DDD仓储层,实现1+1 >= 2

Spring-Data-JDBC整合 Mybatis-plus

**spring-data-jdbc官方文档

  1. 项目目录结构:

  2. 导入Maven依赖

  <!-- mybatis-plus的代码生成器 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.5.2</version>
        </dependency>

        <!-- mybatis-plus的stater -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>


        <!-- 代码生成器依赖的模板 -->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.3</version>
        </dependency>
    </dependencies>

        <!-- 导入Spring Data JDBC 实现DDD的功能-->

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jdbc</artifactId>
        </dependency>

        <!-- MySQL 驱动, 注意, 这个需要与 MySQL 版本对应 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

根据自身选择 是否使用mybatis-plus的代码生成器,如果不使用则无需导入

 <!-- mybatis-plus的stater -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>
        <!-- 代码生成器依赖的模板 -->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.3</version>
        </dependency>
    </dependencies>
  1. yam文件配置
#mp
mybatis-plus:
  #这里的路径就是打包出来的 target路径
  mapper-locations: classpath*:com/imoc/ecommerce/mapper/xml/*.xml
  configuration:
      log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
      map-underscore-to-camel-case: true


#springdata-jdbc打印输出
logging:
  level:
    org.springframework.jdbc.core.JdbcTemplate: DEBUG
spring:
  datasource:
    # 数据源
    url: jdbc:mysql://127.0.0.1:3306/数据库名?autoReconnect=true&useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
    username: 数据库连接账号
    password: 密码
  1. mybatis + spring-data-jdbc的整合的配置文件,放在能被spring容器扫描注入的packge下面即可。
@Configuration
@EnableJdbcRepositories
@EnableJdbcAuditing  // 开始审计注解
@Import(MyBatisJdbcConfiguration.class)
public class MyBatisConfiguration {}
  1. 编写实体类
@Getter
@Setter
@Accessors(chain = true)
@TableName("t_ecommerce_address") 、、
@Table("t_ecommerce_address")
public class EcommerceAddress implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 自增主键
     */
    @TableId(value = "id", type = IdType.AUTO)
    @Id // 这个是spring-data-jdbc的注解
    private Long id;

    /**
     * 详细地址
     */
    @TableField("address_detail")
    @Column("address_detail")
    private String addressDetail;

    /**
     * 创建时间
     */
    @TableField(value = "create_time",fill = FieldFill.INSERT)
    @Column("create_time")
    @CreatedDate // 创建时候自动 填充为 当前时间
    private LocalDate createTime;

    /**
     * 更新时间
     */
    @TableField(value = "update_time",fill = FieldFill.INSERT)
    @Column("update_time")
    @LastModifiedDate // 更新时候自动 填充为 当前时间
    private LocalDate updateTime;```

} 

其中 @TableField(value = "update_time",fill = FieldFill.INSERT) 这是mybatis-plus的注解,使用fill = FieldFill.INSERT 按照官网文档的操作就会在插入时候自动更新时间。

spring-data-jdbc 用到 官方文档的 :审计篇章来实现
其中 创建时间 @CreatedDate 和 更新时间用@LastModifiedDate 实现,但是注意:

坑: 上面两个注解支持的数据格式为: 实现了 TemporalAccessor接口的时间类。
坑: 要在

  1. Repository层的实现 Application.class 或者 MyBatisConfiguration.class 上添加注解@EnableJdbcAuditing 使得审记注解有效!!!

/**
 * spring-data-jdbc实现DDD中 Repository
 */
@Repository
public interface AddressRepository extends PagingAndSortingRepository<EcommerceAddress,Long> {
	/**
	**  这里利用了 JPA的规范,通过IDEA自动就可以生成简单的sql
	**/
    List<EcommerceAddress> findAllByUserId(Long userId);



mapper层的实现我是用mybatis-plus代码生成器完成的。这里用的是spring-boot无需烦人的配置,都已经自动配置好了。

  1. spring-data-jdbc审计功能
    实现 BeforeSaveCallback<T> 即可在插入之前进行操作(如加密、解密)
    全部的实体回调如下

在这里插入图片描述


@Component
public class EcommerceAddressCallbacks implements BeforeSaveCallback<EcommerceAddress> {

    @Override
    public EcommerceAddress onBeforeSave(EcommerceAddress aggregate, MutableAggregateChange<EcommerceAddress> aggregateChange) {
        /** 插入前的一些操作,如数据加密等。。。 **/
        return aggregate;
    }
}



  1. 在Service层导入 Repository 和 Mapper 文件即可食用。
@Service
@Slf4j
public class AddressServiceImpl extends ServiceImpl<AddressMapper, EcommerceAddress> implements IAddressService {
    @Autowired
    AddressRepository addressRepository;
	

    @Override
    public TableId createAddressInfo(AddressInfo addressInfo) {
        /**
         * 获取由拦截器从请求头中token 经过JWT解析出来的 LoginUserInfo对象
         */
        LoginUserInfo loginUserInfo = AccessContext.getLoginUserInfo();

        // 将传递的参数转换为实体对象
        List<EcommerceAddress> ecommerceAddressList =
                addressInfo.getAddressItems().stream()
                        .map(a -> EcommerceAddress.to(loginUserInfo.getId(),a))
                        .collect(Collectors.toList());

        // 保存到数据表并把返回记录的 id给调用方
        List<Long> ids = StreamSupport.stream(
                addressRepository.saveAll(ecommerceAddressList).spliterator(),false)
                .map(EcommerceAddress::getId).collect(Collectors.toList());
        log.info("create address info: [{}] [{}] ",loginUserInfo.getId(),JSON.toJSONString(ids));

        // 返回
        return new TableId(
                ids.stream().map(TableId.Id::new).collect(Collectors.toList())
        );
    }
}    
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是 Spring Boot 集成 Sharding-JDBC + Mybatis-Plus 实现分库分表的实战代码: 1. 添加依赖 在 `pom.xml` 文件中添加以下依赖: ```xml <dependencies> <!-- Sharding-JDBC --> <dependency> <groupId>io.shardingsphere</groupId> <artifactId>sharding-jdbc-core</artifactId> <version>4.1.1</version> </dependency> <!-- Mybatis-Plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.3</version> </dependency> <!-- MySQL 驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.24</version> </dependency> </dependencies> ``` 2. 配置数据源 在 `application.yml` 文件中配置数据源: ```yaml spring: datasource: # 主库 master: url: jdbc:mysql://localhost:3306/db_master?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver # 从库 slave: url: jdbc:mysql://localhost:3306/db_slave?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver ``` 3. 配置 Sharding-JDBC 在 `application.yml` 文件中配置 Sharding-JDBC: ```yaml spring: shardingsphere: datasource: names: master, slave # 数据源名称 master: type: com.zaxxer.hikari.HikariDataSource slave: type: com.zaxxer.hikari.HikariDataSource config: sharding: tables: user: actualDataNodes: master.user_$->{0..1} # 分表规则,user_0 和 user_1 表 tableStrategy: inline: shardingColumn: id algorithmExpression: user_$->{id % 2} # 分表规则,根据 id 取模 databaseStrategy: inline: shardingColumn: id algorithmExpression: master # 分库规则,根据 id 取模 bindingTables: - user # 绑定表,即需要进行分库分表的表 ``` 4. 配置 Mybatis-Plus 在 `application.yml` 文件中配置 Mybatis-Plus: ```yaml mybatis-plus: configuration: map-underscore-to-camel-case: true # 下划线转驼峰 ``` 5. 编写实体类 创建 `User` 实体类,用于映射数据库中的 `user` 表: ```java @Data public class User { private Long id; private String name; private Integer age; } ``` 6. 编写 Mapper 接口 创建 `UserMapper` 接口,用于定义操作 `user` 表的方法: ```java @Mapper public interface UserMapper extends BaseMapper<User> { } ``` 7. 编写 Service 类 创建 `UserService` 类,用于调用 `UserMapper` 接口中的方法: ```java @Service public class UserService { @Autowired private UserMapper userMapper; public User getById(Long id) { return userMapper.selectById(id); } public boolean save(User user) { return userMapper.insert(user) > 0; } public boolean updateById(User user) { return userMapper.updateById(user) > 0; } public boolean removeById(Long id) { return userMapper.deleteById(id) > 0; } } ``` 8. 测试 在 `UserController` 类中进行测试: ```java @RestController public class UserController { @Autowired private UserService userService; @GetMapping("/user") public User getUser(Long id) { return userService.getById(id); } @PostMapping("/user") public boolean addUser(@RequestBody User user) { return userService.save(user); } @PutMapping("/user") public boolean updateUser(@RequestBody User user) { return userService.updateById(user); } @DeleteMapping("/user") public boolean removeUser(Long id) { return userService.removeById(id); } } ``` 启动应用程序,访问 `http://localhost:8080/user?id=1` 可以得到 `id` 为 1 的用户信息。访问 `http://localhost:8080/user` 并传入用户信息,可以添加用户。访问 `http://localhost:8080/user` 并传入更新后的用户信息,可以更新用户信息。访问 `http://localhost:8080/user?id=1` 并使用 DELETE 方法,可以删除用户。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值