You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从其他实体获取数据:新增用户时如何获取已存在Location实体的state值

代码修改方案

你原来的代码存在两个核心问题:

  • 只判断了locName是否存在,没有查询对应的已持久化Location实体,无法获取已存储的state值
  • else分支中你初始化的空Location对象直接调用lRepo.save()会存入无意义的空数据

修改后的完整代码

@Component 
public class UserManager{
    @Autowired
    private UserRepository uRepo;
    @Autowired
    private LocationRepository lRepo;
    
    @Transactional
    public void save(UserDto u){        
        User user = new User();
        // 先直接查询对应locName的Location实体,避免两次数据库查询
        Location location = lRepo.findByLocName(u.getLocName()).orElse(null);
    
        if(location == null){
            // locName不存在,新建Location实体
            location = new Location();
            location.setLocName(u.getLocName());
            location.setState(u.getState());
            
            user.setBatchNum(u.getBatchNum());
            user.setLocName(u.getLocName());
            user.setState(u.getState());
        }
        else{
            // locName已存在,直接用查询到的location实体的state赋值
            user.setBatchNum(u.getBatchNum());
            user.setLocName(u.getLocName());
            user.setState(location.getState());
        }       
        lRepo.save(location);
        uRepo.save(user);
    }
}

补充说明

  • 你需要先在LocationRepository中新增查询方法:Optional<Location> findByLocName(String locName);,Spring Data JPA会自动根据方法名生成SQL查询
  • 这里把原来的existsByLocName判断改成直接查询,减少了一次数据库请求,性能更优
  • else分支不需要再修改location对象,直接用查询到的持久化对象即可,save操作会自动识别是新增还是更新

内容的提问来源于stack exchange,提问作者casio_3000

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 11:54:03