朝花夕拾之ORM-MyBatis

继上文配置好Spring WebMVC+Spring Framework,继续添加ORM-MyBatis。

pom.xml
        
            org.mybatis
            mybatis-spring
            1.3.0
        
        
            org.mybatis
            mybatis
            3.4.1
        
        
            org.springframework
            spring-jdbc
            4.3.3.RELEASE
        
        
            mysql
            mysql-connector-java
            5.1.37
        
        
            commons-dbcp
            commons-dbcp
            1.4
        

添加以上库。
配置步骤如下(java config)

  1. 封装DataSource, SqlSessionFactoryBean,SqlSession成bean
  2. 设置MapperScan
  3. 写Mapper;
  4. 实现
1,2 封装、MapperScan

MyBatisConfig.java

@Configuration
@MapperScan("jufou.info.mapper")
public class MyBatisConfig {
    @Bean
    public DataSource dataSource(){
        BasicDataSource basicDataSource=new BasicDataSource();
        basicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        basicDataSource.setUsername("root");
        basicDataSource.setPassword("password");
        basicDataSource.setUrl("jdbc:mysql://localhost:3306/test");
        return basicDataSource;
    }
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(){
        SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath*:/jufou/info/mybatis/mappers.xml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sqlSessionFactoryBean;
    }
    @Bean
    public SqlSession sqlSession(){
        SqlSessionTemplate sqlSessionTemplate= null;
        try {
            sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactoryBean().getObject());
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            return sqlSessionTemplate;
        }
    }
}
3,4 Mapper与实现
public interface UserMapper {
    @Select("select * from user where uid=#{id}")
    public User findById(int id);

}
@Component
@Scope(scopeName="singleton")
public class UserService implements UserServiceImpl {
    @Resource(name="sqlSession")
    private SqlSession sqlSession;
    public UserService(){

    }
    public String getUserNickname() {
        User user=sqlSession.selectOne("jufou.info.mapper.UserMapper.findById", 1);
        System.out.println(user.getUid() + "--" + user.getName() + "--");
        return "Hello";
    }
}

也可以写成xml配置放在mappers.xml内。

至此Java config 版本的SSM配置完成。

你可能感兴趣的:(朝花夕拾之ORM-MyBatis)