创建一个实体类
public class User {
private Integer id;
private String user_name;
private String real_name;
private String user_pwd;
private String sex;
private Date birthday;
private Date create_datetime;
private String remark;
}
所有的增删改差 都有7步骤
* 1.对hibernate.cfg.xml建模
* 2.通过建模所的到的config文件类,获取所配置的sessionfactory
* 3.获取session会话
* 4.开启事务
* 5.操作数据库
* 6.提交事务
* 7.关闭session会话
增加:(hibernate.cfg.xml,文件配置在上一章)
Configuration configure = new Configuration().configure("hibernate.cfg.xml");
SessionFactory sessionFactory = configure.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
User user=new User();
user.setBirthday(new Date());
user.setUser_name("hhh");
user.setUser_pwd("123456");
user.setReal_name("hhh");
user.setRemark("不知道");
user.setSex("男");
session.save(user);
transaction.commit();
session.close();
删除:
Configuration configure = new Configuration().configure("hibernate.cfg.xml");
SessionFactory sessionFactory = configure.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
User user=new User();
user.setId(1);
session.delete(user);
transaction.commit();
session.close();
查询:
Configuration configure = new Configuration().configure("hibernate.cfg.xml");
SessionFactory sessionFactory = configure.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
//查询单个
// User user = session.get(User.class, 3);
// System.out.println(user.getUser_name());
//查询多个
List<User> from_user = session.createQuery("from User").list();
for (User obj:from_user){
System.out.println(obj.getUser_name());
}
transaction.commit();
session.close();
修改:
Configuration configure = new Configuration().configure("hibernate.cfg.xml");
SessionFactory sessionFactory = configure.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
// 通过查询出来的对象,改变对象的属性值进行修改数据库中的列名对应的值
// User user = session.get(User.class, 3);
// user.setReal_name("xxx");
// System.out.println(user.getReal_name());
// 修改整张表可以试用这个 但是相对而言来说 上一个修改方式比较简单
User user=new User();
user.setId(3);
user.setReal_name("hhh1");
user.setUser_name("hhh1");
user.setSex("男");
user.setUser_pwd("654321");
user.setRemark("123123");
session.update(user);
transaction.commit();
session.close();
所有的操作都对应着这七步骤