MyBatis笔记——Mapper动态代理

时间:2024-08-29 08:05:37

前提概要

Mapper接口开发方法只需要程序员编写Mapper接口(相当于Dao接口),由Mybatis框架根据接口定义创建接口的动态代理对象,代理对象的方法体同上边Dao接口实现类方法。

Mapper接口开发需要遵循以下规范:

1.Mapper.xml文件中的namespace与mapper接口的类路径相同。
2.Mapper接口方法名和Mapper.xml中定义的每个statement的id相同
3.Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql 的parameterType的类型相同
4.Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同

下面是实例介绍。


1.环境配置

工程目录结构如下
MyBatis笔记——Mapper动态代理

SqlMapConfig.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="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/db_pwc" />
<property name="username" value="pwc" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/pwc/dao/mapper/UserMapper.xml" />
</mappers>
</configuration>

2.Mapper映射接口(UserMapper.java)和Mapper映射表(UserMapper.xml)

UserMapper.java

package com.pwc.dao.mapper;

import java.util.List;

import com.pwc.pojo.User;

public interface UserMapper {

    public User findById(int id);
public void deleteById(int id);
public void insert(User user);
public List<User> findByAge(int age); }

UserMapper.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">
<mapper namespace="com.pwc.dao.mapper.UserMapper">
<select id="findById" parameterType="int" resultType="com.pwc.pojo.User">
SELECT * FROM User WHERE id = #{id}
</select> <insert id="insert" parameterType="com.pwc.pojo.User">
INSERT INTO User(name,age) VALUES(#{name},#{age})
</insert> <delete id="deleteById" parameterType="int">
DELETE * FROM User WHERE id=#{id} </delete> <select id="findByAge" parameterType="int" resultType="com.pwc.pojo.User">
SELECT * FROM User WHERE age=#{age}
</select> </mapper>

3.测试

测试类

package com.pwc.test;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.pwc.dao.mapper.UserMapper;
import com.pwc.pojo.User; public class Test { public static void main(String[] args) { SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
SqlSessionFactory factory=builder.build(Test.class.getClassLoader().getResourceAsStream("SqlMapConfig.xml"));
SqlSession session = factory.openSession(); UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.findById(1);
session.close();
System.out.println(user); } }

测试结果如下
User [id=1, name=pwc, age=18]

版权声明:本文为博主原创文章,未经博主允许不得转载。