之前在写包的时候会划分为dao层,service层,action层,以及实现类层
有了mybatis后dao接口层的实现类不需要写了,有spring代理完成,步骤如下
在spring的配置文件中spring.xml配置如下:
1. spring.xml
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
">
2.mapper.xml:就是实体类对应的映射文件
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
insert into dept values(#{deptId},#{deptName},#{deptAddress})
3. service实现层
package com.coffee.scm.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.coffee.scm.dao.IDeptDao;
import com.coffee.scm.entity.Dept;
import com.coffee.scm.service.IDeptService;
@Service
public class DeptService implements IDeptService {
// 这个注解是根据类型配置,只需找类型,加上这个注解,然后配置接口映射可以去掉dao的接口实现,由spring自动代理完成
@Autowired
private IDeptDao deptDao;
/**
* 插入部门信息,如果遇到异常会回滚,因为spring.xml的事务通知配置里面配置了rollback-for="Exception"
*/
@Override
public void insertDept(Dept dept) throws Exception {
try {
deptDao.insert(dept);
} catch (Exception e) {
throw new Exception(e);
}
}
}
注意:dao接口层定义的方法名要和mapper.xml的sql标签的id对应一致