简体   繁体   中英

With MyBatis, how can I build an SqlSessionFactory without writing a configuration file (i.e. programmatically)?

I am trying to write a unit test for a DAO implemented using MyBatis using annotations. I would like to instantiate that DAO to unit test against my (in-memory) database. However, the only way I see to instantiate it is through a SqlSessionFactory and the only way I see to see instantiate one of those is by using a SqlSessionFactoryBuilder only of whose methods that a configuration file.

However, in my unit test I already have a connection to the in-memory database can I just use that to somehow instantiate the mapper? That would also allow me to mock or spy the Connection later if I needed to for a test.

The SqlSessionFactory class has a openSession(Connection connection) method. You can use it to retrieve a SqlSession using the Connection you have to your in memory db.

You can build a SqlSessionFactory programmatically without using a configuration file with the following code:

Environment environment = new Environment("ID", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.addMappers(mappersPackageName);
// Other configuration tweaks
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(configuration);

Then you can mock or stub the DataSource to return your desired Connection instance.

Use junit for testing this. Check out this link for more info

The setup() method would be the correct point in this case to create a SqlSessionFactory object

 @BeforeClass
 public static void setUp() throws Exception {
  log.info("starting up myBatis tests");
  String resource = "mybatis.config.xml";
  Reader reader = Resources.getResourceAsReader(resource); 
  sf = new SqlSessionFactoryBuilder().build(reader,"testing");
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM