首页 > 解决方案 > 如何使用@Query 在 JPA 中获取自动生成的密钥?

问题描述

有没有办法通过使用查询来获取自动生成的主键。

    @Modifying
    @Query(value = "Insert into device_menu(MenuName,ICON,Type,TenantID,ParentID) Values (:menuName,:icon,:type,:tenantId,:parentId)", nativeQuery = true)
    int createMenu(@Param("menuName") String name, @Param("icon") String icon, @Param("type") int type,
            @Param("tenantId") int tenantId, @Param("parentId") int parentId);

下面是实体类。

@Entity
@Table(name = "deviceMenu")
public class Menu {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "menu_id")
private int id;

@NotBlank
private int parentId;
@NotBlank
private int type;
private String menuName;
private String iconURL;
@Column(name = "form_uuid")
private String formUUID;
private String searchId;
private byte IsActive;
@Column(name = "tenant_id")
private int tenantId;
@NotBlank
private int sortOrder;
private String[] formList;
@ElementCollection
@CollectionTable(name = "device_menu_privilege", joinColumns = @JoinColumn(name = "menu_id", referencedColumnName = "menu_id"))
private int[] roleId;

我没有使用实体管理器或预定义的方法,因为我必须只将数据存储在选定的列中,而且我必须实现这样的分层嵌套对象

{
  "menuId": 1,
  "menuName": "Inspection",
  "icon": "https://s3.ap-south-1.amazonaws.com/front-man/beta/170b090b-1424-4c78-8def-e57d39436a27/DeviceMenu/185febd1-f2b8-4d39-b3a2-f5dd0e6be40c.png",
  "type": 1,
  "formId": 0,
  "formUUID": null,
  "formName": null,
  "parentId": 0,
  "menu": [
    {
      "menuId": 440,
      "menuName": null,
      "icon": null,
      "type": 2,
      "formId": 0,
      "formUUID": "2f84a801-cc3e-4807-a68c-cdd3cc9df9af",
      "formName": "Production Line",
      "parentId": 1,
      "menu": [
        {
          "menuId": 450,
          "menuName": null,
          "icon": null,
          "type": 2,
          "formId": 0,
          "formUUID": "41e8e326-000a-4d8a-abb6-ece29b80a9c5",
          "formName": "Inspection Form",
          "parentId": 3,
          "menu": null
        }
      ]
    }
  ]
}

标签: javaspringjpahierarchy

解决方案


我不明白你为什么不使用预定义的save方法。在这两种情况下(那个和你的),未通知的列将被保存为空值。

无论如何,¿您是否尝试过返回 Entity 而不是 int?

@Modifying
@Query(value = "Insert into device_menu(MenuName,ICON,Type,TenantID,ParentID) Values (:menuName,:icon,:type,:tenantId,:parentId)", nativeQuery = true)
Menu createMenu(@Param("menuName") String name, @Param("icon") String icon, @Param("type") int type,
        @Param("tenantId") int tenantId, @Param("parentId") int parentId);

推荐阅读