我想根据user表中的id关联创建plan表的creator,要求user登录后根据ID获取到的token关联plan表的唯一一个creator,使用springboot和mybatisplus
时间: 2024-04-30 22:20:43 浏览: 180
可以按照以下步骤进行操作:
1. 创建两个实体类User和Plan,分别对应user表和plan表。
```java
@Data
public class User {
private Long id;
private String name;
private String token;
}
@Data
public class Plan {
private Long id;
private String name;
private String creator;
}
```
2. 在mybatisplus中配置实体类与数据库表的映射关系。
```java
@Configuration
@MapperScan("com.example.mapper")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
@Bean
public ConfigurationCustomizer configurationCustomizer() {
return configuration -> configuration.setUseDeprecatedExecutor(false);
}
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}
@Bean
public MetaObjectHandler metaObjectHandler() {
return new MybatisMetaObjectHandler();
}
@Bean
public ConfigurationCustomizer mybatisConfigurationCustomizer() {
return configuration -> {
configuration.getTypeHandlerRegistry().register(UserTypeHandler.class);
configuration.getTypeHandlerRegistry().register(PlanTypeHandler.class);
};
}
}
```
3. 创建Mapper接口,在其中定义查询方法。
```java
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
@Mapper
public interface PlanMapper extends BaseMapper<Plan> {
@Select("SELECT creator FROM plan WHERE id = #{id}")
String getCreatorById(@Param("id") Long id);
}
```
4. 创建Service层,调用Mapper中的方法,完成业务逻辑处理。
```java
@Service
public class PlanService {
@Autowired
private PlanMapper planMapper;
@Autowired
private UserMapper userMapper;
public String getCreatorById(Long id) {
User user = userMapper.selectById(id);
if (user == null) {
return null;
}
return planMapper.getCreatorById(id);
}
}
```
5. 在Controller中调用Service层的方法,返回查询结果给前端。
```java
@RestController
public class PlanController {
@Autowired
private PlanService planService;
@GetMapping("/plan/{id}/creator")
public String getCreatorById(@PathVariable("id") Long id) {
return planService.getCreatorById(id);
}
}
```
以上就是根据user表中的id关联创建plan表的creator的实现方法,希望可以帮助到你。
阅读全文