Spring整合MyBatis,本质是将MyBastis的核心配置文件换成Spring来整合;
总结:总共需要配置两个bean:SqlSessionFactoryBean
和MapperScannerConfigurer
,(外加dataSource
)
即pojo实体类,对应数据库结构;
public class Account implements Serializable {private Integer id;private String name;private Double money;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Double getMoney() {return money;}public void setMoney(Double money) {this.money = money;}@Overridepublic String toString() {return "Account{" +"id=" + id +", name='" + name + '\'' +", money=" + money +'}';}
}
AccountDao:
即mapper代理接口类,对应mapper映射文件,此处使用注解的方式写sql;
public interface AccountDao {@Insert("insert into tbl_account(name,money)values(#{name},#{money})")void save(Account account);@Delete("delete from tbl_account where id = #{id} ")void delete(Integer id);@Update("update tbl_account set name = #{name} , money = #{money} where id = #{id} ")void update(Account account);@Select("select * from tbl_account")List findAll();@Select("select * from tbl_account where id = #{id} ")Account findById(Integer id);
}
public interface AccountService {void save(Account account);void delete(Integer id);void update(Account account);List findAll();Account findById(Integer id);}
使用@Service
注解来定义bean;
@Service
public class AccountServiceImpl implements AccountService {@Autowiredprivate AccountDao accountDao;public void save(Account account) {accountDao.save(account);}public void update(Account account){accountDao.update(account);}public void delete(Integer id) {accountDao.delete(id);}public Account findById(Integer id) {return accountDao.findById(id);}public List findAll() {return accountDao.findAll();}
}
用来填充 dataSource 数据源信息
即定义dataSource
这个 bean;
只要和数据库有关都需要!
dataSource的值从 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;@Beanpublic DataSource dataSource(){DruidDataSource ds = new DruidDataSource();ds.setDriverClassName(driver);ds.setUrl(url);ds.setUsername(userName);ds.setPassword(password);return ds;}
}
要@import
两个外部配置类:JDBC(datasource)和MyBatis;
SqlSessionFactoryBean
:
第一个bean用来获取SqlSessionFactory;
事务处理由JDBC提供了, 这里使用默认的就可以;
setTypeAliasesPackage是用来扫描类型别名的包;
需要注入dataSource的bean,也就是JdbcConfig定义的bean,这里从方法参数注入;
MapperScannerConfigurer
:
是用来扫描mapper映射文件,所以这里一个单独的bean,不是在SqlSessionFactoryBean中;
原mapper:
原dataSource:
使用配置类创造IOC容器;
只需获取service的bean再操作即可,dao的bean已经注入到service了(通过定义bean的方法参数注入);
结果:打印出查询信息
在上面基础上进行整合;
增加Junit包和Spring-test整合包:
一般都是测试业务层,测数据层的少;
新建测试业务层接口的测试类:
用@RunWith
设定类运行器:
SpringJunitClassRunner.class
是专用类运行器;
需要让类知道Spring的配置环境:
@ContextConfiguration(classes=Spring配置文件.class)
将要被测试的(被注入的bean)建立成员变量;
设置@Autowired
自动装配,让IOC容器中的bean自动注入;
测试方法用@Test
注释;
结果:打印查询信息
下一篇:【版本控制】Git快速上手