Question

I'm trying to create one-to-many relation with @JoinTable. Code works and does what it's supposed to do, BUT, is there a way to add more columns to the join-table? It will be a business application that needs some sort of history, so I will need fields like add_user, update_user, timestamp on create/update in the join-table. Is there an elegant way to do this with Java, without adding additional fields through altering tables? If there is, how to elegantly edit that data, lets say I add new relation, how to change value of mentioned fields? I say elegant, because you can always do something ugly, in this case - create relation, then update fields of that relation by both IDs, I'm interested if there is prettier, kind of more Java, way.

Code of both entities:

@Entity
@Table(name="users")
public class Users {
    int id;
    String username;
    private List<Jobs> jobs;

    @OneToMany
    @JoinTable(
        name="users_jobs_rel",
        joinColumns= @JoinColumn(name="user_id", referencedColumnName="user_id") ,
        inverseJoinColumns= @JoinColumn(name="job_id", referencedColumnName="job_id") 
    )
    public List<Jobs> getJobs() {
        return jobs;
    }
    public void setJobs(List<Jobs> jobs) {
        this.jobs = jobs;
    }
    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "user_id", unique = true, nullable = false)
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
 }

@Entity
@Table(name="jobs")
public class Jobs {
    int id;
    String title;
    @ManyToOne
    private Users user;

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "job_id", unique = true, nullable = false)
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

    @Column
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
}

Thanks in advance.

Was it helpful?

Solution

Usually, When you are using Many-to-Many , you need to create additional table for this relationship. But now, I do not have any idea why you are using one-to-many with creating new table (why? it is unnecessary). And the answer will be yes, you can join some additional columns to your table with @JoinColumn annotation. And pay attention if you really need bidirectional relationship :) Good luck

edited:

Is there an elegant way to do this with Java, without adding additional 
fields through altering tables?

What do you mean by saying 'altering'? Don't you let Hibernate to create it auto with using hbm2dll?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top