|
1 | 1 | package com.baeldung.mybatis.utils;
|
| 2 | + |
| 3 | +import com.baeldung.mybatis.mapper.AddressMapper; |
| 4 | +import com.baeldung.mybatis.mapper.PersonMapper; |
| 5 | +import org.apache.ibatis.datasource.pooled.PooledDataSource; |
2 | 6 | import org.apache.ibatis.io.Resources;
|
3 | 7 | import org.apache.ibatis.jdbc.SQL;
|
| 8 | +import org.apache.ibatis.mapping.Environment; |
| 9 | +import org.apache.ibatis.session.Configuration; |
4 | 10 | import org.apache.ibatis.session.SqlSessionFactory;
|
5 | 11 | import org.apache.ibatis.session.SqlSessionFactoryBuilder;
|
| 12 | +import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory; |
6 | 13 |
|
| 14 | +import javax.sql.DataSource; |
7 | 15 | import java.io.IOException;
|
8 | 16 | import java.io.InputStream;
|
9 | 17 |
|
10 | 18 | public class MyBatisUtil {
|
| 19 | + public static final String DRIVER = "org.apache.derby.jdbc.EmbeddedDriver"; |
| 20 | + public static final String URL = "jdbc:derby:testdb1;create=true"; |
| 21 | + public static final String USERNAME = "sa"; |
| 22 | + public static final String PASSWORD = "pass123"; |
11 | 23 | private static SqlSessionFactory sqlSessionFactory;
|
12 |
| - static { |
13 |
| - String resource = "mybatis-config.xml"; |
14 |
| - InputStream inputStream; |
15 |
| - try { |
16 |
| - inputStream = Resources.getResourceAsStream(resource); |
17 |
| - sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); |
18 |
| - } catch (IOException e) { |
19 |
| - e.printStackTrace(); |
20 |
| - } |
| 24 | + |
| 25 | + public static SqlSessionFactory buildqlSessionFactory(){ |
| 26 | + DataSource dataSource=new PooledDataSource(DRIVER, URL, USERNAME, PASSWORD); |
| 27 | + Environment environment=new Environment("Development",new JdbcTransactionFactory(),dataSource); |
| 28 | + Configuration configuration = new Configuration(environment); |
| 29 | + configuration.addMapper(PersonMapper.class); |
| 30 | + configuration.addMapper(AddressMapper.class); |
| 31 | + SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); |
| 32 | + SqlSessionFactory factory = builder.build(configuration); |
| 33 | + return factory; |
| 34 | + |
21 | 35 | }
|
| 36 | + |
22 | 37 | public static SqlSessionFactory getSqlSessionFactory(){
|
23 | 38 | return sqlSessionFactory;
|
24 | 39 | }
|
|
0 commit comments