简体   繁体   中英

Hibernate OneToOne Relationship: Unable to delete the child table

Let's say we are living in a world a person could have only one vehicle(Forgive me for my lame example)

Let's say I have this UserDetails Class

public class UserDetails {

    @Id
    @GeneratedValue
    @Column(name = "USER_ID")
    private int id;
    @Column(name = "USER_NAME")
    private String name;
    @OneToOne
    private Vehicle vehicle;

    public Vehicle getVehicle() {
        return  vehicle;
    }

    public void setVehicle(Vehicle  vehicle) {
        this.vehicle =  vehicle;
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

And this is My Vehicle class

@Entity
public class Vehicle {
    @Id
    @GeneratedValue
    private long vechile_id;
    private String vehicleName;
    public long getVechile_id() {
        return vechile_id;
    }
    public void setVechile_id(long vechile_id) {
        this.vechile_id = vechile_id;
    }

    public String getVehicleName() {
        return vehicleName;
    }
    public void setVehicleName(String vehicleName) {
        this.vehicleName = vehicleName;
    }   
}

Upon Saving it to the database it works fine, but when I went to delete the Table for vehicle this error showed up on my workbench

NOTE That there are only one entries on both UserDetails and Vehicle Table.

ERROR 1217: Cannot delete or update a parent row: a foreign key constraint fails

SQL Statement:

drop table `hibernate`.`vehicle`

How come am I not allowed to drop the table? Should I delete The UserDetails table first?

If you'd delete the Vehicle table, that would make the UserDetails table loose it's referential integrity because the vehicle column's foreign keys would point to nowhere. Drop the fk constraint or the vehicle column from UserDetails then you can delete the table you want.

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