Java jdbc模板&x2B;MySQL主键到外键

Java jdbc模板&x2B;MySQL主键到外键,java,mysql,jdbc,spring-jdbc,Java,Mysql,Jdbc,Spring Jdbc,我对JDBC以及它如何使用数据库还不熟悉。我们看到了一个示例,但没有数据库,也没有显示任何工作功能。我要做的是同时创建一个用户名和一个用户 必须首先创建用户名,因为它包含主键。我遇到的问题是,当我创建用户和用户名时,username的user表中的外键为null CREATE TABLE `username` ( `UserNameId` int(11) NOT NULL AUTO_INCREMENT, `UserName` varchar(55) DEFAULT NULL, `Passwo

我对JDBC以及它如何使用数据库还不熟悉。我们看到了一个示例,但没有数据库,也没有显示任何工作功能。我要做的是同时创建一个用户名和一个用户

必须首先创建用户名,因为它包含主键。我遇到的问题是,当我创建用户和用户名时,username的user表中的外键为null

CREATE TABLE `username` ( `UserNameId` int(11) NOT NULL AUTO_INCREMENT, `UserName` varchar(55) DEFAULT NULL,   `Password` varchar(100) DEFAULT NULL `RoleId` int(11) DEFAULT NULL,`enabled` tinyint(4) DEFAULT '1',PRIMARY KEY (`UserNameId`),KEY `fkrole_idx` (`RoleId`),CONSTRAINT `fkrole` FOREIGN KEY (`RoleId`) REFERENCES `role` (`roleId`) ON DELETE NO ACTION ON UPDATE NO ACTION ENGINE=InnoDB AUTO_INCREMENT=38 DEFAULT CHARSET=utf8;


CREATE TABLE `user` (`UserID` int(11) NOT NULL AUTO_INCREMENT, `FirstName` varchar(55) DEFAULT NULL, `LastName` varchar(55) DEFAULT NULL,`BirthDate` date DEFAULT NULL,`Address` varchar(55) DEFAULT NULL,`StateId` int(11) DEFAULT NULL,`Zip` int(9) DEFAULT NULL,`EducationID` int(11) DEFAULT NULL,`UserNameID` int(11) DEFAULT NULL,`Email` varchar(55) DEFAULT NULL,`PhoneNumber` varchar(55) DEFAULT NULL,`description` varchar(500) DEFAULT NULL,`Resume` varchar(4000) DEFAULT NULL,PRIMARY KEY (`UserID`),UNIQUE KEY`UserNameID_UNIQUE` (`UserNameID`),KEY `fkstateID`(`StateId`),KEY`fkeducationID` (`EducationID`),KEY `fkusername` (`UserID`),KEY `fkusernameID_idx` (`UserNameID`),CONSTRAINT `fkeducationID` FOREIGN KEY(`EducationID`) REFERENCES `education` (`EducationId`) ON DELETE NO ACTION ON UPDATE NO ACTION,CONSTRAINT `fkstateID` FOREIGN KEY (`StateId`) REFERENCES `state` (`StateId`) ON DELETE NO ACTION ON UPDATE NO ACTION,CONSTRAINT `fkusernameID` FOREIGN KEY (`UserNameID`) REFERENCES `username` (`UserNameId`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE=InnoDB AUTO_INCREMENT=144 DEFAULT CHARSET=utf8;

private static final String INSERT_USER = "INSERT INTO USER (`firstName`, `lastName`, `birthdate`,`address`,`stateid`,`zip`,`educationId`,`userNameId`,`email`,`phoneNumber`,`description`) VALUES (?,?,?,?,?,?,?,?,?,?,?);";
private static final String INSERT_USERNAME = "INSERT INTO USERNAME (`userName`, `password`, `roleId`,`enabled`) VALUES (?,?,?,?)";


@Override
public void add(UserName userName) {
    this.jdbcTemplate.update(INSERT_USERNAME, 
            userName.getUserName(),
            userName.getPassword(),
            userName.getRole().getRoleId(),
            userName.isEnabled());
}

@Override
public void add(User user) {
    this.jdbcTemplate.update(INSERT_USER,user.getFirstName(),
            user.getLastName(),user.getBirthdate(),user.getAddress(),user.getState().getStateId(),
            user.getZip(),user.getEducation().getEducationId(),user.getUserName().getUserNameId(),user.getEmail(),user.getPhoneNumber(),
            user.getDescription());
}
public class UserNameRowMapper implements RowMapper<UserName> {

private static final int USERNAMEID_FIELD = 1;
private static final int USERNAME_USERNAME_FIELD = 2;
private static final int USERNAME_PASSWORD_FIELD = 3;
private static final int USERNAME_ROLE_FIELD = 4;
private static final int USERNAME_ENABLED_FIELD = 5;

@Override
public UserName mapRow(ResultSet rs, int rowNum) throws SQLException {
    UserName userName = new UserName();
    userName.setUserNameId(rs.getInt(USERNAMEID_FIELD));
    userName.setUserName(rs.getString(USERNAME_USERNAME_FIELD));
    userName.setPassword(rs.getString(USERNAME_PASSWORD_FIELD));
    Role role = new Role();
        role.setRoleId(rs.getInt(USERNAME_ROLE_FIELD));
    userName.setRole(role);
    userName.setEnabled(rs.getBoolean(USERNAME_ENABLED_FIELD));
    return userName;
}

public class UserRowMapper implements RowMapper<User> {

private static final int USERID_FIELD = 1;
private static final int USER_FIRSTNAME_FIELD = 2;
private static final int USER_LASTNAME_FIELD = 3;
private static final int USER_BIRTHDATE_FIELD = 4;
private static final int USER_ADDRESS_FIELD = 5;
private static final int USER_STATE_FIELD = 6;
private static final int USER_ZIP_FIELD = 7;
private static final int USER_EDUCATION_FIELD = 8;
private static final int USERNAME_FIELD = 9;
private static final int USER_EMAIL_FIELD = 10;
private static final int USER_PHONENUMBER_FIELD = 11;
private static final int USER_DESCRIPTION_FIELD = 12;

@Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
    User user = new User();
        user.setUserId(rs.getInt(USERID_FIELD));
        user.setFirstName(rs.getString(USER_FIRSTNAME_FIELD));
        user.setLastName(rs.getString(USER_LASTNAME_FIELD));
        user.setBirthdate(rs.getDate(USER_BIRTHDATE_FIELD));
        user.setAddress(rs.getString(USER_ADDRESS_FIELD));
        State state = new State();
            state.setStateId(USER_STATE_FIELD);
        user.setState(state);
        user.setZip(rs.getInt(USER_ZIP_FIELD));
        Education education = new Education();
        education.setEducationId(rs.getInt(USER_EDUCATION_FIELD));
            user.setEducation(education);
        Integer userNameID = rs.getInt(USERNAME_FIELD);
          if (userNameID != 0) {
              UserName username = new UserName();
              username.setUserNameId(userNameID);
              user.setUserName(username);

          }
        user.setEmail(rs.getString(USER_EMAIL_FIELD));
        user.setPhoneNumber(rs.getString(USER_PHONENUMBER_FIELD));
        user.setDescription(rs.getString(USER_DESCRIPTION_FIELD));

    return user;
}

@Override
public void add(User user) {
    user.getUserName().setPassword(encoder.encode(user.getUserName().getPassword()));
    unDao.add(user.getUserName());

    userDao.add(user);

}
创建表`username`(`UserNameId`int(11)非空自动递增,`username`varchar(55)默认为空,`Password`varchar(100)默认为空`RoleId`int(11)默认为空,`enabled`tinyint(4)默认为'1',主键(`UserNameId`),键`fkrole`idx`(`RoleId`),约束`fkrole`外键(`RoleId`)引用`role`(`RoleId`)删除时无操作更新时无操作引擎=InnoDB AUTO_INCREMENT=38默认字符集=utf8;
创建表`user`(`UserID`int(11)非空自动增量,`FirstName`varchar(55)默认空,`LastName`varchar(55)默认空,`BirthDate`date默认空,`Address`varchar(55)默认空,`StateId`int(11)默认空,`Zip`int(9)默认空,`EducationID`int(11)默认空,`UserNameID`int(11)默认空,`Email`varchar(55)默认为空,`PhoneNumber`varchar(55)默认为空,`description`varchar(500)默认为空,`Resume`varchar(4000)默认为空,主键(`UserID`),唯一键`UserNameID\u UNIQUE`(`UserNameID`),键`fkstateID`(`StateId`),键`fkeducationID`(`EducationID`),键`fkusernameID`(`UserNameID`),约束'fkeducationID'外键('EducationID`)在删除时引用'education`('EducationID`)在更新时不执行任何操作,约束'fkstateID`外键('StateId`)在删除时引用'state`('StateId`)在更新时不执行任何操作,约束'fkusernameID`外键('UserNameID`)在更新时引用'UserNameID`('UserNameID`)在删除时无操作在更新时无操作)引擎=InnoDB自动增量=144默认字符集=utf8;
private static final String INSERT_USER=“INSERT INTO USER(`firstName`、`lastName`、`birthdate`、`address`、`stateid`、`zip`、`educationId`、`userNameId`、`email`、`phoneNumber`、`description`)值(?,,,,,,,,,,,,,,,,,?);”;
私有静态最终字符串INSERT_USERNAME=“插入用户名(`USERNAME`、`password`、`roleId`、`enabled`)值(?,,?,?)”;
@凌驾
公共无效添加(用户名){
此.jdbcTemplate.update(插入\u用户名,
userName.getUserName(),
userName.getPassword(),
userName.getRole().getRoleId(),
userName.isEnabled());
}
@凌驾
公共无效添加(用户){
此.jdbcTemplate.update(插入_USER,USER.getFirstName(),
user.getLastName(),user.getBirthdate(),user.getAddress(),user.getState().getStateId(),
user.getZip()、user.getEducation().getEducationId()、user.getUserName().getUserNameId()、user.getEmail()、user.getPhoneNumber(),
user.getDescription());
}
公共类UserNameRowMapper实现了RowMapper{
私有静态final int USERNAMEID_字段=1;
私有静态最终整数用户名\用户名\字段=2;
私有静态最终整数用户名\密码\字段=3;
私有静态最终int用户名\角色\字段=4;
私有静态最终整数用户名\启用\字段=5;
@凌驾
公共用户名mapRow(ResultSet rs,int rowNum)引发SQLException{
用户名=新用户名();
userName.setUserNameId(rs.getInt(USERNAMEID_字段));
userName.setUserName(rs.getString(userName\u userName\u字段));
userName.setPassword(rs.getString(userName\u PASSWORD\u字段));
角色=新角色();
role.setRoleId(rs.getInt(用户名\角色\字段));
userName.setRole(角色);
userName.setEnabled(rs.getBoolean(userName_ENABLED_字段));
返回用户名;
}
公共类UserRowMapper实现了RowMapper{
私有静态最终int USERID_字段=1;
私有静态final int USER_FIRSTNAME_FIELD=2;
私有静态final int USER_LASTNAME_FIELD=3;
私有静态最终整数用户\出生日期\字段=4;
私有静态最终整数用户地址字段=5;
私有静态最终整数用户\状态\字段=6;
私有静态final int USER_ZIP_字段=7;
私有静态最终整数用户\教育\字段=8;
私有静态最终整数用户名\字段=9;
私有静态最终整数用户\电子邮件\字段=10;
私有静态最终整数用户\电话号码\字段=11;
私有静态最终整数用户描述字段=12;
@凌驾
公共用户mapRow(ResultSet rs,int rowNum)抛出SQLException{
用户=新用户();
user.setUserId(rs.getInt(USERID_字段));
user.setFirstName(rs.getString(user_FIRSTNAME_字段));
user.setLastName(rs.getString(user\u LASTNAME\u字段));
user.setBirthdate(rs.getDate(user\u BIRTHDATE\u字段));
user.setAddress(rs.getString(用户地址字段));
状态=新状态();
state.setStateId(用户\状态\字段);
user.setState(状态);
user.setZip(rs.getInt(user_ZIP_字段));
教育=新教育();
教育.setEducationId(rs.getInt(用户教育字段));
用户教育(教育);
整数userNameID=rs.getInt(USERNAME\u字段);
如果(userNameID!=0){
用户名=新用户名();
username.setUserNameId(userNameID);
user.setUserName(用户名);
}
user.setEmail(rs.getString(user_EMAIL_字段));
user.setPhoneNumber(rs.getString(user\u PHONENUMBER\u字段));
user.setDescription(rs.getString(用户描述字段));
返回用户;
}
@凌驾
公共无效添加(用户){
user.getUserName().setPassword(encoder.encode(user.getUserName().getPassword());
unDao.add(user.getUserName());
添加(用户);
}

因为用户名id是在数据库端生成的(使用
自动增量

您需要使用
GeneratedKeyHolder
检索生成的p
`UserNameId` int(11) NOT NULL AUTO_INCREMENT
@Override
public Number add(UserName userName) {
    KeyHolder holder = new GeneratedKeyHolder();
    this.jdbcTemplate.update(
        new PreparedStatementCreator() {
          public PreparedStatement createPreparedStatement(Connection connection)
                                                            throws SQLException {
            PreparedStatement pstmt = connection.prepareStatement(
                                      INSERT_USERNAME, new String[] {"UserNameId"});
            pstmt.setString(1, userName.getUserName());
            pstmt.setString(2, userName.getPassword());
            pstmt.setInt(3, userName.getRole().getRoleId());
            pstmt.setBoolean(4, userName.isEnabled());
            return pstmt;
          }
        }, holder);
    Number key = holder.getKey();
    userName.setUserNameId(key.intValue());
    return key;
}