Hibernate之基本的增删改查

一、java代码

package pde.ams.user.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import pde.ams.helllworld.User;

/**
 * @author 作者 macx:
 * @version 创建时间:2018年4月29日 下午2:27:50 类说明
 */
public class UserDao {

	private static SessionFactory sessionFactory;
	static {

		// 读取配置文件并生成Session工厂对象
		Configuration cfg = new Configuration();
		cfg.configure("hibernate.cfg.xml");
		sessionFactory = cfg.buildSessionFactory();
	}

	/**
	 * 新增用户
	 * 
	 * @param user
	 */
	public void saveUser(User user) {
		Session session = sessionFactory.openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			session.save(user);
		} catch (RuntimeException e) {
			tx.rollback();
			throw e;
		} finally {
			tx.commit();
			session.close();
		}
	}

	/**
	 * 删除用户
	 * 
	 * @param user
	 */
	public void deleteUser(int id) {
		Session session = sessionFactory.openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			User user = (User) session.get(User.class, 1);
			session.delete(user);
		} catch (RuntimeException e) {
			tx.rollback();
			throw e;
		} finally {
			tx.commit();
			session.close();
		}
	}

	/**
	 * 更新用户
	 * 
	 * @param user
	 */
	public void updateUser(User user) {
		Session session = sessionFactory.openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			session.update(user);
		} catch (RuntimeException e) {
			tx.rollback();
			throw e;
		} finally {
			tx.commit();
			session.close();
		}
	}

	/**
	 * 根据ID查找用户
	 * 
	 * @param user
	 */
	public User findUserById(int id) {
		Session session = sessionFactory.openSession();
		Transaction tx = null;
		User user = null;
		try {
			tx = session.beginTransaction();
			user = (User) session.get(User.class, id);
		} catch (RuntimeException e) {
			tx.rollback();
			throw e;
		} finally {
			tx.commit();
			session.close();
		}
		return user;
	}

	/**
	 * 查询所有用户
	 * 
	 * @param user
	 */
	public List<User> findAll() {
		Session session = sessionFactory.openSession();
		Transaction tx = null;
		List userList = null;
		try {
			tx = session.beginTransaction();

			userList = session.createQuery("from User").list();
		} catch (RuntimeException e) {
			tx.rollback();
			throw e;
		} finally {
			tx.commit();
			session.close();
		}
		return userList;
	}

	/**
	 * 分页查询所有用户
	 * 
	 * @param user
	 * @return
	 */
	public QueryResult<User> findByPageSize(int firstResult, int maxResults) {
		Session session = sessionFactory.openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			long count = (Long) session.createQuery("select COUNT(*) from User").uniqueResult();

			// 2,查询一段数据
			Query query = session.createQuery("FROM User");
			query.setFirstResult(firstResult);
			query.setMaxResults(maxResults);
			List<User> list = query.list(); // 执行查询
			// -------------------------------------
			return new QueryResult<User>(list, count);
		} catch (RuntimeException e) {
			tx.rollback();
			throw e;
		} finally {
			tx.commit();
			session.close();
		}
	}
}

二、主配置文件

<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
	<session-factory>
		<!-- 一、数据库信息:数据库方言(是一个类的全名)与数据库连接信息 -->
		<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
		<property name="connection.url">jdbc:mysql:///hibernate</property>
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.username">root</property>
		<property name="connection.password">921010</property>

		<!-- 二、其他配置 -->
		<property name="show_sql">true</property>
		<property name="format_sql">false</property>
		<!-- 
			create: 先删表,再建表。
			create-drop: 启动时建表,退出前删表。
			update: 如果表结构不一致,就创建或更新。
			validate: 启动时验证表结构,如果不致就抛异常。
		
		<property name="hibernate.hbm2ddl.auto">update</property>
		 -->
		
		<!-- 三、导入映射配置文件-->
		<mapping resource="pde/ams/helllworld/User.hbm.xml"/>
		
	</session-factory>
</hibernate-configuration>

三、类映射文件

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

	<class name="pde.ams.helllworld.User" table="user">
		<id name="id" type="int" column="id">
            <generator class="native"/>
		</id>
		<property name="name" type="string" not-null="true" column="name"/>
		<property name="age" type="string" not-null="true" column="age"/>
	</class>
	
</hibernate-mapping>

猜你喜欢

转载自blog.csdn.net/weixin_40931184/article/details/80143381