1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 <!-- 全局配置文件 --> 6 <configuration> 7 <environments default="development"> 8 <environment id="development"> 9 <transactionManager type="JDBC"/> 10 <dataSource type="POOLED"> 11 <property name="driver" value="com.mysql.jdbc.Driver"/> 12 <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8"/> 13 <property name="username" value="root"/> 14 <property name="password" value="root"/> 15 </dataSource> 16 </environment> 17 </environments> 18 19 <!-- 加载映射文件 --> 20 <mappers> 21 <mapper resource="EmployeeMapper1.xml"/> 22 <mapper resource="EmployeeMapper2.xml"/> 23 </mappers> 24 </configuration>
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper 3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 5 6 <!-- demo2 --> 7 <mapper namespace="com.demo2.EmployeeMapper"> 8 <!-- 9 mybatis 支持命名空间设置为 dao 接口 进行绑定 框架会自动对接口进行代理 不需要手动实例化 10 sql 唯一id与接口中的方法进行绑定 这里的接口只需要设定好方法的参数而不需要实例化 11 --> 12 <select id="getById" resultType="org.entity.Employee"> 13 select * from employee where id = #{id} 14 </select> 15 </mapper>
1 package demo2; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 6 import org.apache.ibatis.io.Resources; 7 import org.apache.ibatis.session.SqlSession; 8 import org.apache.ibatis.session.SqlSessionFactory; 9 import org.apache.ibatis.session.SqlSessionFactoryBuilder; 10 import entity.Employee; 11 12 public class Demo2 { 13 14 public static void main(String[] args) throws IOException { 15 // 1、获取sessionFactory 16 String resource = "mybatis-config.xml"; 17 InputStream inputStream = Resources.getResourceAsStream(resource); 18 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder() 19 .build(inputStream); 20 // 2、获取 session 21 SqlSession session = sqlSessionFactory.openSession(); 22 // 3、获取接口的是实现类对象 自动代理 23 EmployeeMapper mapper = session.getMapper(EmployeeMapper.class); 24 25 Employee employee = mapper.getById(1); 26 System.out.println(employee.toString()); 27 session.close(); 28 } 29 }