Mybatis之 Mapper接口方式的开发整合

1.简介

Mybatis之 Mapper接口方式的开发整合_第1张图片Mybatis之 Mapper接口方式的开发整合_第2张图片

Mybatis之 Mapper接口方式的开发整合_第3张图片

2.代码实例

Mapper代理开发的规范
1.Mapper接口的名称和对应的Mapper.xml映射文件的名称必须一致
2.Mapper.xml文件的namespace与Mapper接口的类路径相同(即接口文件和映射文件必须放在同一个包中)
3.Mapper接口中的方法名和Mapper.xml中定义的每个执行语句的id相同
4.Mapper接口中方法的输入参数类型和Mapper.xml中定义的每个sql的parameterType类型相同
5.Mapper接口方法的输出参数类型要和Mapper.xml中每个sql中定义的resultType的类型相同


Customer 实体类

package com.lin.po;

/**
 * 客户持久化类
 */
public class Customer {

	private Integer id;
	private String username;
	private String jobs;
	private String phone;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getJobs() {
		return jobs;
	}

	public void setJobs(String jobs) {
		this.jobs = jobs;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	@Override
	public String toString() {
		return "Customer [id=" + id + ", username=" + username + ", jobs=" + jobs + ", phone=" + phone + "]";
	}

}

CustomerMapper 接口

package com.lin.mapper;

import com.lin.po.Customer;

public interface CustomerMapper {
	//通过id查询客户
	public Customer findCustomerById(Integer id);
}

CustomerMapper.xml文件



  
  
  
  
<mapper namespace="com.lin.mapper.CustomerMapper">
	
	<select id="findCustomerById" parameterType="Integer" resultType="customer">
			select * from t_customer where id=#{id};	
	select>
	
mapper>

在applicationContext.xml配置 Mapper代理开发(基于MapperFactoryBean


	
	<bean id="customerMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
		<property name="mapperInterface" value="com.lin.mapper.CustomerMapper">property>
			
		<property name="sqlSessionFactory" ref="sqlSessionFactory">property>
	bean>

添加依赖


	<mappers>
		<mapper resource="com/lin/po/CustomerMapper.xml"/>
		<mapper resource="com/lin/mapper/CustomerMapper.xml"/>
	mappers>

单元测试

@Test
	public void findCustomerByIdTest2() {
		//加载配置文件
		ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
		CustomerMapper customerMapper=	applicationContext.getBean(CustomerMapper.class);
		Customer customer=customerMapper.findCustomerById(1);
		System.out.println(customer);
	}

测试结果

DEBUG [main] - ==>  Preparing: select * from t_customer where id=?; 
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <==      Total: 1
Customer [id=1, username=joy, jobs=doctor, phone=13778888666]

你可能感兴趣的:(JAVA,EE企业级实战)