首页 > 解决方案 > 使用 JPA 获取数据库用户并在 Entity Attribute 中设置

问题描述

我是 JPA 的新手。我在数据库中有这些表,其中 Created_By 列不可为空。问题是我有一个约束问题,因为这个值不能为空。

数据库:Oracle 11G 应用服务器:IBM Websphere 使用 JNDI 作为数据源事务表:

Customer_Id | Amount | Status  | Created_BY   | Created_Date  |
1           | 10    | Pending  |   (USER)     |  (new Date()) |

在我的 Java 代码中,我没有设置 CreatedBy 和属性,因为它们在我的数据库脚本中默认为日期是 SYSDATE。

Customers customer = new Customer();
customer.setCustomerId(12324);
customer.setAmount(10);
customer.setStatus(StatusType.PENDING.getName());
customer.setCreatedDate(new Date());

无论如何我可以使用 JPA 从数据库中的用户吗?不使用本机查询“从 Dual 中选择用户”。

标签: javajpaoracle11gpersistence

解决方案


我可以按照下面的代码获取连接用户名。

 EntityManagerFactoryInfo info = (EntityManagerFactoryInfo) em.getEntityManagerFactory();
 String userName = info.getPersistenceUnitInfo().getNonJtaDataSource().getConnection().getMetaData().getUserName();

推荐阅读