哈喽,大家好,我是木头左!
一、背景介绍
在某些情况下,实体类可能没有主键属性,这时该如何使用Mybatis Plus向表中插入数据呢?本文将详细介绍如何在没有主键的实体WhitelistEntity中增加一行数据。
二、实体类WhitelistEntity的设计
需要设计一个没有主键属性的实体类WhitelistEntity。在这个实体类中,可以定义一些其他的属性,例如id(主键)、name(名称)、description(描述)等。由于实体类没有主键属性,需要在插入数据时手动指定主键值。
public class WhitelistEntity {
private Integer id;
private String name;
private String description;
// 省略getter和setter方法
}
三、自定义主键生成策略
为了在插入数据时能够手动指定主键值,需要实现一个自定义的主键生成策略。在Mybatis Plus中,可以通过实现KeyGenerator接口来自定义主键生成策略。
public class CustomIdGenerator implements KeyGenerator {
@Override
public Object generate(Object target, String columnName, Object propertyValue) {
// 在这里实现自定义的主键生成策略,例如根据时间戳生成主键
return System.currentTimeMillis();
}
}
接下来,需要将自定义的主键生成策略注册到Mybatis Plus中。在Spring Boot项目中,可以通过在配置类中添加一个Bean来实现这一点。
@Configuration
public class MybatisPlusConfig {
@Bean
public KeyGenerator keyGenerator() {
return new CustomIdGenerator();
}
}
四、编写Mapper接口
为了实现向表中插入数据的功能,需要编写一个Mapper接口。在这个接口中,定义一个插入数据的方法,并使用@Insert注解来指定插入数据的SQL语句。同时,需要在方法参数中添加一个@Param注解,用于指定插入数据时的字段名。
public interface WhitelistMapper extends BaseMapper<WhitelistEntity> {
@Insert("INSERT INTO whitelist (id, name, description) VALUES (#{id}, #{name}, #{description})")
int insertWhitelist(@Param("id") Integer id, @Param("name") String name, @Param("description") String description);
}
五、编写Service接口及实现类
接下来,需要编写一个Service接口及实现类,用于调用Mapper接口中的方法。在这个实现类中,实现一个插入数据的方法,并在方法中调用Mapper接口中的插入数据方法。
public interface WhitelistService extends IService<WhitelistEntity> {
}
@Service
public class WhitelistServiceImpl extends ServiceImpl<WhitelistMapper, WhitelistEntity> implements WhitelistService {
@Autowired
private WhitelistMapper whitelistMapper;
public int insertWhitelist(WhitelistEntity whitelistEntity) {
return whitelistMapper.insertWhitelist(whitelistEntity.getId(), whitelistEntity.getName(), whitelistEntity.getDescription());
}
}
六、编写Controller类
需要编写一个Controller类,用于处理前端发起的请求。在这个类中,定义一个插入数据的方法,并在方法中调用Service接口中的插入数据方法。
@RestController
@RequestMapping("/whitelist")
public class WhitelistController {
@Autowired
private WhitelistService whitelistService;
@PostMapping("/insert")
public ResponseEntity<?> insertWhitelist(@RequestBody WhitelistEntity whitelistEntity) {
int result = whitelistService.insertWhitelist(whitelistEntity);
if (result > 0) {
return ResponseEntity.ok("插入成功");
} else {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("插入失败");
}
}
}
七、测试插入数据功能
现在,已经完成了所有准备工作,可以开始测试插入数据的功能了。可以通过编写一个简单的测试用例来验证的代码是否能够正常工作。
@SpringBootTest
public class WhitelistTest {
@Autowired
private WhitelistService whitelistService;
@Test
public void testInsertWhitelist() {
WhitelistEntity whitelistEntity = new WhitelistEntity();
whitelistEntity.setId(1);
whitelistEntity.setName("test");
whitelistEntity.setDescription("这是一个测试");
int result = whitelistService.insertWhitelist(whitelistEntity);
Assertions.assertEquals(1, result);
}
}
通过运行测试用例,可以看到插入数据的功能能够正常工作。至此,已经成功地在没有主键的实体WhitelistEntity中增加了一行数据。
我是木头左,感谢各位童鞋的点赞、收藏,我们下期更精彩!