1. 程式人生 > 實用技巧 >配置Mybatis(使用IDEA)

配置Mybatis(使用IDEA)

一、配置Mybatis

第一步:在pom.xml中匯入相關依賴

<!-- Mybatis框架 -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.0</version>
</dependency>
<!-- MyBatis整合Spring -->
<dependency>
    <groupId>org.mybatis</
groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.1</version> </dependency> <!-- Spring JDBC依賴,必須與其它Spring依賴使用完全相同的版本 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId>
<version>5.2.2.RELEASE</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.25</version> </dependency>

第二步:建立在resources資料夾下建立jdbc.properties並配置連線資料庫的配置

db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/mysql?characterEncoding=utf8
&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true db.username=root db.password=root db.maxActive=10 db.initialSize=2

第三步:編寫Mybatis的配置檔案

@PropertySource("classpath:jdbc.properties")
public class MyBatisConfig {
    @Bean
    public DataSource dataSource(
            @Value("${db.driver}") String driver,
            @Value("${db.url}") String url,
            @Value("${db.username}") String username,
            @Value("${db.password}") String password,
            @Value("${db.maxActive}") int maxActive,
            @Value("${db.initialSize}") int initialSize) {
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        ds.setMaxActive(maxActive);
        ds.setInitialSize(initialSize);
        return ds;
    }
}

二、測試,檢視Mybatis配置類是否配置成功

public class TestConfig {
    AnnotationConfigApplicationContext ctx;
    @Before
    public void berfore(){
        ctx = new AnnotationConfigApplicationContext(Mybaits_Config.class);
        System.out.println("測試開始");
    }

    @Test
    public void mybatisConfig_Test_DataSource() throws SQLException{
        DataSource ds = ctx.getBean(
                "dataSource",DataSource.class);
        String sql = "select username from vrduser where id=1";   //檢視資料庫vrduser中id=1的username的資料
        try(Connection connection = ds.getConnection()){
            Statement statement = connection.createStatement();
            ResultSet rs = statement.executeQuery(sql);
            while (rs.next()){
                System.out.println(rs.getString(1));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @After
    public void after(){
        System.out.println("測試結束");
        ctx.close();
    }
}

測試成功並輸出

測試開始
admin
測試結束