hibernate的复习

今天突然感觉到自己学的东西,都快忘完了,而且可能以后会用到,所以看了看自己以前写的东西,回忆一下,若以后用到上手快
一接口
import java.util.List;

import tmc.domail.Favor;
import tmc.domail.Nation;
import tmc.domail.User;

public interface IUserService {

public User login(String name,String pwd);
public void create(User user);
public void del(int id);
public User findUserById(int id);
public List<User> findUsers();
public List<User> findUsers(int pageNo,int maxNo);
public void update(User user);
public List<Nation> nations();
public List<Favor> favors();
public Nation findNativeById(int id);
public void createUserFavor(int uid,Integer[] fid);

}
二:加载hibernate文件
package tmc.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution.  Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {

    /**
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses 
     * #resourceAsStream style lookup for its configuration file.
     * The default classpath location of the hibernate config file is
     * in the default package. Use #setConfigFile() to update
     * the location of the configuration file for the current session.  
     */
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private  static Configuration configuration = new Configuration();   
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

static {
    try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
    }
    private HibernateSessionFactory() {
    }

/**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
        return session;
    }

/**
     *  Rebuild hibernate session factory
     *
     */
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}

/**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

/**
     *  return session factory
     *
     */
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}

/**
     *  return session factory
     *
     * session factory will be rebuilded in the next call
     */
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}

/**
     *  return hibernate configuration
     *
     */
public static Configuration getConfiguration() {
return configuration;
}

}
三:执行相应的数据库操作
package tmc.util;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import tmc.domail.Favor;
import tmc.domail.Nation;
import tmc.domail.User;
import tmc.domail.UserFavor;

public class UserServiceImp implements IUserService{
   /**
    * 添加用户
    */
public void create(User user) {
Session session = null;
Transaction tx = null;
try{
    session = HibernateSessionFactory.getSession();
tx = session.beginTransaction();
    session.save(user);
tx.commit();

}catch(Exception e){
e.printStackTrace();
}finally{
HibernateSessionFactory.closeSession();
}
    }
   /**
    * 删除用户
    */
public void del(int id) {
Session session = null;
Transaction tx = null;
try{
session = HibernateSessionFactory.getSession();
tx = session.beginTransaction();
User user = (User)session.get(User.class,id);
session.delete(user);
tx.commit();
}catch(Exception e){
e.printStackTrace();
tx.rollback();
}finally{
HibernateSessionFactory.closeSession();
}
}
    /**
    *  根据id查看用户信息
    */
public User findUserById(int id) {
Session session = null;
User user = null;
try{
session = HibernateSessionFactory.getSession();
user = (User)session.get(User.class,id);

}catch(Exception e){
e.printStackTrace();
}finally{
HibernateSessionFactory.closeSession();
}
return user;
}
    /**
     * 查看所有的用户信息
     */
public List<User> findUsers() {
Session session = null;
List<User> user = null;
try{
session = HibernateSessionFactory.getSession();
String hql = "from User";
Query query = session.createQuery(hql);
    user = query.list();

}catch(Exception e){
e.printStackTrace();
}finally{
HibernateSessionFactory.closeSession();
}
return user;
}
   /**
    * 分页显示信息
    */
public List<User> findUsers(int pageNo,int maxNo) {
Session session = null;
List<User> user = null;
try{
session = HibernateSessionFactory.getSession();
String hql = "from User";
Query query = session.createQuery(hql);
user =query.setFirstResult(pageNo).setMaxResults(maxNo).list();

}catch(Exception e){
e.printStackTrace();
}finally{
HibernateSessionFactory.closeSession();
}
return user;
}
    /**
     * 用户登录验证
     */
public User login(String username, String password) {
Session session = null;


try {
session = HibernateSessionFactory.getSession();
User users = (User)session.createQuery("from tmc.domail.User u where u.username = :name and u.password = :pwd")
.setString("name", username)
.setString("pwd", password)
.uniqueResult();
            return users;
} catch (HibernateException e) {
e.printStackTrace();
return null;
}finally{
HibernateSessionFactory.closeSession();
}
}
    /**
     * 修改用户信息
     */
public void update(User user) {
Session session = null;
Transaction tx = null;
try{
session = HibernateSessionFactory.getSession();
tx = session.beginTransaction();
user  = (User)session.get(User.class, user.getId());
session.update(user);
tx.commit();
}catch(Exception e){
e.printStackTrace();
tx.rollback();
}finally{
HibernateSessionFactory.closeSession();
}
}
/**
* 查看所有的民族
*/
public List<Nation> nations(){
Session session = null;
List<Nation> nation = null;
try{
session = HibernateSessionFactory.getSession();
String hql ="from Nation";
Query query = session.createQuery(hql);
nation = query.list();
}catch(Exception e){
e.printStackTrace();
}finally{
HibernateSessionFactory.closeSession();
}
return nation;
}
/**
* 查询出所有的爱好
*/
public List<Favor> favors(){
Session session = null;
List<Favor> favor = null;
try{
session = HibernateSessionFactory.getSession();
String hql = "from Favor";
Query query = session.createQuery(hql);
favor = query.list();

}catch(Exception e){
e.printStackTrace();
}finally{
HibernateSessionFactory.closeSession();
}
return favor;
}
/**
* 创建三张表的对应关系,即用户表,爱好表,和中间表
* 本来是多对多的关系,变成了两张多对一的关系
* 用户表--》中间表
* 中间表--》爱好表
* @param uid
* @param fid
*/
public void createUserFavor(int uid,Integer[] fid){
Session session = null;
Transaction tx = null;
try{
session = HibernateSessionFactory.getSession();
tx = session.beginTransaction();
User user = (User)session.get(User.class,uid);
for(int i=0;i<fid.length;i++){
Favor fa = (Favor)session.get(Favor.class, fid[i]);
UserFavor uf = new UserFavor();
uf.setUser(user);
uf.setFavors(fa);
session.save(uf);
}
tx.commit();
}catch(Exception e){
e.printStackTrace();
tx.rollback();
}finally{
HibernateSessionFactory.closeSession();
}

}
public Nation findNativeById(int id) {
Session session = null;
//Transaction tx = null;
Nation nation = null;
try{
session = HibernateSessionFactory.getSession();
nation = (Nation)session.get(Nation.class,id);
}catch(Exception e){
e.printStackTrace();
}finally{
HibernateSessionFactory.closeSession();
}
return nation;
}
}

猜你喜欢

转载自tiansoft.iteye.com/blog/1096660