Spring整合Mybatis注解方式

liqiancao 2020-07-26

Spring整合Mybatis(注解方式)

目录

环境准备

jar包:

  • Spring所需依赖:spring-context、spring-aspects、aspectjrt、aspectjweaver、spring-tx、spring-jdbc
  • mybatis所需要:mybatis、mybatis-spring、mysql-connector-java、(druid、c3p0、HikariCP)
  • 辅助性依赖:logback-classic、lombok、spring-test、junit、mapper(可选)、pagehelper(可选)

数据库:mysql

服务层代码

@Service
@Data
public class UserService implements IUserService {

    private SqlSessionTemplate sqlSession;
    private UserMapper mapper;

    public UserService(SqlSessionTemplate sqlSession){
        this.sqlSession=sqlSession;
        mapper=sqlSession.getMapper(UserMapper.class);
    }

    @Override
    public List<User> getAll() {
        return mapper.getAll();
    }
}

mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hello.mapper.UserMapper">

    <select id="getAll" resultType="user">
        select * from user
    </select>

</mapper>

纯注解方式

纯注解方式需要一个配置类来代替xml配置文件的作用,需在配置文件上注

//注解扫描
@ComponentScan(basePackages = "com.hello")
//声明当前类为配置类
@Configuration

配置类中@Bean相当于xml的标签

通过@Bean将类放入spring容器,也可以通过注解扫描

配置类具体内容

@ComponentScan(basePackages = "com.hello")
@Configuration
public class Config {

    //配置数据库连接池
    @Bean
    public DataSource dataSource(){
    	//使用HikariCP连接池
        HikariDataSource hikariDataSource = new HikariDataSource();
        //配置连接池的jdbcUrl属性
        hikariDataSource.setJdbcUrl("jdbc:mysql://localhost:3306/ssm?servexrTimezone=GMT%2B8");
        //账号
        hikariDataSource.setUsername("root");
        //密码
        hikariDataSource.setPassword("root");
        //驱动Driver
        hikariDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        return hikariDataSource;
    }

    //配置sqlSessionFactory
    @Bean
    public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
    	//在spring和Mybatis整合中采用mybatis提供的SQLSessionFactoryBean对象
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        //为sqlSessionFatoryBean设置连接池属性
        sqlSessionFactoryBean.setDataSource(dataSource());
        //获取PathMatchingResourcePatternResolver对象为扫描mapper文件做准备
        PathMatchingResourcePatternResolver path = new PathMatchingResourcePatternResolver();
		//设置mapper文件位置        
 sqlSessionFactoryBean.setMapperLocations(path.getResources("classpath*:com/hello/mapper/**/*.xml"));
 		//为javaBean对象设置别名
        sqlSessionFactoryBean.setTypeAliasesPackage("com.hello.bean");
        //返回SqlSessionFactory对象
       return  sqlSessionFactoryBean.getObject();
    }

    //配置sqlSession
    @Bean
    public SqlSessionTemplate sqlSessionTemplate() throws Exception {
    //将SqlSessionFactory作为参数传入构造方法
        SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactoryBean());
        return sqlSessionTemplate;
    }

    @Bean
    public UserService userService() throws Exception {
        UserService userService = new UserService(sqlSessionTemplate());
        return userService;
    }
}

测试类具体内容

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {Config.class})
public class AppTest 
{
    @Autowired
    public UserService userService;
    @Test
    public void getALL(){
        List<User> users = userService.getAll();
        for (User user:users) {
            System.out.println(user);
        }
    }
}

相关推荐