First, add new records to the database by instantiating objects
package com.yh.test; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.junit.Test; import com.yh.entity.Buyer; public class Demo { @Test public void doAdd() { SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); Buyer buyer = new Buyer(); buyer.setUsername("yehuan"); buyer.setPassword("123"); session.save(buyer); transaction.commit(); session.close(); sessionFactory.close(); } }
Second, by way of example of the object updates the corresponding database record
Similar code, only the save () method to change update () method, updates to the primary key attribute mapping condition.
Note: Both () method saveOrUpdate apply.
Third, the corresponding record is deleted in the database by instantiating objects
Similar code, only the save () method into delete () method, in order to delete the primary key attribute mapping condition.
Fourth, the records in the database query
1. The primary key attribute corresponding to the query (a single object can be used to instantiate)
By get () and load () method
@Test public void doSingleQuery() { SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); Buyer buyer = session.load(Buyer.class,"yehuan1"); System.out.println(buyer.getPassword()); session.close(); sessionFactory.close(); }
The other attributes query (available for instantiation objects)
@Test public void doSimpleSingleQuery() { SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); Criteria criteria = session.createCriteria(Buyer.class); criteria.add(Restrictions.eq("username", "yehuan1")); @SuppressWarnings("unchecked") List<Buyer> list = criteria.list(); for(Buyer b:list){ System.out.println(b); } transaction.commit(); session.close(); sessionFactory.close(); }
3. Query table all records corresponding to a class (a plurality of objects are available for instantiation)
By the createQuery () and createSQLQuery () and
@Test public void doAllQuery() { SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); String hql="from Buyer"; Query query = session.createQuery(hql); @SuppressWarnings("unchecked") List<Buyer> list = query.list(); for(Buyer b:list){ System.out.println(b); // 调用Buyer类中的toString()方法 } transaction.commit(); session.close(); sessionFactory.close(); }