Spring整合

2023-08-09 19:09:05 浏览数 (1)

一、MyBatis核心对象分析

其中最关键的对象为SqlSessionFactory对象

二、整合

1. 整合MyBatis

导入pom.xml坐标(Spring整合MyBatis的两个关键坐标)

代码语言:javascript复制
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>6.0.4</version>
</dependency>
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.0</version>
</dependency>

Spring配置类

代码语言:javascript复制
@Configuration
@ComponentScan("com.cikian")
@PropertySource({"classpath:jdbc.properties"};)
@Import({JdbcConfig.class, MyBatisConfig.class};)
public class SpringConfig {
};

配置数据源

代码语言:javascript复制
public class JdbcConfig {
    @Value("${jdbc.driver};")
    private String driverClassName;
    @Value("${jdbc.url};")
    private String url;
    @Value("${jdbc.username};")
    private String username;
    @Value("${jdbc.password};")
    private String password;

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    };
};

MyBatis配置类

代码语言:javascript复制
public class MyBatisConfig {
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
        ssfb.setTypeAliasesPackage("com.cikian.domain");
        ssfb.setDataSource(dataSource);
        return ssfb;
    };

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.cikian.dao");
        return msc;
    };
};

开发使用

代码语言:javascript复制
public class Main {
    public static void main(String[] args) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
        AccountService accountService = ctx.getBean(AccountService.class);
        Account account = accountService.findById(1);
        System.out.println(account);
    };
};

2. 整合JUnit

导入两个关键坐标

代码语言:javascript复制
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>6.0.4</version>
</dependency>

测试

代码语言:javascript复制
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class AccountServiceTest {
    @Autowired
    private AccountService accountService;

    @Test
    public void testFindById() {
        System.out.println(accountService.findById(2));
    };

    @Test
    public void testFindAll() {
        System.out.println(accountService.findAll());
    };
};

0 人点赞