views:

109

answers:

2

I'm trying to generate JPA entities out of an existing database having an "interesting" design.

Database has a table called UserSet, which can have links to several other UserSets. There is a one to many relation between UserSets and LinkedUserSets. LinkedUserSets also has one to one relation to UserSets.

I tried to generate a JPA Entity out of the database structure using Dali JPA Tools. The resulting entity Linkeduserset misses @Id or @EmbeddedId annotation and thus failes to compile. As the resulting entity contains only two @JoinColumns (which cannot be marked as @Id), I have not so far found a way around this issue.

Database structure can not be modified in any way.

Is there a way to overcome this somehow?

Relevant pars of create table statements:

CREATE  TABLE `LinkedUserSets` (
  `UsrSetID` INT(11) NOT NULL DEFAULT '0' ,
  `ChildID` INT(11) NOT NULL DEFAULT '0' ,
  CONSTRAINT `fk_LinkedUserSets_UserSet1`
    FOREIGN KEY (`UsrSetID` )
    REFERENCES `UserSet` (`UsrSetID` ));

CREATE  TABLE `UserSet` (
  `UsrSetID` INT(11) NOT NULL AUTO_INCREMENT ,
  PRIMARY KEY (`UsrSetID`),
  CONSTRAINT `fk_UserSet_LinkedUserSets1`
    FOREIGN KEY (`UsrSetID` )
    REFERENCES `LinkedUserSets` (`ChildID` ));

Generated entities:

@Entity
@Table(name="linkedusersets")
public class Linkeduserset {
    //bi-directional many-to-one association to Userset
    @ManyToOne
    @JoinColumn(name="UsrSetID")
    private Userset userset1;

    //bi-directional one-to-one association to Userset
    @OneToOne
    @JoinColumn(name="ChildID")
    private Userset userset2;
}


@Entity
@Table(name="userset")
public class Userset {
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name="UsrSetID")
    private int jngSetID;

    //bi-directional many-to-one association to Linkeduserset
    @OneToMany(mappedBy="userset1")
    private Set<Linkeduserset> linkedusersets;

    //bi-directional one-to-one association to Linkeduserset
    @OneToOne(mappedBy="userset2")
    private Linkeduserset linkeduserset;
}

Error message:

Entity "Linkeduserset" has no Id or EmbeddedId
A: 

You should still add a unique PK column to the LinkedUserSets table. This will help fortify this table.

You may also want to create an index (unique?) on LinkedUserSets(UsrSetId, ChildId) for faster lookups.

... and it's not such an "interesting" design. This is quite common :)

Tim Drisdelle
I cannot take the risk of modifying the database structure. It might break "something else" utilizing the same database.That's not the only "interesting" part in the DB :-)
tputkonen
+1  A: 

If you wish to map this without changing the database, you might want to consider trying to map just the UserSet class as an entity with a many-to-many relation to itself and with the LinkedUserSet as a join table, so that the mapping really reflects what's in the database.

Don Roby