1、在IDEA中创建Maven项目
Maven pom.xml
4.0.0 com.xiaobai MyBatis_Maven 1.0-SNAPSHOT war MyBatis_Maven Maven Webapp http://www.example.com UTF-8 1.7 1.7 org.mybatis mybatis 3.4.6 org.mariadb.jdbc mariadb-java-client 2.3.0 junit junit 4.11 MyBatis_Maven maven-clean-plugin 3.0.0 maven-resources-plugin 3.0.2 maven-compiler-plugin 3.7.0 maven-surefire-plugin 2.20.1 maven-war-plugin 3.2.0 maven-install-plugin 2.5.2 maven-deploy-plugin 2.8.2
2、创建数据库
use test;drop table if exists person;create table person( bId int primary key auto_increment, bName varchar(10) not null)default charset = utf8;
3、添加MyBatis配置文件
mybatis-config.xml文件内容如下:
jdbc.properties 文件内容如下:
driver = org.mariadb.jdbc.Driverurl = jdbc:mariadb://localhost:3306/testusername = rootpassword = Qi1007..
解释
4、定义操作Person表的映射文件
在resources目录下创建sql映射文件,在目录中创建一个PersonMapper.xml文件,如下图所示:
PersonMapper.xml文件内容如下:
解释:
5、编写数据访问层
package com.xiaobai.mybatis.dao;import com.xiaobai.mybatis.entiy.Person;public interface PersonDAO{
Person selectOne(int bId);
}
6、编写单元测试类检查代码
package com;import com.xiaobai.dao.InvoiceDAO;import com.xiaobai.dao.PersonDAO;import com.xiaobai.entity.InvoiceEntity;import com.xiaobai.entity.Person;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import java.io.IOException;import java.io.Reader;public class App { public static void main(String[] args) throws IOException { Reader reader = Resources.getResourceAsReader("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession session = sqlSessionFactory.openSession(); PersonDAO personDAO = session.getMapper(PersonDAO.class); System.out.println(personDAO.selectOne(1));// InvoiceDAO invoiceDAO = session.getMapper(InvoiceDAO.class);// System.out.println(invoiceDAO.selectAll(1));// InvoiceEntity invoiceEntity = session.selectOne("com.xiaobai.dao.InvoiceDAO.selectOne",1);// System.out.println(invoiceEntity); }}
结果: