6.CUD操作
工具类
public class ConfigUtil { public static SessionFactory sessionFactory; static{ Configuration configuration = new Configuration(); configuration.configure(); sessionFactory = configuration.buildSessionFactory(); } }
CUD操作
public class PersonTest extends ConfigUtil{ @Test public void testQueryPerson(){ Session session = sessionFactory.openSession(); List<Person> personList = session.createQuery("from Person").list(); for(Person person:personList){ System.out.println(person.getPname()); } session.close(); } @Test public void testQueryPersonByID(){ Session session = sessionFactory.openSession(); /** * 按照主键的方式查询数据库表中的记录 * 第二个参数的类型必须和持久化中标示符的类型保持一致 */ Person person = (Person)session.get(Person.class, 1L); System.out.println(person.getPname()); session.close(); } /** * hibernate内部会检查标示符,看标示符中的值在数据库相应的表中有没有对应的记录,如果有,则删除 */ @Test public void testDeletePerson(){ Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); /** * 1、根据id把值从数据库中查找出来 * 2、把对象删除掉 */ //Person person = (Person)session.get(Person.class, 1L); //session.delete(person); /** * 1、新创建一个person对象 * 2、给person对象的标示符赋值 * 3、调用session.delete方法删除 */ Person person = new Person(); //person.setPid(2L); session.delete(person); transaction.commit(); session.close(); } @Test public void testUpdatePerson(){ Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); /** * 1、根据id把持久化对象提取出来 * 2、进行修改 * 3、执行upate操作 */ Person person = (Person)session.get(Person.class, 1L); person.setPsex("不详"); //Person person = new Person(); //person.setPid(1L); session.update(person); transaction.commit(); session.close(); } }
时间: 2024-10-10 11:00:44