SpringBoot中间件—ORM(Mybatis)框架实现
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Properties;
@SpringBootApplication
@MapperScan("com.example.mapper") // 扫描Mapper接口所在的包
public class Application {
@Bean
public DataSource dataSource() throws SQLException {
// 配置数据源,这里仅示例,具体配置需要根据实际情况
return DataSourceBuilder.create().build();
}
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
// 设置MyBatis的配置文件
sessionFactory.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
// 设置mapper.xml文件的位置
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*.xml"));
return sessionFactory.getObject();
}
@Bean
public TransactionManager transactionManager(DataSource dataSource) throws SQLException {
return new DataSourceTransactionManager(dataSource);
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Configuration
public class MyBatisConfig {
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
// 设置MyBatis配置文件
sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
// 设置mapper.xml文件的位置
PathMatchingResourcePatternResolver res
评论已关闭