Spring Boot 实践:MyBatis

本文介绍了如何在Spring Boot项目中使用MyBatis进行数据库操作。内容包括配置generatorConfig.xml进行代码生成,利用VirtualPrimaryKeyPlugin和LombokPlugin增强功能,设置generatedKey,以及创建Controller层使用ResponseEntity处理响应,配合@Valid验证请求参数,定义HttpStatus和Api-Version。在Service层,使用InDTO和OutDTO进行数据转换,并应用@Transactional进行事务管理。最后提到了全局异常处理的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

generatorConfig.xml 

  • 自动生成之外,也可同时手动创建,通过mapper2.xml中的namespace来指定mapper2对象即可。
  • VirtualPrimaryKeyPlugin
  • LombokPlugin
  • generatedKey
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
 
<generatorConfiguration>
  <properties  resource="application.properties"/>
  <!--数据库链接URL,用户名、密码 -->
  <context id="MySQL" targetRuntime="MyBatis3">
    <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
    <plugin type="org.mybatis.generator.plugins.ToStringPlugin" />
    <plugin type="org.mybatis.generator.plugins.VirtualPrimaryKeyPlugin" />
    <plugin type="com.softwareloop.mybatis.generator.plugins.LombokPlugin">
         <property name="allArgsConstructor" value="true"/>
         <property name="noArgsConstructor" value="true"/>
    </plugin>
    <commentGenerator>
            <property name="suppressDate" value="true"/>  
            <property name="suppressAllComments" value="true"/>  
    </commentGenerator> 
    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
        connectionURL="${spring.datasource.url}"
        userId="${spring.datasource.username}"
        password="${spring.datasource.password}">
    </jdbcConnection>
 
    <!--是否启用java.math.BigDecimal-->
    <javaTypeResolver >
      <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>
    <!-- 生成模型的包名和位置--> 
    <javaModelGenerator targetPackage="com.aaa.pay.model" targetProject="src/main/java">
      <property name="enableSubPackages" value="true" />
      <property name="trimStrings" value="true" />
    </javaModelGenerator>
    <!-- 生成映射文件的包名和位置--> 
    <sqlMapGenerator targetPackage="com.aaa.pay.dao"  targetProject="src/main/resources">
      <property name="enableSubPackages" value="true" />
    </sqlMapGenerator>
    <!-- 生成DAO的包名和位置--> 
    <javaClientGenerator type="XMLMAPPER" targetPackage="com.aaa.pay.dao"  targetProject="src/main/java">
      <property name="enableSubPackages" value="true" />
    </javaClientGenerator>
    <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
    <table tableName="payment" domainObjectName="Payment" enableSelectByPrimaryKey="true"
               enableUpdateByPrimaryKey="true" enableDeleteByPrimaryKey="true" 
               enableCountByExample="true" enableUpdateByExample="true" 
               enableDeleteByExample="true" enableSelectByExample="true" 
               selectByExampleQueryId="true">
        <property name="virtualKeyColumns" value="id"/>
        <generatedKey column="id" sqlStatement="Mysql" identity="true" />
    </table>
    <table tableName="payment_timeline" domainObjectName="PaymentTimeline" enableSelectByPrimaryKey="true"
               enableUpdateByPrimaryKey="true" enableDeleteByPrimaryKey="true" 
               enableCountByExample="true" enableUpdateByExample="true" 
               enableDeleteByExample="true" enableSelectByExample="true" 
               selectByExampleQueryId="true">
        <generatedKey column="id" sqlStatement="Mysql" identity="true" />
    </table>
    <table tableName="payment_pricing" domainObjectName="PaymentPricing" enableSelectByPrimaryKey="true"
               enableUpdateByPrimaryKey="true" enableDeleteByPrimaryKey="true" 
               enableCountByExample="true" enableUpdateByExample="true" 
               enableDeleteByExample="true" enableSelectByExample="true" 
               selectByExampleQueryId="true">
        <generatedKey column="id" sqlStatement="Mysql" identity="true" />
    </table>
    <table tableName="payment_metadata" domainObjectName="PaymentMetadata" enableSelectByPrimaryKey="true"
               enableUpdateByPrimaryKey="true" enableDeleteByPrimaryKey="true" 
               enableCountByExample="true" enableUpdateByExample="true" 
               enableDeleteByExample="true" enableSelectByExample="true" 
               selectByExampleQueryId="true">
        <generatedKey column="id" sqlStatement="Mysql" identity="true" />
    </table>
    
  </context>
</generatorConfiguration>

Controller:

  • ResponseEntity<Map<String,Object>>
  • @Valid及内部对象
  • HttpStatus
  • Api-Version
    @PostMapping("/createPayment")
    public ResponseEntity<Map<String,Object>> createPayment(@Valid @RequestBody PaymentInDTO dto, BindingResult bindingResult){
    	log.info("data:{}", dto);
    	if(bindingResult.hasErrors()) { 
    		Map<String,Object> err = MiscUtil.getValidateError(bindingResult);
            return new ResponseEntity<Map<String,Object>>(err, HttpStatus.UNPROCESSABLE_ENTITY);
        }
    	
        PaymentOutDTO dtoOut = paymentService.createPayment(dto);
        Map<String, Object> result = new HashMap<String, Object>();        
        result.put("data", dtoOut);        
        return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
    }
    
    @PostMapping(value = "/createPayment", headers = "Api-Version=2")
    public ResponseEntity<Map<String,Object>> createPaymentV2(@Valid @RequestBody PaymentInDTO dto, BindingResult bindingResult){
    	log.info("data:{}", dto);
    	
        Map<String, Object> result = new HashMap<String, Object>();        
        result.put("data", "just test");        
        return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
    }

ServiceImpl:

  • InDTO
  • OutDTO
  • Transactional
@Override
@Transactional(rollbackFor={RuntimeException.class, Exception.class})
public PaymentOutDTO createPayment(PaymentInDTO dto) {
    	Date createAt = new Date(System.currentTimeMillis());

    	Payment payment = new Payment();
    	BeanUtils.copyProperties(dto, payment);    	
    	payment.setCode(MiscUtil.getUUID());
    	payment.setStatus(StatusEnum.STATUS_NEW.getCode());
    	payment.setCreatedAt(createAt);
    	payment.setLogoUrl("https://aaa.com/payments/aaa.png");//TODO
    	payment.setPaymentUrl("https://aaa.com/payments/"+payment.getCode());//TODO
    	paymentMapper.insertSelective(payment);

    	PaymentOutDTO dtoOut = new PaymentOutDTO();
    	BeanUtils.copyProperties(payment, dtoOut);
    	dtoOut.setStatus(StatusEnum.STATUS_NEW.getName());
    	
    	dto.getPrice().forEach(price -> {
    		PaymentPricing paymentPricing = new PaymentPricing();
    		BeanUtils.copyProperties(price, paymentPricing);
    		paymentPricing.setPaymentId(payment.getId()); 
    		paymentPricingMapper.insertSelective(paymentPricing);
    	});
    	dtoOut.setPrice(dto.getPrice());
    	
    	PaymentTimeline paymentTimeline = new PaymentTimeline();
    	paymentTimeline.setPaymentId(payment.getId());
    	paymentTimeline.setStatus(StatusEnum.STATUS_NEW.getCode());
    	paymentTimeline.setTime(createAt);
    	paymentTimelineMapper.insertSelective(paymentTimeline);
    	
    	PaymentTimelineOutDTO paymentTimelineOutDTO = new PaymentTimelineOutDTO();
    	BeanUtils.copyProperties(paymentTimeline, paymentTimelineOutDTO);
    	paymentTimelineOutDTO.setStatus(StatusEnum.STATUS_NEW.getName());
    	
    	List<PaymentTimelineOutDTO> timelineList = new ArrayList<PaymentTimelineOutDTO>();
    	timelineList.add(paymentTimelineOutDTO);
    	dtoOut.setTimeline(timelineList);
    	
    	dtoOut.setConfirmations(0);
    	
	return dtoOut;
}

全局异常处理:

@ControllerAdvice
public class CommonExceptionHandler {

    /**
     *  拦截Exception类的异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseEntity<Map<String,Object>> exceptionHandler(Exception e){
        Map<String,Object> result = new HashMap<String,Object>();
        result.put("message", "内部错误");
        result.put("description", e.getMessage());
        return new ResponseEntity<Map<String,Object>>(result, HttpStatus.INTERNAL_SERVER_ERROR); 
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值