Hibernate例子(添加,修改,删除,获得结果集)
关键词: Hibernate,添加,修改,删除,结果集
1.添加
public int insertNewOneUser(UserVo user) {Session session = sessionFactory.openSession();Transaction tx = null;try {tx = session.beginTransaction();session.save(user);tx.commit();} catch (Exception e) {tx.rollback();e.printStackTrace();} finally {session.close();}return 0;}
public int updateUser(UserVo user) {Session session = sessionFactory.openSession();Transaction tx = null;try {tx = session.beginTransaction();session.update(user);tx.commit();} catch (Exception e) {tx.rollback();e.printStackTrace();} finally {session.close();}return 0;}
public int deleteUser(UserVo user) {Session session = sessionFactory.openSession();Transaction tx = null;try {tx = session.beginTransaction();session.delete(user);tx.commit();} catch (Exception e) {tx.rollback();e.printStackTrace();} finally {session.close();}return 0;}
public UserVo selectUserFromId(int id) {Session session = sessionFactory.openSession();Transaction tx = null;try {tx = session.beginTransaction();Query query = session.createQuery("from UserVo where id = :id");query.setInteger("id", id);return (UserVo) query.list().get(0);} catch (Exception e) {tx.rollback();e.printStackTrace();} finally {session.close();}return null;}
<?xml version='1.0' encoding='UTF-8'?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping><class name="com.zakisoft.hib.UserVo" table="user2"><id name="id" column="ID" type="int"><generator column="NAME" type="string" not-null="true"/><property name="password" column="PASSWORD" type="string" not-null="true"/></class></hibernate-mapping>