2010-03-15 44 views
11

我一直在使用Hibernate Annotations 3.4.0在Scala 2.8.0中構建一些帶註釋的域類。它一直工作正常,除了有某些註釋將數組作爲參數。例如,這裏就是我想在Scala中表達一個Java註解:如何在Scala 2.8註釋中指定一個靜態數組?

@OneToMany(mappedBy="passport_id", cascade=CascadeType.PERSIST) 

然而,註釋需要數組/設置爲輸入:

[ERROR] .../Passport.scala:50: error: type mismatch; 
[INFO] found : javax.persistence.CascadeType(value PERSIST) 
[INFO] required: Array[javax.persistence.CascadeType] 
[INFO]  @OneToMany(mappedBy="passport_id", cascade=CascadeType.PERSIST) 

我已經試過各種圓括號,方/角度/大括號等等:

@OneToMany(mappedBy="passport_id", cascade=(CascadeType.PERSIST)) 
@OneToMany(mappedBy="passport_id", cascade=[CascadeType.PERSIST]) 
@OneToMany(mappedBy="passport_id", cascade=<CascadeType.PERSIST>) 
@OneToMany(mappedBy="passport_id", cascade={CascadeType.PERSIST}) 

......但不幸的是我已經達到了我對Scala/Java註釋理解的最後。幫助表示讚賞。

+5

你試過cascade = Array(CascadeType.PERSIST)嗎? – 2010-03-15 15:58:11

+0

是的。有效。 :-) 謝謝。 – 2010-03-15 16:58:21

回答

14

我會從spec中添加一些片段來解釋雷克斯解決方案的原因。

對於斯卡拉在JVM上,參數,將生成的類中保留標註必須是常量表達式:

Instances of an annotation class inheriting from trait scala.ClassfileAnnotation will be stored in the generated class files. ... Additionally, on both Java and .NET, all constructor arguments must be constant expressions.

什麼是常量表達式?

6.24 Constant Expressions Constant expressions are expressions that the Scala compiler can evaluate to a constant. The definition of 「constant expression」 depends on the platform, but they include at least the expressions of the following forms:

  • A literal of a value class, such as an integer
  • A string literal
  • A class constructed with Predef.classOf (§12.4)
  • An element of an enumeration from the underlying platform
  • A literal array, of the form Array(c1, . . . , cn), where all of the ci ’s are themselves constant expressions
  • An identifier defined by a constant value definition (§4.1).

您還應該能夠將參數重構爲final val。但是,這似乎不適用於陣列。我會提出一個錯誤。

class T(value: Any) extends ClassfileAnnotation 

object Holder { 
    final val as = Array(1, 2, 3) 
    final val a = 1 
} 

@T(Holder.a) 
@T(Holder.as) // annot.scala:9: error: annotation argument needs to be a constant; found: Holder.as 
class Target 
+0

不適用於我:@BeanProperty @Id @GeneratedValue(strategy = Array(GenerationType.IDENTITY))var id:Long = _給出錯誤:找到數組常量,期望的參數類型爲javax.persistence.GenerationType – 2011-04-13 18:11:51

+1

註釋參數正如編譯器錯誤所建議的,「strategy」只接受單個值。 http://download.oracle.com/javaee/5/api/javax/persistence/GeneratedValue.html'strategy = GenerationType.IDENTITY'應該做到這一點。 – retronym 2011-04-13 20:57:16

+0

他們仍然在想。 http://stackoverflow.com/q/19060918/1296806 – 2013-09-28 04:34:18

8

雷克斯克爾:

@OneToMany(mappedBy="passport_id", cascade=Array(CascadeType.PERSIST)) 

這個工作。謝謝。

相關問題