kotlin中的数字不可序列化

时间:2014-10-04 20:17:49

标签: spring serialization kotlin spring-data-jpa

我发现kotlin中的数字不可序列化。

  1. 第一个问题
  2. Device.kt:

    package test.domain
    
    import javax.persistence.*
    
    Entity public class Device {
        public Id GeneratedValue var id: Long = -1
        public var name: String = ""
        ...
    }
    

    DeviceRestRepository.kt:

    package test.domain
    
    import org.springframework.data.repository.PagingAndSortingRepository
    import org.springframework.data.repository.query.Param
    import org.springframework.data.rest.core.annotation.RepositoryRestResource
    
    RepositoryRestResource(collectionResourceRel = "device", path = "device")
    public trait DeviceRestRepository : PagingAndSortingRepository<Device, Long?> {
        public fun findByName(Param("name") name: String): List<Device>
    }
    

    我尝试编译此代码时出错,因为 kotlin.Long 不是可序列化

      

    错误:(14,72)Kotlin:类型参数不在其范围内:应该   是&#39; java.io.Serializable?&#39;

    的子类型
    1. 第二个问题
    2. 当我尝试使用 java.lang.Long 时出现同样的错误:

      DeviceRestRepository.kt:

      package test.domain
      
      import org.springframework.data.repository.PagingAndSortingRepository
      import org.springframework.data.repository.query.Param
      import org.springframework.data.rest.core.annotation.RepositoryRestResource
      
      RepositoryRestResource(collectionResourceRel = "device", path = "device")
      public trait DeviceRestRepository : PagingAndSortingRepository<Device, java.lang.Long?> {
          public fun findByName(Param("name") name: String): List<Device>
      }
      
        

      警告:(14,72)Kotlin:这个课不应该在Kotlin中使用。使用   kotlin.Long代替。

           

      错误:(14,72)Kotlin:类型参数不是   在其范围内:应该是&#39; java.io.Serializable?&#39;

      的子类型

3 个答案:

答案 0 :(得分:3)

Asot of Kotlin 1.0 Beta 1基元类型是可序列化的:

  

Int是Serializable

     

现在,类型Int和其他基本类型在JVM上是Serializable。这应该有助于许多框架。

自: http://blog.jetbrains.com/kotlin/2015/10/kotlin-1-0-beta-candidate-is-out/

因此,您不再有任何问题。

答案 1 :(得分:1)

我找到了解决这个问题的方法:

Device.kt:

package test.domain

import javax.persistence.*

Entity public class Device {
    public EmbeddedId var id: DeviceId = DeviceId()
    public var name: String = ""
    ...
}

Embeddable public class DeviceId: Serializable {
    public GeneratedValue var id: Long = -1
}

DeviceRestRepository.kt:

package test.domain

import org.springframework.data.repository.PagingAndSortingRepository
import org.springframework.data.repository.query.Param
import org.springframework.data.rest.core.annotation.RepositoryRestResource

RepositoryRestResource(collectionResourceRel = "device", path = "device")
public trait DeviceRestRepository : PagingAndSortingRepository<Device, DeviceId?> {
    public fun findByName(Param("name") name: String): List<Device>
}

此用例工作正常

答案 2 :(得分:0)

我偶然发现了同样的问题,我设法通过在Java中使用我的Repository接口来处理它,其中我将 java.lang.Long 作为id的泛型类型参数。其余的仍留在kotlin(数据类,服务类等)

相关问题