Object mapping JPA/openEJB for database

139 Views Asked by At

Hello everyone I am trying to get my class to persist to my database however I have run into a problem im not sure how to solve. I am attempting to map the three instances of Score with my user but I am not sure how ti get this to work. Any help is appreciated. Thank you :)

User class Snipit.

@Column(name="userName", unique=true)
private String username;
@Column(name="password")
private String password;

//I am not sure how to map the three fields below.
private Score highestScore; 
private Score averageScore; 
private Score lowestScore;
3

There are 3 best solutions below

0
On BEST ANSWER

While there is an accepted answer here I am not seeing how the proposed mapping distinguishes between the High, Low and Average scores?

You could consider using a Map such as below where the score table will have a column 'score_type' which can be mapped to an Enum 'ScoreType':

public class User{  

    @Column(name="userName", unique=true)
    private String username;

    @Column(name="password")
    private String password;

    @OneToMany
    @MapKeyColumn(name="score_type")
    @MapKeyEnumerated
    private Map<ScoreType, Score> scores; 

    public Score getHighScore(){
        return scores.get(ScoreType.HIGH);
    }

    public void setScore(Score score){
        score.setUser(this);
        scores.put(score.getType(), score);
    }
}

and

public class Score{

    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    @Column(name = "type")
    @Enumerated(EnumType.String)//or ordinal
    private ScoreType type;
}
3
On

In my point of view User have one score and score have one user. So @OneToOne User is the owning side and its bidirectional.

code should looks like this

in Score:

@OneToOne(mappedBy = "score")
private User user

in User:

@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
@PrimaryKeyJoinColumn
private Score highestScore;
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
@PrimaryKeyJoinColumn
private Score averageScore;
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
@PrimaryKeyJoinColumn
private Score lowestScore;
4
On

if score not related to the database, use @Transient annotation for score

if score related to database, use mapping annotation such as @OneToOne , @OneToMany (depend on your database cardinality)

EDIT : if score related to database table, IMHO the easiest way is let the IDE automaticly generate entity from database for you (but sometimes IDE can generate undesired mapping, so you still need to check it)

if you using eclipse Generating entities from tables

if you using netbeans Adding Entity Classes

but you still need to know about Multiplicity in Entity Relationships