Mapper动态代理需要遵循以下规范:
- 接口的全路径和映射文件中mapper标签namespace保持一致
- 接口的方法名和映射文件的statementId保持一致
- 接口方法的参数类型和映射文件的parameterType保持一致,返回类型和映射文件的resultType保持一致
- 接口名称和映射文件的名称保持一致
- 接口和映射文件放在一起
sqlMapconfig.xml配置文件 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 <configuration> 6 <environments default="development"> 7 <environment id="development"> 8 <!-- 使用jdbc事务管理--> 9 <transactionManager type="JDBC" /> 10 <!-- 数据库连接池--> 11 <dataSource type="POOLED"> 12 <property name="driver" value="数据库驱动" /> 13 <property name="url" value="链接地址" /> 14 <property name="username" value="用户名" /> 15 <property name="password" value="密码" /> 16 </dataSource> 17 </environment> 18 </environments>
19 <mappers> 20 <!-- 此种方法要求mapper接口名称和mapper映射文件名称相同,且放在同一个目录中。--> 21 <mapper class="mapper.mapperDao"></mapper> 22 <!-- 注册指定包下的所有mapper接口 23 此种方法要求mapper接口名称和mapper映射文件名称相同,且放在同一个目录中 24 --> 25 <package name="包全路径名"/> 26 </mappers> 27 </configuration>
mapper.xml映射文件
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 <!--namespace和接口全路径名保持一致--> 6 <mapper namespace="mapper.mapperDao"> 7 <select id="findAll" parameterType="int" resultType="commodity.commodity"> 8 select * from commodity where id=#{id} 9 </select> 10 </mapper>
pojo类:
1 public class commodity { 2 private int id; 3 private String name; 4 private int price; 5 6 @Override 7 public String toString() { 8 return "commodity{" + 9 "id=" + id + 10 ", name=‘" + name + ‘\‘‘ + 11 ", price=" + price + 12 ‘}‘; 13 } 14 15 public int getId() { 16 return id; 17 } 18 19 public void setId(int id) { 20 this.id = id; 21 } 22 23 public String getName() { 24 return name; 25 } 26 27 public void setName(String name) { 28 this.name = name; 29 } 30 31 public int getPrice() { 32 return price; 33 } 34 35 public void setPrice(int price) { 36 this.price = price; 37 } 38 }
接口:
1 import commodity.commodity; 2 3 public interface mapperDao { 4 public commodity findAll(int id); 5 public void insert(); 6 }
测试:
1 public void Test() throws IOException { 2 SqlSessionFactoryBuilder sqlSessionFactoryBuilder=new SqlSessionFactoryBuilder(); 3 SqlSessionFactory sqlSessionFactory=sqlSessionFactoryBuilder.build(Resources.getResourceAsStream("sqlMapconfig.xml")); 4 //通过sqlSession获取sqlSession对象 5 SqlSession sqlSession=sqlSessionFactory.openSession(); 6 //获取代理对象 7 mapperDao mapperDao=sqlSession.getMapper(mapper.mapperDao.class); 8 commodity commodity= mapperDao.findAll(1); 9 System.out.println(commodity); 10 }