【问题标题】:Getting data from another entity从另一个实体获取数据
【发布时间】:2021-12-09 11:40:18
【问题描述】:

我必须使用 post 方法添加一个新用户。如果用户提供的 locName 存在于 location_table 中,则将 location_table 中的 locName 及其对应的状态考虑在新的用户记录中,并保存在 user_table 中。代码在下面的 else 语句中。

@Component 
public class UserManager{
    @Autowired
    private UserRepository uRepo;
    @Autowired
    private LocationRepository lRepo;
    
    @Transactional
    public void save(UserDto u){        
        User user = new User();
                 Location location = new Location();
    
        if(!lRepo.existsByLocName(u.getLocName())){
             user.setBatchNum(u.getBatchNum());
             user.setLocName(u.getLocName());
             user.setState(u.getState());

             location.setLocName(u.getLocName());
             location.setState(u.getState());    
        }
        else{
             user.setBatchNum(u.getBatchNum());
             user.setLocName(u.getLocName());
             user.setState(l.getState ()); // How do I turn this l in “l.getState()” into      
                                           // a variable for Location so I can get the State of
                                           // that Location entity (not in UserDto)?
        }       
        lRepo.save(location);
        uRepo.save(user);
}

【问题讨论】:

  • 你到底想要什么?当 lRepo.existsByLocName 为 true 时,是否要从 u.getLocName 中选择位置数据?

标签: java json spring-data-jpa


【解决方案1】:

尝试给LocationRepository添加一个方法,通过用户名返回位置状态,然后作为user.setState(...)的arg。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多