MyBatis Environment Setup
In this article, I am going to share how to create the environment set up for Mybatis and creating a small example demo as well.
A significant difference between iBATIS and other persistence frameworks such as Hibernate is that iBATIS emphasizes the use of SQL, while other frameworks typically use a custom query language such has the Hibernate Query Language (HQL)
1. Create a Maven project. (Maven will have advantage on managing external jars needed)
In the pom.xml file add below dependencies.
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.8</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.5</version> </dependency>
As could see, Maven has downloaded the needed jars for us.
2. database.properties
driver = com.mysql.jdbc.Driver url = jdbc:mysql://localhost:3306/sakila?useUnicode=true&characterEncoding=utf8 username = root password = 3792354
3. mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> </configuration>
4. Test the connection.
import java.io.IOException; import java.io.InputStream; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class TestMain { public static void main(String args[]) { //System.out.println("开始做mybatis"); InputStream inputStream = null; try { inputStream = Resources.getResourceAsStream("mybatis-config.xml"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } /* * 创建工厂 */ SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); /* * 打开ssion */ SqlSession sqlSession = sqlSessionFactory.openSession(); System.out.println(sqlSession); sqlSession.close(); try { inputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Output:
The connection test is fine.
we are able to proceed with further development related to Mybatis