简体   繁体   中英

foreign key constraint fails - hibernate

I have problem when i try add data to table USERS. First my DB and classes.

DB structure:

CREATE TABLE IF NOT EXISTS `admins` (
  `ADMIN_ID` int(10) unsigned NOT NULL AUTO_INCREMENT ,
  `USERNAME` varchar(45) NOT NULL, 
  `PASSWORD` varchar(45) NOT NULL,
  `AUTHORITY` varchar(45) NOT NULL,
  PRIMARY KEY (`ADMIN_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `lecturers` (
  `LECTURER_ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `NAME` varchar(45) NOT NULL,
  `SURNAME` varchar(45) NOT NULL,
  `TITLES` varchar(45) NOT NULL,
  `USERNAME` varchar(45) NOT NULL,
  `PASSWORD` varchar(45) NOT NULL,
  `AUTHORITY` varchar(45) NOT NULL,
  `LEC_DESCRIPTION` varchar(100) NOT NULL,
  PRIMARY KEY (`LECTURER_ID`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=40;

CREATE TABLE IF NOT EXISTS `roles_name` (
  `role_id` int(1) NOT NULL,
  `authority` varchar(45) NOT NULL,
  UNIQUE KEY `role_id` (`role_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `roles_name` (`role_id`, `authority`) VALUES
(1, 'ROLE_ADMIN'),
(2, 'ROLE_USER'),
(3, 'ROLE_LECTURER');

CREATE TABLE IF NOT EXISTS `users` (
  `USER_ID` int(10) unsigned NOT NULL AUTO_INCREMENT ,
  `NAME` varchar(45) NOT NULL,
  `SURNAME` varchar(45) NOT NULL,
  `username` varchar(45) NOT NULL,
  `PASSWORD` varchar(45) NOT NULL,
  `USER_DESCRIPTION` varchar(100) NOT NULL,
  `AUTHORITY` varchar(45) NOT NULL,
  `ENABLED` tinyint(1) NOT NULL,
  PRIMARY KEY (`USER_ID`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=50000;

CREATE TABLE IF NOT EXISTS `roles_map` (
  `rm_id` int(10) unsigned NOT NULL,
  `user_id` int(10) unsigned,
  `admin_id` int(10) unsigned,
  `lecturer_id` int(10) unsigned,
  `username` varchar(45) NOT NULL,
  `password` varchar(45) NOT NULL,
  `role_id` int(1) NOT NULL,
  PRIMARY KEY (`rm_id`),
  FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`),
  FOREIGN KEY (`lecturer_id`) REFERENCES `lecturers` (`lecturer_id`),
  FOREIGN KEY (`admin_id`) REFERENCES `admins` (`admin_id`),
  FOREIGN KEY (`role_id`) REFERENCES `roles_name` (`role_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

RolesMap.java

@Entity
@Table(name = "roles_map")
public class RolesMap {
    @Id
    @Column(name = "RM_ID", unique = true, nullable = false)
    private int rm_id;
    //@Column(name = "USER_ID", unique = true)
    //private int user_id;
    @Column(name = "ADMIN_ID", unique = true)
    private int admin_id;
    @Column(name = "LECTURER_ID", unique = true)
    private int lecturer_id;
    @Column(name = "USERNAME", unique = true, nullable = false)
    private String username;
    @Column(name = "PASSWORD", unique = true, nullable = false)
    private String password;
    @Column(name = "ROLE_ID", unique = true, nullable = false)
    private int role_id;
    @ManyToOne(cascade={CascadeType.ALL})
    @JoinColumn(name = "user_id")
    private User user;

     //getters and setters

}

User.java

@Entity
@Table(name = "users")
public class User {
    @Id
    @Column(name = "USER_ID", unique = true, nullable = false)
    private int user_id;
    @Column(name = "NAME", nullable = false)
    private String name;
    @Column(name = "SURNAME", unique = true, nullable = false)
    private String surname;
    @Column(name = "USERNAME", unique = true, nullable = false)
    private String username; // zamiast username
    @Column(name = "PASSWORD", unique = true, nullable = false)
    private String password;
    @Column(name = "USER_DESCRIPTION", nullable = false)
    private String userDescription;
    @Column(name = "AUTHORITY", nullable = false)
    private String authority = "ROLE_USER";
    @Column(name = "ENABLED", nullable = false)
    private int enabled;

    @OneToMany(mappedBy="user", cascade=CascadeType.ALL)
    private List <RolesMap> rolesMap;

      //getters and setters
}

adding method

public String addUser() {

    Session sess = null;

    try {
        sess = UserDao.getSessionFactory().openSession();
        sess.beginTransaction();
        RolesMap roles = new RolesMap();
        //roles.setrUser(user);
        User user = new User();
        roles.setPassword(getPassword());
        roles.setRole_id(2);
        roles.setUsername(getUsername());

        user.setName(getName());
        user.setSurname(getSurname());
        user.setUsername(getUsername());
        user.setPassword(getPassword());
        user.setUserDescription(getUserDescription());
        user.setAuthority(getAuthority());
        user.setEnabled(getEnabled());
        user.setRolesMap(new ArrayList<RolesMap>());
        user.getRolesMap().add(roles);
        sess.save(user);
        sess.getTransaction().commit();
        //getUserService().addUser(user);

        return SUCCESS;
    } catch (DataAccessException e) {
        e.printStackTrace();
    }

    return ERROR;
}

When I try use this method I have error: Cannot add or update a child row: a foreign key constraint fails ( soeOne2 . roles_map , CONSTRAINT roles_map_ibfk_2 FOREIGN KEY ( lecturer_id ) REFERENCES lecturers ( LECTURER_ID ))

But I do not know why, because I'm trying to add data to the USER and ROLESMAP tables. I think when you add data to a table ROLESMAP/USER field lecturer_id and admin_id in ROLESMAP table shuld be NULL. Can anyone tell me what I'm doing wrong?

It is because lecturer_id=0 is NOT lecturer_id=null .

Your application try to save lecturer_id=0 and the database think that 0 is the ID of an item in table lecturers .

So the first workarround is to replace the int with Integer , so that you can assign lecturer_id = null

@Column(name = "LECTURER_ID", unique = true)
private Integer lecturer_id;

And I think you need this modification for all other references that work the same way.


The second point is, that the way you map references between entities is not the jpa (hibernate) way. I strongly recommend that you read something about mapping relations (OneToOne, OneToMany, ManyToOne, ManyToMany) For example the Hibernate Reference Chapter 7. Collection mapping and 8. Association Mappings

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