- 搭建环境
- 依赖maven创建项目,并将此项目作为父项目导入依赖的jar包
- 依据父项目,创建模板,在resources下创建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"> <!--核心配置文件 sqlconfig--> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/jdbc?useSSL=true&useUniode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="
<mappers>
<mapper resource="./UserMapper.xml"/>
</mappers>"/> </mappers> </configuration>
- 创建一个工具类用于获取SqlSession对象
package com.neusoft.utils; 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.InputStream; //工具类 创建SqlSession工厂 生产SqlSession public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static{ try { // 使用mybatis获取SqlSessionFactory对象 String resource="mybatis-config.xml"; InputStream inputStream = null; inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (Exception e) { e.printStackTrace(); } } // 获取一个sqlsession对象,用于操作数据库 public static SqlSession getsqlsession(){ return sqlSessionFactory.openSession(); } }
- 创建操作数据的接口dao
public interface UserDao { List<User> getUserList(); }
- 编写对应的mapper.xml文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- namespace绑定一个对应的dao/mapper接口--> <mapper namespace="com.neusoft.dao.UserDao"> <select id="getUserList" resultType="com.neusoft.entity.User"> select * from users </select> </mapper>
- 编写测试类
package com.neusoft.dao; import com.neusoft.entity.User; import com.neusoft.utils.MybatisUtils; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import java.util.List; public class UserDaoTest { @Test public void test(){ SqlSession sqlsession= MybatisUtils.getsqlsession(); UserDao mapper= sqlsession.getMapper(UserDao.class); List<User> list= mapper.getUserList(); for (User u:list){ System.out.println(u); } } }
- 注意点
- namespace的重要性:必须配置namespace,否则xml文件中标签中的操作语句将没有入口,就无法自动映射进对应接口的抽象方法