1.简介
2.代码演示
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.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">
<!-- namespace表示命名空间 -->
<mapper namespace="com.lin.po.CustomerMapper">
<!-- 根据id查询客户信息 -->
<select id="findCustomerById" parameterType="Integer" resultType="customer">
select * from t_customer where id=#{id};
</select>
</mapper>
CustomerDao类
package com.lin.dao;
import com.lin.po.Customer;
public interface CustomerDao {
//通过id查询客户
public Customer findCustomerById(Integer id);
}
实现层
package com.lin.dao.impl;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import com.lin.dao.CustomerDao;
import com.lin.po.Customer;
public class CustomerImpl extends SqlSessionDaoSupport implements CustomerDao {
//通过id查询客户
@Override
public Customer findCustomerById(Integer id) {
// TODO Auto-generated method stub
return this.getSqlSession().selectOne("com.lin.po.CustomerMapper.findCustomerById", id);
}
}
在applicationContext.xml核心配置文件中加入实例化Dao
<!-- 实例化Dao -->
<bean id="customerDao" class="com.lin.dao.impl.CustomerImpl">
<!--注入sqlSessionFactory 对象实例 -->
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
在mybatis-config.xml中指定Mapper位置
<!--2.配置Mapper的位置 -->
<mappers>
<mapper resource="com/lin/po/CustomerMapper.xml"/>
</mappers>
单元测试
@Test
public void findCustomerByIdTest() {
//加载配置文件
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
//根据容器中的Bean的Id来获取指定的Bean
CustomerDao customerDao=(CustomerDao) applicationContext.getBean("customerDao");
//获取Bean的另一种方式
CustomerDao customerDao2=applicationContext.getBean(CustomerDao.class);
//执行方法
Customer customer= customerDao.findCustomerById(1);
Customer customer2= customerDao2.findCustomerById(2);
System.out.println(customer);
System.out.println(customer2);
}
运行结果:
使用了两种方法
DEBUG [main] - ==> Preparing: select * from t_customer where id=?;
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <== Total: 1
DEBUG [main] - ==> Preparing: select * from t_customer where id=?;
DEBUG [main] - ==> Parameters: 2(Integer)
DEBUG [main] - <== Total: 1
Customer [id=1, username=joy, jobs=doctor, phone=13778888666]
Customer [id=2, username=Tom, jobs=teacher, phone=1377888886]