Springboot+MyBatis——SqlSession 骑猪看日落 2022-04-24 07:16 418阅读 0赞 1,[新建Maven项目,搭建Springboot服务框架+MyBatis持久层+druid连接池+MySQL数据库][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文件 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd"> <mapper namespace="com.a.test.dao.TestDao"> <select id="queryStudentsLimite" resultType="java.util.Map"> select * from studentinfo limit #{i,jdbcType=INTEGER} </select> </mapper> 4,在Service中注入SqlSessionFactory,并获取SqlSession,调用其增删改查方法,输入参数 @Service public class TestService { @Autowired SqlSessionFactory factory; public List<Map> queryStudentsLimite(int i) { String sqlid="com.a.test.dao.TestDao.queryStudentsLimite";//xml文件中的namespace+语句对应的ID SqlSession session=factory.openSession(); List<Map> list=session.selectList(sqlid, i); return list; } } 5,在控制器组件中进行调用 @RequestMapping("limite") @ResponseBody public List<Map> test4(Integer count){ return testService.queryStudentsLimite(count); } 6,[在浏览器中进行检验][Link 1] 7,[代码地址][Link 2] [Maven_Springboot_MyBatis_druid_MySQL]: https://blog.csdn.net/weixin_40429030/article/details/89377506 [Link 1]: http://localhost:8080/limite?count=5 [Link 2]: https://download.csdn.net/download/weixin_40429030/11141244
还没有评论,来说两句吧...