其他分享
首页 > 其他分享> > Spring: transaction

Spring: transaction

作者:互联网

 

声明式:

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-aop:2.7.0'
    implementation group: 'org.springframework', name: 'spring-aspects', version: '5.3.18'
    implementation('org.springframework:spring-jdbc:5.3.20')
    implementation('com.alibaba:druid-spring-boot-starter:1.2.9')
    implementation('mysql:mysql-connector-java:8.0.29')
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

 

配置类

@Configuration
public class Config{
  @Bean
  public DataSource dataSource(){
    DruidDataSource druidDataSource = new DruidDataSource();
    druidDataSource.setUrl("jdbc:mysql://localhost:3306/java");
    druidDataSource.setUsername("root");
    druidDataSource.setPassword("coalesce");
    druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
    return druidDataSource;
  }

  @Bean
  public JdbcTemplate jdbcTemplate(DataSource dataSource){
    return new JdbcTemplate(dataSource);
  }
  @Bean
  public TransactionManager transactionManager(DataSource dataSource){
    return new DataSourceTransactionManager(dataSource);
  }
}

 

DAO:

@Repository
public class VengeDao{
  @Autowired
  private JdbcTemplate jdbcTemplate;

  public int insert(){
    String sql = "INSERT INTO auth (name,password) VALUES (?,?)";
    String name = UUID.randomUUID().toString().substring(0, 5);
    Random random = new Random();
    Integer password = random.nextInt(1000, 10000);
    int update = jdbcTemplate.update(sql, name, password);
    int b = 10 / 0;
    return update;
  }
}

 

Service

@Service
@EnableTransactionManagement
public class VengeService{
  @Autowired
  private VengeDao vengeDao;

  @Transactional
  public int insertVenge(){
    return vengeDao.insert();

  }
}

 

@ComponentScan("io.vent.venial")
public class VenialApplication{
  public static void main(String[] args){
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    context.registerBean(VenialApplication.class);
    context.refresh();
    VengeService vengeService = context.getBean(VengeService.class);
    System.out.println("vengeService.insertVenge() = " + vengeService.insertVenge());
    for(String beanDefinitionName : context.getBeanDefinitionNames()){
      System.out.println("\033[37;7m>>>>>> " + beanDefinitionName + " <<<<<<\033[0m");
    }
    context.close();
  }
}

 

标签:transaction,implementation,Spring,boot,spring,druidDataSource,org,public
来源: https://www.cnblogs.com/dissipate/p/16344683.html