1.创建 springboot+mybatis 应用
2.pom 文件的编写,需要配置相关数据库连接
3.配置 mybatis-config 文件
4.配置 datasource
@Configuration // 配置 mybatis mapper 的扫描路径 @MapperScan("com.qinmei.demo.dao") public class DataSourceConfiguration { @Value("${jdbc.driver}") private String jdbcDriver; @Value("${jdbc.url}") private String jdbcUrl; @Value("${jdbc.username}") private String jdbcPassword; @Value("${jdbc.password}") private String jdbcUsername; @Bean(name = "dataSource") public ComboPooledDataSource createDataSource() throws PropertyVetoException { // 数据库连接池的配置 ComboPooledDataSource dataSource = new ComboPooledDataSource(); dataSource.setDriverClass(jdbcDriver); dataSource.setJdbcUrl(jdbcUrl); dataSource.setUser(jdbcUsername); dataSource.setPassword(jdbcPassword); // 关闭连接后不自动 commit提交 dataSource.setAutoCommitOnClose(false); return dataSource; } }5.配置 sessionFactory
@Configuration public class SessionFactoryConfiguration { // mybatis-config.xml 配置文件的路径 @Value("${mybatis_config_file}") private String mybatisConfigFilePath; // mybatis mapper 文件所在路径 @Value("${mapper_path}") private String mapperPath; // 实体类所在的 package @Value("${entity_package}") private String entityPackage; @Autowired //按照名称加载 datasource @Qualifier("dataSource") private DataSource dataSource; @Bean(name = "sqlSessionFactory") public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException { // 创建 sqlSession 工厂 SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFilePath)); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); // mapper 文件存放的位置 String packageSearchPath = PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperPath; // 设置属性 sqlSessionFactoryBean.setMapperLocations(resolver.getResources(packageSearchPath)); sqlSessionFactoryBean.setDataSource(dataSource); sqlSessionFactoryBean.setTypeAliasesPackage(entityPackage); return sqlSessionFactoryBean; } }6.配置文件
server.port=80 server.context-path=/demo # 数据库连接 jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/demo jdbc.username=root jdbc.password=root #Mybatis mybatis_config_file=mybatis-config.xml mapper_path=/mapper/**.xml entity_package=com.qinmei.demo.entity7.dao层编写接口
8.dao 层 mapper 编写
9.dao 层测试
测试自动注入时会报错,找不到实例,修改 idea 配置即可
网友评论