Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

java - @ManyToMany without join table (legacy database)

I have to apply JPA in a legacy database with an awful design. Unfortunately is not possible to change it. Luckily is only for read-only access.

One of the strangest things I found is a "many-to-many" relationship without a join (or intermediate) table. This is a simplification of the table structure:

USER                      ACCESS
----                      ------
ID int primary key        ID int primary key
NAME varchar2(20)         NAME varchar2(20)
ACCESS_GROUP int          ACCESS_GROUP int
  • ACCESS_GROUP columns can be repeated in both tables
  • One USER can be related to N ACCESS
  • One ACCESS can be related to N USER

"Conceptually" this tables must be mapped with Java classes this way:

public class User {
    private Integer id;
    private String name;
    @ManyToMany private List<Access> accessList;
}

public class Access {
    private Integer id;
    private String name;
    @ManyToMany private List<User> userList;
}

But I think this is not possible. What do you think is the best approach to access this tables in JPA and navigate through them?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can try to map it as two read-only one-to-many relationships:

public class User {
    @Column(name = "ACCESS_GROUP")
    private Integer group;

    @OneToMany
    @JoinColumn(name = "ACCESS_GROUP", referencedColumnName = "ACCESS_GROUP",
        insertable = false, updateable = false)
    private List<Access> accessList;
    ...
}

public class Access {
    @Column(name = "ACCESS_GROUP")
    private Integer group;

    @OneToMany
    @JoinColumn(name = "ACCESS_GROUP", referencedColumnName = "ACCESS_GROUP",
        insertable = false, updateable = false)
    private List<User> userList;
    ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...