我创建了一个简单的表格,如下所示。
CREATE TABLE CUSTOMERS
(
CUST_ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
CUSTOMER_NAME VARCHAR(24) NOT NULL,
REGION VARCHAR(26),
PRIMARY KEY (CUST_ID)
);
然后,我使用此映射文件为此表创建了一个映射
<class name="Customer" table="CUSTOMERS">
<id type="int" column="CUST_ID" >
<generator class="native"></generator>
</id>
<property name="customerName" type="string" column="CUSTOMER_NAME" />
<property name="region" type="string" column="REGION"/>
</class>
然后,我创建了一个如下所示的简单类来访问数据库。
public class CustomerDao {
public void addCustomer(Customer customer) {
Session session = SessionManager.getSessionFactory()
.getCurrentSession();
session.beginTransaction();
session.saveOrUpdate(customer);
session.getTransaction().commit();
}
public List<Customer> getAllCustomer() {
Session session = SessionManager.getSessionFactory()
.getCurrentSession();
session.beginTransaction();
List<Customer> booksList = session.createQuery("from Customer").list();
session.getTransaction().commit();
return booksList;
}
}
客户类只是一个POJO
public class Customer {
private int customerID;
private String customerName;
private String region;
//getters setters
}
但是它不绑定到表上生成的键。
public class Starter {
public static void main(String[] args) {
List<Customer> lstCust = daoCust.getAllCustomer();
for (Customer cust : lstCust) {
System.out.println(cust);
}
}
}
输出是这样的吗?
Customer Details:
------------
Customer ID:0
Customer Name: Symera
Region:Asia
Customer Details:
------------
Customer ID:0
Customer Name: Indra
Region:US
Customer Details:
------------
Customer ID:0
Customer Name:Istaf
Region:US
我在地图中错过了什么吗?添加客户没有问题,但是检索自动生成的密钥有问题。
最佳答案
我认为您的hbm文件中缺少ID标签的name属性可能是问题所在:
<id type="int" column="CUST_ID" name="customerID">
<generator class="native"></generator>
</id>
关于java - 无法在 hibernate 中检索自动生成的 key ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4530833/