我创建了一个简单的表格,如下所示。
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>
然后我创建了一个简单的类来访问db。
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;
}
}
Customer类只是一个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
我的地图中是否遗漏了一些内容?添加客户没有问题,但检索自动生成的密钥有。
答案 0 :(得分:5)
我认为hbm文件中id标记缺少的name属性可能是问题:
<id type="int" column="CUST_ID" name="customerID">
<generator class="native"></generator>
</id>