我正在使用 Spring JPA 并希望将值设置为外键列。这是我的实体和存储库。
@Entity
public class Device {
@NotEmpty
@Id
private String deviceId;
@ManyToOne
@JoinColumn(name="userId", referencedColumnName="userId", insertable=false, updatable=false)
@NotFound(action=NotFoundAction.IGNORE)
private User user;
//Getters and setters
}
@Entity
public class User(){
@Id
private String userId;
private String userName;
//Getters and setters
}
public interface DeviceRepository extends PagingAndSortingRepository {
}
public class DeviceServiceImpl implements DeviceService {
@Autowired
private DeviceRepository devRepos;
@Autowired
private UserRepository userRepos;
@Override
public void saveDevice(Device device, String userId) {
User user = null;
if (userId!=null) {
user = userRepos.findOne(userid);
device.setUser(user);
}
deviceRepos.save(device);
}
}
用户存在于 Device 表中,但表中的 userId 列未设置值。请帮我解决问题。
编辑:我从注释中删除了可插入和可更新的,现在它可以工作了。@JoinColumn(name="userId", referencedColumnName="userId")
那么,这意味着每当我保存设备时,我都必须从用户表中获取设备的用户?