spring-mybatis

org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.example.mapper.AccountMapper.selectAccount

maven在配置的时候会自动忽略xml文件

        
        
            
                src/main/java
                
                    **/*.xml
                    **/*.properties
                
                true
            
        

### Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: Cannot create PoolableConnectionFactory (Access denied for user 'GF'@'localhost' (using password: YES))
spring-mybatis_第1张图片

写的都是对的但是报错了,这是个坑

解决方法

db.propertise

spring-mybatis_第2张图片

applicationContext.xml

spring-mybatis_第3张图片

username写成两段

运行结果

spring-mybatis_第4张图片

单元测试@Test加@Transactional注解自动回滚

spring-mybatis_第5张图片

spring-mybatis_第6张图片

去掉以后不会回滚

spring-mybatis_第7张图片

数据库会更新

基础文件

spring-mybatis_第8张图片

Account

package com.example.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Account {
    private Long id;
    private String accountno;
    private String password;
    private Double balance;
}

AccountMapper

package com.example.mapper;

import com.example.entity.Account;

public interface AccountMapper {

    //查询账户
    Account selectAccount (String accountno);

    //更新账户
    void updateAccount(Account account);
}

AccountMapper.xml




    

    
        update spring_account set accountno=#{accountno},password=#{password},balance=#{balance} where id=#{id}
    

AccountService

package com.example.service;

public interface AccountService {

    //转账
    void transfer(String fromAccountNo,String toAccountNo,double money);
}

AccountServiceImpl

package com.example.service;


import com.example.entity.Account;
import com.example.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
//@Transactional
public class AccountServiceImpl implements AccountService {

    @Autowired
    AccountMapper accountMapper;
    @Override
    public void transfer(String fromAccountNo, String toAccountNo, double money) {

        Account fromAccount=accountMapper.selectAccount(fromAccountNo);
        fromAccount.setBalance(fromAccount.getBalance()-money);
        Account toAccount=accountMapper.selectAccount(toAccountNo);
        toAccount.setBalance(toAccount.getBalance()+money);
        accountMapper.updateAccount(fromAccount);
        accountMapper.updateAccount(toAccount);
    }
}

 

xml+注解

applicationContext.xml




    
    

    
    

    
    

    
    
    
    
        
        
        
        
        
        
        
        
    
    
    
        
        
        
        
        
        
    

    
    
        
        
    

    
    
        
    



db.properties

# 数据库配置文件
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring?serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=123456
jdbc.initialSize=10
jdbc.maxTotal=5
jdbc.maxIdle=5
jdbc.maxWaitMillis=5000



SqlMapConfig.xml





    
        
        
        

        
    
    
    
        
        
    

log4j.properties

### 设置###
log4j.rootLogger = debug,stdout,D,E

### 输出信息到控制抬 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n

### 输出DEBUG 级别以上的日志到=D://Projects/java/Mybatis/logs/log.log  ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = D://Projects/java/Mybatis/logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG 
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

### 输出ERROR 级别以上的日志到=D://Projects/java/Mybatis/logs/log.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =D://Projects/java/Mybatis/logs/log.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR 
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

全注解

全注解版本就不要xml文件了,新增AppConfig

package com.example;

import org.apache.commons.dbcp2.BasicDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;


@Configuration
@ComponentScan
@EnableTransactionManagement
@EnableAspectJAutoProxy
@PropertySource("classpath:db.properties")
//mapper扫描器
@MapperScan(basePackages = "com.example.mapper")
public class AppConfig {

    @Autowired
    Environment env;

    //数据源
    @Bean
    public DataSource dataSource() {
        BasicDataSource bds = new BasicDataSource();
        bds.setDriverClassName(env.getProperty("jdbc.driver"));
        bds.setUrl(env.getProperty("jdbc.url"));
        bds.setUsername(env.getProperty("jdbc.username"));
        bds.setPassword(env.getProperty("jdbc.password"));
        bds.setInitialSize(Integer.parseInt(env.getProperty("jdbc.initialSize")));
        bds.setMaxTotal(Integer.parseInt(env.getProperty("jdbc.maxTotal")));
        bds.setMaxIdle(Integer.parseInt(env.getProperty("jdbc.maxIdle")));
        bds.setMaxWaitMillis(Long.parseLong(env.getProperty("jdbc.maxWaitMillis")));
        return bds;
    }

    //SqlSessionFactory
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean() {
        SqlSessionFactoryBean sqlSessionFactoryBean = null;
        sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        //spring整合mybatis配置文件
        //别名
        sqlSessionFactoryBean.setTypeAliasesPackage("com.example.entity");
        //mybatis框架其他配置


        return sqlSessionFactoryBean;
    }


    //事务管理器
    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager() {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource());
        return dataSourceTransactionManager;
    }

}

测试类

spring-mybatis_第9张图片

AccountMapperTest
package com.example.mapper;

import com.example.BaseTest;
import com.example.entity.Account;
import junit.framework.TestCase;
import org.junit.Test;

public class AccountMapperTest extends BaseTest {

    @Test
    public void testSelectAccount() {
        Account account=accountMapper.selectAccount("10001");
        System.out.println(account);
    }

    @Test
    public void testUpdateAccount() {
    }
}
AccountServiceTest
package com.example.service;

import com.example.BaseTest;
import org.junit.Test;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


//@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
public class AccountServiceTest extends BaseTest {

    @Test
    public void testTransfer() {
        accountService.transfer("10001", "10002", 1000);
    }


}
BaseTest
package com.example;

import com.example.mapper.AccountMapper;
import com.example.service.AccountService;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@ContextConfiguration(locations = "classpath:applicationContext.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class BaseTest {

    @Autowired
    public AccountMapper accountMapper;

    @Autowired
    public AccountService accountService;
}

运行结果

spring-mybatis_第10张图片

你可能感兴趣的:(java)