Mybatis-plus只是一个Mybatis的增强工具,只是简化了开发,提高了效率
一、导入Mybatis-plus依赖
com.baomidou
mybatis-plus-boot-starter
3.4.3.4
注:导入后不必再导入Mybatis的依赖
其底层自动配置好了SqlSessionFactory,数据源是自定义的数据源(druid)
二、编写Mapper接口所有Mapper接口所对应的 *Mapper.xml文件都必须在classpath*:/mapper/ 下,
因为底层自动配置好了mapperLocations
容器中也自动配置好了 SqlSessionTemplate
附:Mybatis:了解SqlSessionTemplate_Java程序员的进阶之路-CSDN博客_sqlsessiontemplate
编写好的接口标注@Mapper
与Mybatis不同的是,我们只需要让接口继承基类baseMapper<>便可以使用封装好的CRUD
package com.teen.review.Mapper; import com.baomidou.mybatisplus.core.mapper.baseMapper; import com.teen.review.Bean.tUser; import org.apache.ibatis.annotations.Mapper; //不要导错类 @Mapper public interface UserMapper extends baseMapper三、编写三层架构{ }
编写serveic层接口
只需要继承 IService<>即可
package com.teen.review.service; import com.baomidou.mybatisplus.extension.service.IService; import com.teen.review.Bean.tUser; public interface UserService extends IService{ }
编写ServiceImpl实现Service接口
此类可以继承ServiceImpl
将实现类注册到容器中@Service
package com.teen.review.service.serviceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.teen.review.Bean.tUser; import com.teen.review.Mapper.UserMapper; import com.teen.review.service.UserService; import org.springframework.stereotype.Service; @Service public class UserServiceImpl extends ServiceImpl四、测试implements UserService { }
测试类中
使用@Autowried 自动注入Service接口
@Autowired
UserService userService;
@Test
void SelectByUserNameTest(){
String username = "123456";
//创建条件构造器Warpper
QueryWrapper wrapper = new QueryWrapper();
//附加条件 .eq 字段相等
wrapper.eq("username",username);
Map map = userService.getMap(wrapper);
if( map==null){
System.out.println("没查到");
}
}
五、自定义查询
1) 在UserMapper中编写自定义方法
package com.teen.review.Mapper; import com.baomidou.mybatisplus.core.mapper.baseMapper; import com.teen.review.Bean.tUser; import org.apache.ibatis.annotations.Mapper; //不要导错类 @Mapper public interface UserMapper extends baseMapper{ public tUser getUserById(Integer id); //实现一对多 查出一个用户的所有书,返回类型为用户 public tUser getUserBookById(Integer id); }
在mapper/UserMapper.xml (名字不一定需要相同)中实现sql映射
mapper标签中的namespace属性对应Mapper接口全类名
select标签的id属性对应接口方法名
parametType属性代表方法形参类型
resultType属性为结果集类型,此处返回pojo对象tUser,会被自动封装
一对多的复杂查询使用resultMap做结果集映射
resultMap 的id属性为select标签中resultMap的值
type属性为返回类型的真实映射的pojo类
标签体中简单类型用result ,集合类型用collection
collection标签的ofType属性为此字段所真实映射的pojo类
其内的result标签继续指定返回字段
2) 测试数据库中不存在的字段没有值
@Test
void MybatisTest01()
{
System.out.println(userMapper.getUserById(1));
//查询结果
}
结果集未返回的字段值也为null
@Test
void MybatisTest04(){
System.out.println(userMapper.getUserBookById(1));
}
自定义查询的缺点:
方法是定义在Mapper接口中的,所以调用方法只能将Mapper接口自动注入,通过调用userMapper来实现方法调用,这样就违背了三层架构的理念,作为初学者,暂时想不到如何调用service层来实现自定义查询



