I am trying to map a class with composite key in datanucleus. The primary key is composed of two foreign keys and I can't seem to be able to include these foreign classes in the fetchgroup:
Using annotations :
@PrimaryKey
@Column(name = idElementOne, allowsNull = "false")
private Long idElementOne;
@PrimaryKey
@Column(name = "idElementTwo", allowsNull = "false");
private Long idElementTwo;
works
@PrimaryKey
@Column(name = idElementOne, allowsNull = "false");
private ElementOne elementOne;
@Column(name = "idElementTwo", allowsNull = "false");
private Long idElementTwo;
works
but
@PrimaryKey
@Column(name = idElementOne, allowsNull = "false")
private ElementOne elementOne;
@PrimaryKey
@Column(name = "idElementTwo", allowsNull = "false");
private Long idElementTwo;
does not.
How am I meant t开发者_JAVA百科o do ?
Thanks to comments from DataNucleus user and documentation from the official website here is what I was missing.
ElementOne needs a PrimaryKey class so that we can use a constructor accepting a string argument in the main class' PrimaryKey.
ElementOne PrimaryKey class:
public static class PK implements Serializable
{
public Long idElementOne;
public PK()
{
}
public PK(String s)
{
this.idElementOne = Long.valueOf(s);
}
public String toString()
{
return "" + idElementOne;
}
//...
}
Main class with its PrimaryKey class:
@PersistenceCapable(objectIdClass=PK.class)
public class MainClass{
@PrimaryKey
@Column(name = idElementOne, allowsNull = "false")
private ElementOne elementOne;
@PrimaryKey
@Column(name = "idElementTwo", allowsNull = "false");
private Long idElementTwo;
//...
public static class PK implements Serializable
{
public Long idElementTwo; // Same name as real field in the main class
public ElementOne.PK elementOne; // Same name as the real field in the main class
public PK()
{
}
public PK(String s)
{
String[] constructorParam = s.split("::");
this.idElementTwo= Long.parseLong(constructorParam[1]);
this.personne = new Personne.PK(constructorParam[2]);
}
public String toString()
{
return "" + idElementTwo+ "::" + this.personne.toString();
}
//...
}
}
PS: Examples from DataNucleus website use StringTokenizer which is not implemented in GWT, use String.split() instead. Moreover the java doc states that:
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
精彩评论