Customer.hbm.xml
hibernate.cfg.xml
com.mysql.jdbc.Driver jdbc:mysql://192.168.137.244:3306/aypak?useUnicode=true&characterEncoding=utf8 root root org.hibernate.dialect.MySQL5Dialect update true false
实例:CRUD
package cn.aypak.a_primer;import java.util.List;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import org.junit.Test;public class App { private static SessionFactory sf = null; static{ Configuration configuration = new Configuration(); configuration.configure("cn/aypak/a_primer/hibernate.cfg.xml"); configuration.addClass(Customer.class); sf = configuration.buildSessionFactory(); } /**新增*/ public void testInsertCustomer(){ Session s = sf.openSession(); Transaction tr = s.beginTransaction(); Customer c = new Customer(); c.setName("小三"); c.setAge(18); c.setDes("专业的"); s.save(c); tr.commit(); s.close(); } /**通过id进行修改*/ public void testUpdateCustomer(){ Session s = sf.openSession(); Transaction tr = s.beginTransaction(); Customer c = new Customer(); c.setId(3); c.setName("小四"); s.update(c); tr.commit(); s.close(); } /**通过id删除客户信息*/ public void testDeleteCustomer(){ Session s = sf.openSession(); Transaction tr = s.beginTransaction(); Customer c = new Customer(); c.setId(2); s.delete(c); tr.commit(); s.close(); } /**通过id查询客户信息*/ public void testQueryCustomer(){ Session s = sf.openSession(); Transaction tr = s.beginTransaction(); Customer c = (Customer) s.get(Customer.class, 1);// Customer c = (Customer) s.load(Customer.class, 1); System.out.println(c.getName()+" "+c.getAge()+" "+c.getDes()); tr.commit(); s.close(); } /**查询所有的客户信息*/ public void testQueryAllCustomer(){ Session s = sf.openSession(); Transaction tr = s.beginTransaction(); /** * s.createQuery("HQL语句"):使用HQL语句查询数据库,返回Query对象 * SQL语句:针对数据库、数据库表、数据库字段 * HQL语句:针对持久化对象、持久化对象的属性 */ Query query = s.createQuery("from Customer"); Listlist = query.list(); for(Customer c:list){ System.out.println(c.getName()+" "+c.getAge()+" "+c.getDes()); } tr.commit(); s.close(); }}