前提:我们已经配置好我们的数据源
①、首先我们导入我们的mybatis-plus:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
②、创建我们的表类,需要知道我们的类名会被解析成我们库中对应的表,所以我们的类名一定不能随便的取,一定要正规合法与库中的表名对应
或者可以使用注解@TableName(“XX”)
@AllArgsConstructor
@NoArgsConstructor
@Data
public class countries {
@TableField(exist = false)
private String userName;
private String country_id;
private String country_name;
private int region_id;
}
2、我们在mybatis中的类中的属性每一个都必须存在于mybatis中,如果不存在的话,我们需要使用@TableFiled(exist = false)
③、配置我们的Mapper,注意我们需要继承于我们的BaseMapper,其中泛型T就是我们想要操作的表类。
@Mapper
public interface countriesMapper extends BaseMapper<countries> {
}
测试:
@Autowired
countriesMapper countriesMapper;
@Test
void test01(){
countries location = locationinfomapper.selectById(2);
System.out.println(location);
}
虽然以上已经很方便了,但是我们开发中更常用的是以下:
①、我们首先创建好我们的bean和Mapper,其中的Mapper
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private int age;
}
@Mapper
public interface userMapper extends BaseMapper<User> {
}
其中我们的MApper需要继承我们的BaseMapper,其中泛型为我们的处理对象
②、接着我们需要编写我们的Userservice接口,该接口需要继承我们的顶级接口IService,其中泛型为我们想要查询的那些数据类型(因为我们的userService实现了我们的顶级接口,所以我们不用使用注入@Service也能将我们的接口注入到IOC容器中):
@Service
public interface userService extends IService<User> {
}
③、编写我们的接口实现类userServiceImpl:
//因为我们的实现类实现了接口,所以我们就得实现他的所有方法,我们通过继承顶级接口的实现类ServiceImpl,该类需要传入泛型是操作哪张表的BaseMapper和想要查询的哪些数据
@Service
public class userServiceImpl extends ServiceImpl<userMapper,User> implements userService {
}
此后我们就可以使用我们的接口中的方法,或者我们的实现类中的方法,我们就再也不用自己去写,自己去调用了。
例如:
@Autowired
userService userService;
@Autowired
userServiceImpl userServiceImpl;
@ResponseBody
@GetMapping("/user")
public User getUser(){
// User user = userServiceImpl.getById(2);
User user = userService.getById(2);
return user;
}
我们只用了几行代码省去了之前写的很多。(有些人的userService可能会爆红,爆红的原因是因为我们的springboot使用注解方式是将我们的
类加入到IOC容器中,而不是接口,如果我们使用的是接口,那么
我们通过动态代理(分为代理类和代理接口)JDK代理。此时我们
的springboot依旧认为IOC容器中我们并没有该接口,实际已经存
在了,可以正常使用,若想不爆红,我们只需在所在接口加上@repository标注为持久层组件)
本文介绍了如何使用MyBatis-Plus进行数据库操作,包括依赖引入、实体类和Mapper接口的创建,以及Service层的实现。通过示例展示了如何通过BaseMapper简化SQL查询,并提供了测试代码。此外,还提及了SpringBoot中接口注入的原理和动态代理的应用。
909

被折叠的 条评论
为什么被折叠?



