学习spring整合mybatis时,写SQL语句的Mapper接口明明没有任何被spring接管的痕迹(前面没有注解)但在serviceimpl类中却可以被自动装载。
BookDao.java(mapper接口类):
package com.itheima.dao; import com.itheima.domain.Book; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import java.util.List; public interface BookDao { // @Insert("insert into tbl_book values(null,#{type},#{name},#{description})") @Insert("insert into tbl_book (type,name,description) values(#{type},#{name},#{description})") public void save(Book book); @Update("update tbl_book set type = #{type}, name = #{name}, description = #{description} where id = #{id}") public void update(Book book); @Delete("delete from tbl_book where id = #{id}") public void delete(Integer id); @Select("select * from tbl_book where id = #{id}") public Book getById(Integer id); @Select("select * from tbl_book") public List<Book> getAll(); }
BookServiceImpl.java(业务层实现类):
package com.itheima.service.impl; import com.itheima.dao.BookDao; import com.itheima.domain.Book; import com.itheima.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class BookServiceImpl implements BookService { @Autowired private BookDao bookDao; public boolean save(Book book) { bookDao.save(book); return true; } public boolean update(Book book) { bookDao.update(book); return true; } public boolean delete(Integer id) { bookDao.delete(id); return true; } public Book getById(Integer id) { return bookDao.getById(id); } public List<Book> getAll() { return bookDao.getAll(); } }
这是因为之前引入的包MyBatis-Spring,默认会扫描整个项目中指定的包及其子包下的所有Mapper接口,并将其注册为Spring Bean。这个扫描范围是可以配置的,通过设置MapperScannerConfigurer的basePackage属性来指定要扫描的包。
若是在配置类里设置扫描范围,有两种写法,第一种是写在注解上:
@Configuration @MapperScan("com.example.dao") public class MyBatisConfig { // 其他配置 }
第二种是定义实体bean:
package com.itheima.config; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.mapper.MapperScannerConfigurer; import org.springframework.context.annotation.Bean; import javax.sql.DataSource; public class MyBatisConfig { @Bean public MapperScannerConfigurer mapperScannerConfigurer(){ MapperScannerConfigurer msc = new MapperScannerConfigurer(); msc.setBasePackage("com.itheima.dao"); return msc; } //其他配置 }
选其一就可
标签:Mapper,Spring,public,book,org,MyBatis,import,com,id From: https://www.cnblogs.com/ban-boi-making-dinner/p/17283077.html