简体   繁体   中英

How to configure Spring Boot one to many entity relationship

In my rest API, I have Role and RolePrivilege entities with @Entity annotation. There are some columns in each entity. I need to set a one-to-many relationship with these two. One role has many role privileges and one role privilege can only have one role. In my DB script file, I set it as

-- -----------------------------------------------------
-- Table `wdc`.`role`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `wdc`.`role` (
  `roleId` INT NOT NULL AUTO_INCREMENT ,
  `roleName` VARCHAR(45) NOT NULL ,
  `disabled` INT(1) ZEROFILL NULL ,
  PRIMARY KEY (`roleId`))
  ENGINE = InnoDB
  DEFAULT CHARACTER SET = utf8;

-- -----------------------------------------------------
-- Table `wdc`.`rolePrivileges`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `wdc`.`rolePrivileges` (
  `privilegeId` INT NOT NULL AUTO_INCREMENT ,
  `privilegeDescription` VARCHAR(45) NOT NULL ,
  `roleId` INT NULL ,
  `disabled` INT(1) ZEROFILL NULL ,
  `lastModifiedUser` VARCHAR(30) NULL DEFAULT NULL,
  `lastModifiedDateTime` DATETIME NULL DEFAULT NULL,
  PRIMARY KEY (`privilegeId`),
  FOREIGN KEY (`roleId`)
  REFERENCES `wdc`.`role` (`roleId`)
    ON UPDATE CASCADE)
  ENGINE = InnoDB
  DEFAULT CHARACTER SET = utf8;

This creates database fine. I created Role entity as follows,

@Entity
@Table(name = "role", schema = "wdc", catalog = "")
public class Role implements Serializable {

    @Id
    @Column(name = "roleid", nullable = false, unique = true)
    @GeneratedValue(strategy=GenerationType.IDENTITY)

    @OneToMany(mappedBy = "role", cascade = CascadeType.ALL)
    private Set<RolePrivilege> rolePrivileges;

    public Role(int roleId, String roleName, Integer disabled, RolePrivilege rolePrivileges) {
        this.roleId = roleId;
        this.roleName = roleName;
        this.disabled = disabled;
        this.rolePrivileges = Stream.of(rolePrivileges).collect(Collectors.toSet());
        this.rolePrivileges.forEach(x -> x.setRoleId(this));
    }
}

RolePrivilege entity as follows,

@Entity
@Table(name = "roleprivileges", schema = "wdc", catalog = "")
public class RolePrivilege implements Serializable {

    @Id
    @Column(name = "privilegeid")
    @GeneratedValue(strategy = GenerationType.IDENTITY)

    @ManyToOne
    @JoinColumn
    private Role role;

    public RolePrivilege(int privilegeId, String privilegeDescription, Integer disabled, String lastModifiedUser, Timestamp lastModifiedDateTime) {
        this.privilegeId = privilegeId;
        this.privilegeDescription = privilegeDescription;
        this.disabled = disabled;
        this.lastModifiedUser = lastModifiedUser;
        this.lastModifiedDateTime = lastModifiedDateTime;
    }
}

I used CrudRepository interface to save new entries to database.

@Repository
public interface RoleRepository extends CrudRepository<Role, Integer> {
}

@Repository
public interface RolePrivilegeRepository extends CrudRepository<RolePrivilege, Integer> {
}

This is my service file for add new role privilege,

// ---------------------------------
// add new role privilege
// ---------------------------------
public String addRolePrivilege(RolePrivilege rolePrivilege){

     try {
        rolePrivilegesRepository.save(rolePrivilege);
        return "Saved";
    } catch (Exception e){
        return "Failed";
    }
}

As last I used Controller file as this,

// ---------------------------------
// add new role privilege to database
// ---------------------------------
@PostMapping(path = "/")
public @ResponseBody String addRolePrivilege(@RequestBody RolePrivilege rolePrivilege){

 return rolePrivilegesService.addRolePrivilege(rolePrivilege);
}

But still when I trying to save new role privilege it saves with out roleId in rolePrivilege table.

I tried it this way,

{
    "privilegeDescription": "add user",
    "role": [
        {
            "roleId": "1",
            "roleName": "user1",
            "disabled": 0
        }
        ],
    "disabled": 0,
    "lastModifiedUser": "1",
    "lastModifiedDateTime": "2020-03-11T17:58:14.361+0000"
}

Where do I need to change? Please help me.

When I send request to save new role privilege it returns saved but when I check it with mysql workbench, the roleId column in emplty.

You have a raw @JoinColumn in RolePrivilege , change it, so that the name of the column is configured: @JoinColumn(name = "roleId") .

Also you're saving RolePrivilege , but the changes are not cascading, change the mapping to:

@ManyToOne(cascade = CascadeType.ALL)

PS: Prefer List s over Set s in -to-many mapping for performance reasons .

Firstly, do not return String(wrap it to class for example to RolePriviligueResponse with String status as response body), secondly you dont need @ResponseBody annotation, your @PostMapping annotation already has it, third - dont use Integer for ID, better use Long type. And you did not provide the name of @JoinColumn(name="roleId")

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