mybatis|mybatis 10 与spring简单整合

结构:
mybatis|mybatis 10 与spring简单整合
文章图片
Paste_Image.png jar包:
mybatis|mybatis 10 与spring简单整合
文章图片
Paste_Image.png 配置文件:
myBatis-conf.xml


applicationContext.xml

DeptMapper.xml
insert into dept_t(dept_name,dept_address) values(#{deptName},#{deptAddress})

类:
package com.xxjqr.dao.impl; import javax.annotation.Resource; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.stereotype.Repository; import com.xxjqr.dao.DeptDao; import com.xxjqr.entity.Dept; import lombok.Data; @Repository("deptDao") @Data public class DeptDaoImpl implements DeptDao {@Resource private SqlSessionTemplate sqlSessionTemplate; public int insertDept(Dept dept) { //命名空间+sqlId return sqlSessionTemplate.insert("com.xxjqr.entity.DeptMapper.insertDept",dept); }}

package com.xxjqr.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.xxjqr.dao.DeptDao; import com.xxjqr.entity.Dept; import com.xxjqr.service.DeptService; import lombok.Data; @Service("deptService") @Data public class DeptServiceImpl implements DeptService {@Resource private DeptDao deptDao; public int insertDept(Dept dept) { deptDao.insertDept(dept); return 0; }}

package com.xxjqr.Test; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.xxjqr.entity.Dept; import com.xxjqr.service.DeptService; public class App {@Test public void testInsertDept(){ ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml",App.class); DeptService deptService = (DeptService)ac.getBean("deptService"); Dept dept = new Dept(); dept.setDeptName("开发部"); dept.setDeptAddress("贵州"); System.out.println("受影响行数:"+deptService.insertDept(dept)); } }

优化 1. 优化别名
myBatis-conf.xml中修改
mybatis|mybatis 10 与spring简单整合
文章图片
Paste_Image.png 2. 优化sql映射文件的加载
myBatis-conf.xml中
mybatis|mybatis 10 与spring简单整合
文章图片
Paste_Image.png applicationContext.xml中修改

mybatis|mybatis 10 与spring简单整合
文章图片
Paste_Image.png 3. 优化dao实现
【mybatis|mybatis 10 与spring简单整合】

insert into dept_t(dept_name,dept_address) values(#{deptName},#{deptAddress})

使用该配置后,就无需Dao接口的实现了,因为框架会自动将dao接口的代理对象并注入到spring容器中;
DeptServiceImpl会通过@Autowired将代理对象注入到“dao接口”引用

    推荐阅读