简体   繁体   中英

How to check the value and retrieve it from database if it exists using Hibernate?

It's a simple question, but I'm new to Hibernate and working in Hibernate 4.2.7. Here is my scenario.

I have a list of product codes so I'm looping through the values like:

Vector<productslist> p = prodcts.getlists();
int size = p.size();
for (int i = 0; i < size; i++) {
    productslist pl = p.elementAt(i) 
    p.setProductcode(pl.getProductcode());
    p.setProductName(pl.getProductName()); 
    session.save(p);
}


Before inserting into database I need to check if the productcode exists in the database. If not I can insert the values, if it exists I need to return back the productID for that productcode.

productID is auto-generated by database.

Please advise how to achieve this.

You can use HQL to do this; try something like "from products where lower(productcode) = " + productCode . Here are some tutorials on HQL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM