版权声明:本文为博主原创文章,转载请标明出处。 https://blog.csdn.net/weixin_43014205/article/details/86155276
1.对应的书写SQL语句的xml文件中的nameapsce必须为接口的全路径
2.接口中的方法名称必须和xml中对应的ID相同
3.xml中的parameterType必须和接口中的参数类型一致 当传递多个参数时parameterType可以省略不写
4.xml中的ResultType必须和接口中的返回值类型一致
例如:对于一个客户表 实现其CRUD
其Customer.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.bullet.mapper.CustomerMapper">
<!--根据cust_id查询客户-->
<select id="queryCustomerById" parameterType="Int" resultType="com.bullet.domain.Customer">
SELECT * FROM `customer` WHERE cust_id = #{cust_id}
</select>
<!--查询所有用户-->
<select id="queryAll" resultType="com.bullet.domain.Customer">
SELECT * FROM `customer`
</select>
<!--根据用户名模糊查询用户-->
<select id="queryCustomerByName" parameterType="String" resultType="com.bullet.domain.Customer">
SELECT * FROM `customer` where cust_name like #{value};
</select>
<!--添加客户-->
<insert id="insertCustomer" parameterType="com.bullet.domain.Customer">
<!--获取插入的最后一条id-->
<!--keyColumn 哪一列是ID
keyProperty 要把id给哪个属性
resultType id是什么类型
order 是插入之前获得id还是插入之后获得id
-->
<selectKey keyColumn="cust_id" keyProperty="cust_id" resultType="Integer" order="AFTER">
select last_insert_id()
</selectKey>
insert into `customer` (cust_name,cust_profession,cust_phone,email)
values (#{cust_name},#{cust_profession},#{cust_phone},#{email})
</insert>
<!--更新-->
<update id="updateCustomer" keyProperty="com.bullet.domain.Customer">
update `customer` set cust_name=#{cust_name} where cust_id=#{cust_id}
</update>
<!--删除-->
<delete id="deleteCustomer" parameterType="com.bullet.domain.Customer">
delete from `customer` where cust_id=#{cust_id}
</delete>
</mapper>
则其对应的接口为:
public interface CustomerMapper {
//根据id查询客户
public Customer queryCustomerById(Integer id);
//查询所有
public List<Customer> queryAll();
//根据用户名模糊查询
public List<Customer> queryCustomerByName(String name);
//添加
public void insertCustomer(Customer customer);
//更新
public void updateCustomer(Customer customer);
//删除操作
public void deleteCustomer(Customer customer);
}
这样便可以实现其动态代理
动态代理的调用:
public void test2(){
SqlSession sqlSession = MyBatisUtils.openSession();
CustomerMapper mapper = sqlSession.getMapper(CustomerMapper.class);
Customer customer = mapper.queryCustomerById(1);
System.out.println(customer);
List<Customer> customers = mapper.queryAll();
for (Customer customer1 : customers) {
System.out.println(customer1);
}
List<Customer> customers1 = mapper.queryCustomerByName("%李%");
for (Customer customer1 : customers1) {
System.out.println(customer1);
}
sqlSession.close();
}