userdao.java

来自「hibernate in action 源码 caveatemptor-0.9.」· Java 代码 · 共 96 行

JAVA
96
字号
package org.hibernate.auction.dao;

import net.sf.hibernate.*;
import net.sf.hibernate.expression.Example;
import org.hibernate.auction.exceptions.InfrastructureException;
import org.hibernate.auction.model.User;
import org.hibernate.auction.persistence.HibernateUtil;

import java.util.Collection;

/**
 * A typical DAO for users using Hibernate.
 *
 * @author Christian Bauer <christian@hibernate.org>
 */
public class UserDAO {

	public UserDAO() {
		HibernateUtil.beginTransaction();
	}

	// ********************************************************** //

	public User getUserById(Long userId, boolean lock)
			throws InfrastructureException {

		Session session = HibernateUtil.getSession();
		User user = null;
		try {
			if (lock) {
				user = (User) session.load(User.class, userId, LockMode.UPGRADE);
			} else {
				user = (User) session.load(User.class, userId);
			}
		}  catch (HibernateException ex) {
			throw new InfrastructureException(ex);
		}
		return user;
	}

	// ********************************************************** //

	public Collection findAll()
			throws InfrastructureException {

		Collection users;
		try {
			users = HibernateUtil.getSession().createCriteria(User.class).list();
		} catch (HibernateException ex) {
			throw new InfrastructureException(ex);
		}
		return users;
	}

	// ********************************************************** //

	public Collection findByExample(User exampleUser)
			throws InfrastructureException {

		Collection users;
		try {
			Criteria crit = HibernateUtil.getSession().createCriteria(User.class);
			users = crit.add(Example.create(exampleUser)).list();
		} catch (HibernateException ex) {
			throw new InfrastructureException(ex);
		}
		return users;
	}

	// ********************************************************** //

	public void makePersistent(User user)
			throws InfrastructureException {

		try {
			HibernateUtil.getSession().saveOrUpdate(user);
		} catch (HibernateException ex) {
			throw new InfrastructureException(ex);
		}
	}

	// ********************************************************** //

	public void makeTransient(User user)
			throws InfrastructureException {

		try {
			HibernateUtil.getSession().delete(user);
		} catch (HibernateException ex) {
			throw new InfrastructureException(ex);
		}
	}


}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?