通过Mapper代理实现自定义接口
-
自定义接口,定义相关业务方法
-
编写与方法相对应的Mapper.xml
- 自定义接口
public interface AccountRepository {
public int save(Account account);
public int update(Account account);
public int deleteById(long id);
public List<Account> findAll();
public Account findByID(long id);
}
-
创建接口对应的Mapper.xml,定义对应接口方法的SQL语句
statement标签可根据SQL执行的业务选择insert、delete、update、select
MyBatis框架会根据规则自动创建接口实现类的代理对象
规则:
-
Mapper.xml中 namespace 为接口的全类名
-
Mapper.xml中 statement 中的 id 为接口对应的方法名
-
Mapper.xml中 statement 中的 parameterType 和接口中对应方法的参数类型一致
-
Mapper.xml中 statement 中的 resultType 和接口中对应方法的返回值类型一致
(添加修改删除的 statement 省略 resultType ,因为其返回类型一定是int)
(查询的 statement 中 resultType 直接写其集合中的泛型,而不要写集合)
编写 AccountRepository.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.mybatistest.repository.AccountRepository">
<insert id="save" parameterType="com.mybatistest.entity.Account">
insert into t_account(username,password,age) values(#{username},#{password},#{age})
</insert>
<update id="update" parameterType="com.mybatistest.entity.Account">
update t_account set username = #{username}, password = #{password}, age = #{age} where id = #{id}
</update>
<delete id="deleteById" parameterType="long">
delete from t_account where id = #{id}
</delete>
<select id="findAll" resultType="com.mybatistest.entity.Account">
select * from t_account
</select>
<select id="findById" parameterType="long" resultType="com.mybatistest.entity.Account">
select * from t_account where id = #{id}
</select>
</mapper>
- 在全局配置文件 config.xml 中注册AccountRepository.xml
<mappers>
<!--新增如下mapper-->
<mapper resource="com/mybatistest/repository/AccountRepository.xml"></mapper>
</mappers>
- 调用接口的代理对象完成相关的业务
public class Test2 {
public static void main(String[] args) {
//加载MyBatis配置文件
InputStream inputStream = Test2.class.getClassLoader().getResourceAsStream("config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取实现接口的代理对象
AccountRepository accountRepository = sqlSession.getMapper(AccountRepository.class);
/*
//添加对象
Account account = new Account(2L, "李四", "123456", 23);
accountRepository.save(account);
sqlSession.commit();
*/
/*
//查询全部对象
List<Account> list = accountRepository.findAll();
for (Account account1:list){
System.out.println(account1);
}
*/
//通过id查询对象
Account account2 = accountRepository.findById(2L);
System.out.println(account2);
//修改对象
account2.setUsername("王五");
account2.setPassword("000000");
account2.setAge(18);
int result = accountRepository.update(account2);
System.out.println(result);
sqlSession.commit();
//通过id删除对象
int result2 = accountRepository.deleteById(account2.getId());
System.out.println(result2);
sqlSession.commit();
sqlSession.close();
}
}