使用springboot整合我们的mybatis-plus

本文介绍了如何使用MyBatis-Plus进行数据库操作,包括依赖引入、实体类和Mapper接口的创建,以及Service层的实现。通过示例展示了如何通过BaseMapper简化SQL查询,并提供了测试代码。此外,还提及了SpringBoot中接口注入的原理和动态代理的应用。

前提:我们已经配置好我们的数据源
①、首先我们导入我们的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标注为持久层组件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值