简体   繁体   中英

How do I properly structure my hibernate relation between two classes

I have a situation where I got a user class and a car class. and the tables in my mysql database could look like this Below is a sketch of how I imagine the relation between the two entities to be.

             user                           user_car                   car
username  firstname  lastname    <---->  username   car_id  <----> car_id   cartype
  tea       bruce      anderson           tea        1             1        ford123
  t         arnold     mena               tea        2             2        audio2
                                          t          2

User have a Set, which contains objects of car. But car should not hold reference to any user. I've tried several methods, but always end up with the same error "duplicate key '' at primary".

@Entity
public class car {
@Id
@GeneratedValue(strategy=GenerationType.AUTO) 
private long car_id;
    private String type;

public car(){

}

public long getCar_id() {
    return car_id;
}

public void setCar_id(long car_id) {
    this.car_id = car_id;
}

public String getType() {
    return type;
}

public void setType(String type) {
    this.type = type;
}

}

User class

@Entity
public class userr {

    @Id
    private String username;
    private String firstname;
    private String lastname;

    //Some relation here, which I do not know how to properly set up
    private Set<Car> cars = new HashSet<>();

    public userr(){

    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public Set<Car> getCars() {
        return cars;
    }

    public void setCars(Set<Car> cars) {
        this.cars = cars;
    }
}

any help is greatly appreciated.

You should use many-to-many mapping with join table. Look it up in Hibernate documentation.

Use the below mapping on your entity.

@OneToMany
    @JoinTable(
            name="USER_CAR",
            joinColumns = @JoinColumn( name="username"),
            inverseJoinColumns = @JoinColumn( name="car_id")
    )
private Set<Car> cars = new HashSet<>();    

Looks like I fixed it, by creating a third column in the jointable, which autoincrements and works as primary key. However now it inserts everything more than twice. If any knows a simple fix, I'd glady hear it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM