gnuvince
gnuvince

Reputation: 2387

Mutually referential fields in Play

I am trying to model users with home directories in my system. I got the following model declarations:

@Entity
public class Directory extends Model {
  public String name;
  @ManyToOne public Directory parent;
  @ManyToOne public User owner;
  @OneToMany public Set<User> sharees;
}

@Entity
public class User extends Model {
  @Unique @Column(unique=true) public String username;
  public String password;
  public Directory homeDirectory;

  public User(String username, String password) {
    this.username = username;
    this.password = password;
    this.homeDirectory = new Directory(username, null, this);
  }
}
  1. When I create a user and call .save(), I get an error (A javax.persistence.PersistenceException has been caught, org.hibernate.exception.GenericJDBCException: could not insert: [models.User]). Can anyone explain why?

  2. Using fixtures, can I test this? I'd need to create forward references in my yaml file, but I'm not sure if that's possible.

Thanks,

Vincent.

Upvotes: 1

Views: 98

Answers (1)

mcls
mcls

Reputation: 9784

  1. The error is thrown because of a missing @OneToOne annotation for homeDirectory.
    I assume you're creating a directory for each user. If that's the case, then you should also use CascadeType.ALL so these directories automatically get created/deleted when users get created/deleted.
  2. And no Yaml does not support forward references,
    so you'll have to work around that when using bidirectional relations.

Upvotes: 2

Related Questions