I'm using Datanucleus (jdo) with derby and I have a class MyClass. And this class has a variable of the type AnotherClass. I want to persist this variable.开发者_如何学Go When an instance of MyClass is persisted, the variable AnotherClass is persisted too.
Now the problem: When I persist a new MyClass and this instance has the same AnotherClass instance as variable I don't want to save it into the AnotherClass table again but just reference it by the ID in the MyClass table. Else my AnotherClass table will have tons of the same instance persisted.
At the momement my class looks like this:
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class MyClass implements Serializable {
private static final long serialVersionUID = -5074030667922748006L;
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
Long key;
@Persistent
AnotherClass anotherClass;
Update:
The AnotherClass class looks like the MyClass class.
I guess Tom Anderson's answer was already the correct one. I'm creating NEW AnotherClass instances and put them into the MyClass instance like myClass.setAnotherClass(anotherClass). So I guess anotherClass is an instance with the same values but it's still not the same instance so it gets its own row in the database even thought it looks exactly identical in there (except of the ID).
So I guess the solution would be: Check if the AnotherClass instance is already persisted in the database, if yes: get it from the database and set that instance to my myClass. If not: create a new instance and set it to the myClass so it gets persisted when myClass is persisted. Is that the way I should do it?
EDIT: Ok, now I have a new problem: I can't delete MyClass (= Character) instances anymore. If I try to do that I get this Exception (AnotherClass = Faction):
java.sql.SQLIntegrityConstraintViolationException: DELETE on table 'FACTION' caused a violation of foreign key constraint 'CHARACTER_FK1' for key (1). The statement has been rolled back.
That just happend when I did this: Create character1, create character2 exactly the same faction (it's only in the database once), try to delete character2. Any idea why?
EDIT2: Forgot something important:
@Persistent(dependent = "true")
Faction faction;
That's what my Character class is saying. I have that because I want the Faction to be deleted if no Character is using it. I guess that's the problem? How can I do that now?
This should just work. If the two MyClass instances are pointing to the same AnotherClass instance, then there will be one entry in the AnotherClass table, referenced by both of the MyClass entries.
If you're seeing lots of AnotherClass entries, it can only be because you have many different instances at runtime. How do you define identity of AnotherClass? How are you associating MyClass instances with AnotherClass instances?
精彩评论