休眠状态下的UUID映射

时间:2018-08-24 05:35:49

标签: spring hibernate spring-boot mapping uuid

我已将一个表映射到我的表,并尝试在其中添加一些值。但出现以下错误

  

产生原因:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:   您的SQL语法有误;检查手册   对应于您的MySQL服务器版本以使用正确的语法   '创建,删除,读取,role_id,更新,id)值附近   (第1行的_binary'Ã〜N_WlAsâ\\niÊnÙ'

我的实体是

RoleSettings.java

@Entity @Table(name = "role_settings")
@Getter @Setter @Data
public class RoleSettings implements Serializable {

private static final long serialVersionUID = 8862104773442047690L;

@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "org.hibernate.id.UUIDGenerator")
private UUID id;

@ManyToOne
@JoinColumn(name = "role_id", referencedColumnName = "id", foreignKey = @ForeignKey(name = "role_settings_iam_role_FK"))
private RoleMaster roleId;
}

RoleMaster.java

@Entity @Table(name = "role")
@Getter @Setter @Data
public class RoleMaster implements Serializable {

private static final long serialVersionUID = 1792968151371176640L;

@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "org.hibernate.id.UUIDGenerator")
private UUID id;

@Column(name = "name", nullable = false, length = 255)
private String name;
}

RoleSettingsRepository.java

public interface RoleSettingsRepository extends JpaRepository<RoleSettings, UUID>{}

RoleSettingsService.java

@Service
Class RoleSettingsService {
@Autowired
private RoleSettingsRepository roleSettingsRepository;
public BaseDTO create(RoleSettings roleSettings) {
    BaseDTO response = new BaseDTO();
    RoleSettings newRoleSettings = new RoleSettings();

    try {
        newRoleSettings.setRoleId(roleSettings.getRoleId());
        newRoleSettings.setAppAccessId(roleSettings.getAppAccessId());
        newRoleSettings.setCreate(roleSettings.getCreate());
        newRoleSettings.setUpdate(roleSettings.getUpdate());
        newRoleSettings.setRead(roleSettings.getRead());
        newRoleSettings.setDelete(roleSettings.getDelete());
        roleSettingsRepository.save(newRoleSettings);
        response.setStatusCode(200);
    } catch (Exception e) {
    }
    return response;
}
}

RoleSettingsController.java

@RestController
@RequestMapping("/v1/rolesettings")
public class RoleSettingsController {

@Autowired
private RoleSettingsService roleSettingsService;

@PostMapping("/post")
public BaseDTO create(@RequestBody RoleSettings roleSettings) {
    BaseDTO response = roleSettingsService.create(roleSettings);
    return response;
}
}

我的json对象

{ "roleId" :{"id":  "b2e64c82-ab75-41d3-bb10-e9150f314807"} }

和我的roleId以二进制(16)类型存储在数据库中。

1 个答案:

答案 0 :(得分:1)

检入id列的数据库数据类型。它必须是BINARY(16)。并将您的实体字段注释为:

@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "org.hibernate.id.UUIDGenerator")
@Column(columnDefinition = "BINARY(16)")
private UUID id;

请注意,在这种情况下,您需要添加列定义。