数据库类型:MySQL
数据库版本:8.0.36
请务必让导入的mysql包与数据库版本兼容
源码仓库:java_spring_learn_repo/tree/master/spring_mybatis
jdbc配置文件需自行添加,下文有模板样例
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.2version>
dependency>
<dependency>
<groupId>com.mysqlgroupId>
<artifactId>mysql-connector-jartifactId>
<version>8.1.0version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.10version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.6version>
dependency>
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://xxxxxxx
jdbc.username=xxxxx
jdbc.password=xxxxx
@PropertySource("classpath:jdbc.properties")
@PropertySource("classpath:jdbc.properties")
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean
public DataSource dataSource() {
DruidDataSource ds = new DruidDataSource();
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
return ds;
}
}
@Bean
public SqlSessionFactoryBean createSqlSessionFactory(DataSource dataSource){
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
// 配置类型别名
sqlSessionFactoryBean.setTypeAliasesPackage("com.nobugnolife.entity");
// 传入druid的datasource
sqlSessionFactoryBean.setDataSource(dataSource);
return sqlSessionFactoryBean;
}
@Bean
public MapperScannerConfigurer maperConfigurer(){
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("com.nobugnolife.dao");
return mapperScannerConfigurer;
}
public interface UserDao {
@Select("select id,name,money from tb_user where id=#{id}")
User findUserById(Integer id);
@Update("update tb_user set money=#{money} where id=#{id}")
Integer updateMoneyById(@Param("id")Integer id,@Param("money") Double money);
@Select("select id,name,money from tb_user")
List<User> findAll();
}
@Override
public User buySomeThing(Integer id, Double productValue) {
User user = userDao.findUserById(id);
user.setMoney(user.getMoney()-productValue);
Integer msg = userDao.updateMoneyById(id,user.getMoney());
// 不做任何边界检测,直接返回数据
return user;
}
@Test
public void testBuySomeThing(){
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
UserService userService = ctx.getBean(UserService.class);
Double productValue = 25.00;
User user = userService.buySomeThing(1,productValue);
System.out.println("用户:"+user.getName()+"在某xx平台消费了"+productValue+"\t当前余额:"+user.getMoney());
}
