Springboot服务框架+MyBatis持久层+SqlSession

1,新建Maven项目,搭建Springboot服务框架+MyBatis持久层+druid连接池+MySQL数据库
2,新建一个Class类并将其交给容器管理

@Configuration
public class SqlSessionFactoryConfig {

	@Autowired
	DataSource dataSource;
	
	@Bean
	@Primary
	public SqlSessionFactory sqlSession() {
		SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
		try {
			sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));//设置对应的xml文件地址
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		sqlSessionFactoryBean.setDataSource(dataSource);
		SqlSessionFactory factory=null;
		try {
			factory = sqlSessionFactoryBean.getObject();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return factory;
	}
}

3,编写对应的xml文件

  


	

4,在Service中注入SqlSessionFactory,并获取SqlSession,调用其增删改查方法,输入参数

@Service
public class TestService {

	@Autowired
	SqlSessionFactory factory;

	public List queryStudentsLimite(int i) {
		String sqlid="com.a.test.dao.TestDao.queryStudentsLimite";//xml文件中的namespace+语句对应的ID
		SqlSession session=factory.openSession();
		List list=session.selectList(sqlid, i);
		return list;
	}
	
}

5,在控制器组件中进行调用

	@RequestMapping("limite")
	@ResponseBody
	public List test4(Integer count){
		return testService.queryStudentsLimite(count);
	}

6,在浏览器中进行检验
7,代码地址

你可能感兴趣的:(MyBatis持久层,SqlSession,Springboot框架)