首页 文章

如何在Spring JPA中设置foriegn键列

提问于
浏览
0

我正在使用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”)

那么,这意味着每当我保存设备时,我必须从User表中获取设备的用户?

1 回答

  • 0

    因为您为 Device 类中的 user 属性设置insertableupdatablefalse ,所以在生成SQL INSERT和UPDATE语句时,它将导致持久性提供程序忽略此列( Device.userId ) .

    只需将它们更改为 true 或删除它们,因为它们的默认值已经为真 .


    更新:

    这意味着每当我保存设备时,我必须从User表中获取设备的用户?

    在纯JPA中,如果您知道用户的ID,则可以使用EntityManager#getReference(User.class , aUserId)来获取用户实例,而无需实际查询数据库 . 但在Spring Data JPA中,it seems that this method is not supported out of the box .

相关问题