java - 如何使用@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
}
]
}
]
}
解决方案
我不明白你为什么不使用预定义的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);
推荐阅读
- java - 无法在 RecyclerView 中显示从 Firebase 检索到的数据
- powershell - Powershell 脚本杀死所有 3 分钟无响应的 PID
- c# - 如何在 Startup.cs 中配置我自己的 NuGet 包
- revit-api - RevitAPI:如何更改族的零件类型?
- python - 为什么'=='比在Python3中手动遍历两个字符串比较快?
- reactjs - 无法访问该状态,但我在调试器上看到它
- electron - 如何获取在 Electron 的 web 视图中打开的页面的 HTTP 状态代码
- ios - 如何在swift中使用带有PKCS5PADDING的AES-256 CFB解密字符串?
- machine-learning - 如何基于微调的 VGGNet16 创建子模型
- java - IntelliJ 2019.3 中的 Gradle 多模块构建的注释处理器配置似乎无法正常工作