增:
package com.maya.test;import org.hibernate.*;import org.hibernate.cfg.*;import com.maya.model.Family; public class Test2 { public static void main(String[] args) { Configuration config=new Configuration().configure(); SessionFactory factory=config.buildSessionFactory(); Session session=factory.openSession(); //增加 Family family=new Family(); family.setInfoCode("p004"); family.setName("张三"); family.setTitle("T003"); family.setFirm("齐鲁石化济南分公司"); family.setOrders(4); try{ session.beginTransaction(); //事务开始 session.save(family); session.getTransaction().commit(); //事务提交 } catch(Exception e){ session.getTransaction().rollback();//如果发生错误,事务回滚 } session.close();//关闭session } }
Hibernate框架自动生成如下语句,将数据插入数据库中
查询
package com.maya.test;import java.util.List;import org.hibernate.*;import org.hibernate.cfg.*;import com.maya.model.Family; public class Test2 { public static void main(String[] args) { Configuration config=new Configuration().configure(); SessionFactory factory=config.buildSessionFactory(); Session session=factory.openSession(); // //查询(根据主键来查)// Family fa=session.load(Family.class, 11);// if(fa!=null){// System.out.println(fa.getName()+" "+fa.getInfoCode());// } Listlist=session.createQuery("from Family").getResultList(); //这里的Family对应的是实体类,不是sql语句中的family for(Family fa:list){ System.out.println(fa.getName()+" "+fa.getInfoCode()); } session.close();//关闭session } }
查询结果如下:SQL语句自动生成
删除:
package com.maya.test;import java.util.List;import org.hibernate.*;import org.hibernate.cfg.*;import com.maya.model.Family; public class Test2 { public static void main(String[] args) { Configuration config=new Configuration().configure(); SessionFactory factory=config.buildSessionFactory(); Session session=factory.openSession(); Family fa=session.get(Family.class,13); //先查询 if(fa!=null){ session.beginTransaction(); session.delete(fa); //后删除 session.getTransaction().commit();; } session.close();//关闭session } }
改
package com.maya.test;import java.util.List;import org.hibernate.*;import org.hibernate.cfg.*;import com.maya.model.Family; public class Test2 { public static void main(String[] args) { Configuration config=new Configuration().configure(); SessionFactory factory=config.buildSessionFactory(); Session session=factory.openSession(); Family fa=session.get(Family.class,10); //先查询 if(fa!=null){ session.beginTransaction(); fa.setName("盲僧"); fa.setFirm("召唤师峡谷"); session.update(fa); session.getTransaction().commit(); } session.close();//关闭session } }