MyBatis-Spring连接
Mybatis-Spring
1.准备JAR包
2.编写配置文件
在类路径下建立下面几个文件
# db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=
jdbc.maxTotal=30
jdbc.maxIdle=10
jdbc.initialSize=5
3.Mapper接口整合
1.编写Mapper文件和Mapper接口
// CustomerMapper.java
public interface CustomerMapper {
public Customer findCustomerById(Integer id);
}
2.主配置文件中添加映射文件
3.将接口包装为MapperFactoryBean
class="org.mybatis.spring.mapper.MapperFactoryBean">
MapperFactoryBean会根据传过来的接口,生成对应的类
4.测试
@Test
public void findCustomerByIdMapperTest(){
ApplicationContext act =
new ClassPathXmlApplicationContext("applicationContext.xml");
CustomerMapper customerMapper = act.getBean(CustomerMapper.class);
Customer customer = customerMapper.findCustomerById(1);
System.out.println(customer);
}
5.实际开发
Spring中加入后不需要 2,3步骤配置即可自动扫描完成
4.事务测试
编写事务接口的实现类
@Service
@Transactional
public class CustomerServiceImpl implements CustomerService{
@Autowired
private CustomerMapper customerMapper;
@Override
public void addCustomer(Customer customer) {
this.customerMapper.addCustomer(customer);
int i=1/0; //制造异常
}
}
//测试
@Test
public void findCustomerByIdDaoTest(){
ApplicationContext act =
new ClassPathXmlApplicationContext("applicationContext.xml");
CustomerDao customerDao;
//customerDao = (CustomerDao) act.getBean("customerDao");
customerDao = act.getBean(CustomerDao.class);
Customer customer = customerDao.findCustomerById(1);
System.out.println(customer);
}