Pergunta

I created a simple table like below.

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)
);

Then I created a mapping for this table with this mapping file

<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>

I then created a simple class like below to access the 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;
    }
}

The Customer class is just a POJO

public class Customer {
    private int customerID;
    private String customerName;
    private String region;
    //getters setters
}

But it does not bind to the generated key at the table.

public class Starter {
    public static void main(String[] args) {
        List<Customer> lstCust = daoCust.getAllCustomer();
        for (Customer cust : lstCust) {
            System.out.println(cust);
        }
    }
}

The output is like these?

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

Did I miss something in my mapping? Adding customer has no problem but retrieving the auto generated key has.

Foi útil?

Solução

I think the missing name attribute for id tag in you hbm file could be the issue:

<id  type="int" column="CUST_ID" name="customerID">
        <generator class="native"></generator>
    </id>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top