1.Hibernate 的增删改查

2018-01-17  本文已影响0人  木有鱼丸啦

//可以抽取出一个openSession的工具类简化代码,但是自己练练手就多写了几遍

public class HibernateTest1 {

// 保存一个Customer

@Test

public static void saveCustomerTest() {

// 创建一个Customer

Customer c = new Customer();

c.setName("张三");

c.setAddress("北京");

c.setSex("男");

// 使用hibernate的api来完成将customer信息保存到mysql中操作

Configuration config = new Configuration().configure(); // 加载hibernate.cfg.xml

SessionFactory sessionFactory = config.buildSessionFactory();

Session session = sessionFactory.openSession(); // 相当于得到一个Connection。

// 开启事务

Transaction transaction = session.beginTransaction();

// 操作

session.save(c);

// 事务提交

transaction.commit();

session.close();

sessionFactory.close();

}

// 根据id查询一个Customer对象

@Test

public static void findCustomerByIdTest() {

Configuration config = new Configuration().configure();

SessionFactory sessionFactory = config.buildSessionFactory();

Session session = sessionFactory.openSession(); // 相当于得到一个Connection。

// 开启事务

session.beginTransaction();

// 根据业务来编写代码

// Customer c = session.get(Customer.class, 1);

Customer c = session.load(Customer.class, 1);

System.out.println(c.getName());

// 事务提交

session.getTransaction().commit();

session.close();

sessionFactory.close();

}

// 修改操作

@Test

public static void updateCustomerTest() {

Configuration config = new Configuration().configure();

SessionFactory sessionFactory = config.buildSessionFactory();

Session session = sessionFactory.openSession(); // 相当于得到一个Connection。

// 开启事务

session.beginTransaction();

// 根据业务来编写代码

Customer c = session.get(Customer.class, 1);

c.setName("李四");

session.update(c); // 修改操作

// 事务提交

session.getTransaction().commit();

session.close();

sessionFactory.close();

}

// 删除操作-----根据id进行删除

@Test

public static void deleteCustomerTest() {

Configuration config = new Configuration().configure();

SessionFactory sessionFactory = config.buildSessionFactory();

Session session = sessionFactory.openSession(); // 相当于得到一个Connection。

// 开启事务

session.beginTransaction();

// 根据业务来编写代码

Customer c = session.get(Customer.class, 1);

session.delete(c); // 删除操作

// 事务提交

session.getTransaction().commit();

session.close();

sessionFactory.close();

}

// 查询所有Customer@Testpublic static void findAllCustomerTest() {Configuration config = new Configuration().configure();SessionFactory sessionFactory = config.buildSessionFactory();Session session = sessionFactory.openSession(); // 相当于得到一个Connection。// 开启事务session.beginTransaction();// 根据业务来编写代码Query query = session.createQuery("from Customer"); // HQL 它是类似于sqlList list = query.list();

System.err.println(list);

// 事务提交

session.getTransaction().commit();

session.close();

sessionFactory.close();

}

public static void main(String[] args) {

//saveCustomerTest();

findAllCustomerTest();

}

}

上一篇 下一篇

猜你喜欢

热点阅读