小汪Hibernate 学习之一 Hibernate 小例子

来源:互联网 发布:淘宝支持微信付款吗 编辑:程序博客网 时间:2024/05/30 04:29

  1. 首先讲讲自己的感受吧,Hibernate这种ORM关系数据库,对于传统的非面向对象的来说的话,无论开发的速度和效率都是大幅度的提升,更加的适合我们的思维方式!我也只是简单的看。文档,看了个视频。收获还是非常的大的,之前把24种设计模式看了一遍,虽然可能还是有些思维不是很懂,对于我在学习框架的时候还是非常的有必要的。更加的倾向面向接口的编程思想,思路,无论从我们的程序的扩展性还是整体的模块化都是很好的思路和例子。Hibernate 改变了我们的思考的方式,用面向对象的去操作我们的数据库。感觉很新颖,但是感觉很棒的!我自己也是做了个例子,感受一下他的力量。

  2. 首先我们从官网上下载个zip文件,这里面的都是好东西,有源码,有配置文件,有例子!比如我
  3.  C:\Users\JetWang\Desktop\hibernate-release-4.3.11.Final\project\hibernate-envers\src\test\resources 在这个文件夹下可以找到我们的配置的东西,很好用!
  4. 增加我们的必须要的包文件   自己建立个用户包 http://blog.csdn.net/zj7758/article/details/8277417
  5. 分模块话的管理非常的棒 比如 http://blog.csdn.net/xiazdong/article/details/6895465/
  6.  DAO    操作数据实体的接口
  7.  Daolmpl   数据接口的实现
  8.  Model  我们的数据实体
  9. 开发我们的Hibernate的工具操作类,可以节省很多的时间做重复的事情。
  10. 我们可以使用hibernate工具直接导出到数据库文件
  11. SchemaExport 这个工具类
  12. 利用好测试文件JUNIT 非常棒的帮助我们实现问题



      讲了这么多的东西,来来看哈怎么处理的,勿喷!模式设计真的很赞、
      1.构建我们的工程
     
配置文件 hibernate.cfg.xml 直接在Jar包中去找,简单的配置哈哈。就行了
<?xmlversion='1.0'encoding='utf-8'?>
<!DOCTYPEhibernate-configurationPUBLIC
       "-//Hibernate/Hibernate Configuration DTD//EN"
       "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
       <propertyname="show_sql">true</property>
       <propertyname="format_sql">false</property>
       <propertyname="dialect">
              org.hibernate.dialect.MySQL5InnoDBDialect
       </property>
       <propertyname="connection.url">
              jdbc:mysql://127.0.0.1:3306/shopping?characterEncoding=UTF-8
       </property>
       <propertyname="connection.driver_class">
              com.mysql.jdbc.Driver
       </property>
       <propertyname="connection.username">wang</property>
       <propertyname="connection.password">wang</property>
       <mappingclass="com.hdu.model.User"/>
       
</session-factory>
</hibernate-configuration>
    


构建我们Model 实体类,采用注释的方式进行 @Entity(name="User")这里为甚么采取这样呢,有问题使用@table 网上使用的方案,让表和我们的对象实体类名一致
package com.hdu.model;

import java.util.Date;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.*;



/**
 * User 实体类
 * @author JetWang
 *
 */

@Entity(name="User")
public class User {

    private  int id;

    private String name;

    private String password;

    private boolean sex;

    private long phone;

    private String email;

    private String addr;

    private Date regeDate;

    private String IP;

    private long QQ;
    @Column(nullable=true)
    public long getQQ() {
        return QQ;
    }

    public void setQQ(long qQ) {
        QQ = qQ;
    }
    @Column(length=15,nullable=false)
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
    @Column(nullable=false)
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
    @Column(nullable=true)
    public boolean isSex() {
        return sex;
    }

    public void setSex(boolean sex) {
        this.sex = sex;
    }
    @Column(nullable=true)
    public long getPhone() {
        return phone;
    }

    public void setPhone(long phone) {
        this.phone = phone;
    }
    @Column(nullable=true)
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
    @Column(nullable=true)
    public String getAddr() {
        return addr;
    }

    public void setAddr(String addr) {
        this.addr = addr;
    }
    @Column(nullable=true)
    public Date getRegeDate() {
        return regeDate;
    }

    public void setRegeDate(Date regeDate) {
        this.regeDate = regeDate;
    }

    public String getIP() {
        return IP;
    }

    public void setIP(String iP) {
        IP = iP;
    }



}




实现我们的Dao接口文件

package com.hdu.dao;

import java.util.List;

import com.hdu.model.User;

public interface UserDao {
    /**
     * 保存User
     * @param user
     * @return
     */
  public User save(User user);
  /**
   * 通过id 删除用户
   * @param id
   * @return
   */
  public boolean delete(int id);
  /**
   * 更新用户
   * @param user
   * @return
   */
  public boolean update(User user);
  /**
   * 找到所有的用户
   * @return
   */
  public List<User> findAll();
  /**
   * 分页查询用户
   * @param start
   * @param end
   * @return
   */
  public List<User> findAll(int start,int end);
  /**
   * 登录判断
   * @param username
   * @param password
   * @return
   */
  public User login(String username,String password);
  /**
   * 检查用户名是否纯在
   * @param username
   * @return
   */
  public boolean checkUserName(String username);

}





实现我们的Daolmp 的接口的各种操作
package com.hdu.dao.impl;

import java.util.List;

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

import com.hdu.dao.UserDao;
import com.hdu.model.User;
import com.hdu.util.HibernateUtil;

public class UserDaolmpl implements UserDao {


    @SuppressWarnings("unused")
    @Override
    public User save(User user) {
        // TODO Auto-generated method stub
        HibernateUtil hbUtil=null;
        hbUtil= new HibernateUtil();
        Session session = null;
        User u=null;
        Transaction transaction=null;
        try {
            session = hbUtil.getSession();
            transaction = session.beginTransaction();
            /*
             * session.save(user);
             * object - a transient instance of
             * a persistent class Returns: the
             * generated identifier
             */
            u = (User) session.load(User.class, session.save(user));
            transaction.commit();
        } catch (HibernateException e) {
            // TODO: handle exception
            e.printStackTrace();
            hbUtil.rollBackTransaction(transaction);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            hbUtil.closeSession(session);
        }
        return u;
    }
    /**
     * 根据主间删除我们的数据
     */
    @Override
    public boolean delete(int id) {
        // TODO Auto-generated method stub
        HibernateUtil hbUtil=new HibernateUtil();
        String hql="delete from User where id="+id;
        return hbUtil.exeDelete(hql);
    }
    /**
     * 更新数据,首先找到数据,然后在更新
     */
    @Override
    public boolean update(User user) {
        // TODO Auto-generated method stub
        HibernateUtil hbUtil =new HibernateUtil();
        Session session=null;
        User u=null;
        Transaction transaction=null;
        boolean flag=false;
        try {
            session = hbUtil.getSession();
            transaction = session.beginTransaction();
            /**
             * 这里写的不好!
             */
            u = (User) session.load(User.class, user.getId());
            u.setName(user.getName());
            u.setPassword(user.getPassword());
            u.setAddr(user.getAddr());
            u.setEmail(user.getEmail());
            u.setPhone(user.getPhone());
            u.setQQ(user.getQQ());
            transaction.commit();
            flag=true;
        } catch (HibernateException e) {
            // TODO: handle exception
            e.printStackTrace();
            hbUtil.rollBackTransaction(transaction);
            flag=false;

        }catch(Exception e){
            e.printStackTrace();
            flag=false;
        }finally{
            hbUtil.closeSession(session);
        }
        return flag;
    }
    @SuppressWarnings("unchecked")
    @Override
    public List<User> findAll() {
        // TODO Auto-generated method stub
        HibernateUtil hbUtil =new HibernateUtil();
        String hql="from User";       
        return hbUtil.exeQuery(hql);       
    }

    @Override
    public List<User> findAll(int start, int end) {
        // TODO Auto-generated method stub
        HibernateUtil hbUtil =new HibernateUtil();
        String hql="from User";       
        return hbUtil.exeQueryPage(hql, start, end);
    }
    /**
     * 这里的登录的时候呢,如果User返回为null,就不存在User
     */
    @Override
    public User login(String username, String password) {
        // TODO Auto-generated method stub
        HibernateUtil hbUtil=new HibernateUtil();
        String hql="from User where name= '"+username
                +"' and password="+password+"'";
        List list=hbUtil.exeQuery(hql);
        if(list.size()>0){
            return (User) list.get(0);           
        }else{
            return null;
        }
    }

    @Override
    public boolean checkUserName(String username) {
        // TODO Auto-generated method stub
        HibernateUtil hbUtil=new HibernateUtil();
        String hql="from User u  where u.name='"+username+"'";
        if(hbUtil.exeQuery(hql).size()>0){
            return true;
        }
        return false;
    }

}






来写我们的工具hibernateUtil类,实现了很多直接就可以使用的功能,很简单的使用。这个不是最好的实现
package com.hdu.util;

import java.util.List;

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

public class HibernateUtil {
    private static  SessionFactory sesionFactory;
    static {
        Configuration cfg= new Configuration().configure();       
        sesionFactory=cfg.buildSessionFactory();
    }

    public HibernateUtil() {
        super();
        // TODO Auto-generated constructor stub
    }
    public static  SessionFactory getSesionFactory() {
        return sesionFactory;
    }
    public void setSesionFactory(SessionFactory sesionFactory) {
        this.sesionFactory = sesionFactory;
    }
    public Session getSession(){
        Session session=null;
        try {
            session = sesionFactory.openSession();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return session;
    }
    public void closeSession(Session session){
        if(session!=null){
            try {
                session.close();
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
    }
    /**
     * 事物回滚
     * @param transaction
     */
    public void rollBackTransaction(Transaction transaction){
        try {
            if (null != transaction) {
                transaction.rollback();
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
    /**
     * 查询List的集合
     * @param hql
     * @return
     */
    public List exeQuery(String hql){
        List list=null;
        Transaction transaction=null;
        Session session=null;
        try {
            session = getSession();
            transaction = session.beginTransaction();
            list = session.createQuery(hql).list();
            transaction.commit();
        } catch (HibernateException e) {
            // TODO: handle exception
            e.printStackTrace();
            rollBackTransaction(transaction);

        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally{
            closeSession(session);
        }
        return list;       
    }
    /**
     * 分页查询功能
     * @param hql
     * @param start
     * @param max
     * @return
     */
    public List exeQueryPage(String hql,int start,int max){
        Session session=null;
        List list=null;
        Transaction transaction=null;
        try {
            session = getSession();
            transaction = session.beginTransaction();
            list = session.createQuery(hql).setFirstResult(start)
                    .setMaxResults(max).list();
            transaction.commit();
        } catch (HibernateException e) {
            // TODO: handle exception
            e.printStackTrace();
            rollBackTransaction(transaction);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            closeSession(session);
        }
        return list;
    }
    /**
     * 执行delete
     * @param hql
     * @return
     */
    public boolean exeDelete(String hql){
        Session session=null;
        Transaction transaction=null;
        boolean flag=false;
        try {
            session = getSession();
            transaction = session.beginTransaction();
            //删除或者更新执行此行
            session.createQuery(hql).executeUpdate();
            transaction.commit();
            flag= true;
        } catch (HibernateException e) {
            // TODO: handle exception
            e.printStackTrace();
            flag= false;
        }catch(Exception e){
            e.printStackTrace();
            flag= false;
        }finally{
            closeSession(session);
        }
        return flag;

    }

}





使用Hibernate直接导出数据到数据库,不用自己去创建表,非常的方便,我们写个测试类就好了
package com.hdu.test;

import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Test;

public class testExport {

    @Test
    public void exportTable(){
        Configuration cfg = new Configuration().configure("hibernate.cfg.xml");
        SchemaExport export = new SchemaExport(cfg);
        export.create(true, true);
    }
}




最后就是使用测试工具,看哈我们的功能是否有错误的地方直接使用JUNIT工具!很好用,我们开发网页的时候后台的数据不一定需要我们直接的使用,网页交互才可进行使用
package com.hdu.userDaoImpl;

import static org.junit.Assert.fail;
import java.util.List;

import org.junit.Test;
import com.hdu.dao.UserDao;
import com.hdu.dao.impl.UserDaolmpl;
import com.hdu.model.User;

public class UserDaolmplTest {

    @Test
    public void testSave() {
        // fail("Not yet implemented");
        UserDaolmpl test = new UserDaolmpl();
        User u = new User();
        u.setName("tata");
        u.setPassword("dd55245");
        System.out.println(test.save(u).getId());

    }

    @Test
    public void testDelete() {
        // fail("Not yet implemented");
        UserDao test = new UserDaolmpl();
        System.out.print("输出" + test.delete(1));

    }

    @Test
    public void testFindAll() {
        UserDao test = new UserDaolmpl();
        List<User> list = test.findAll();
        User user = null;
        for (int i = 0; i < list.size(); i++) {
            user = (User) list.get(i);
            System.out.println("usernaem:" + user.getName());
            System.out.println("passsword:" + user.getPassword());
        }
    }

    @Test
    public void testFindAllIntInt() {
        // fail("Not yet implemented");
        UserDao test = new UserDaolmpl();
        List<User> list = test.findAll(1, 2);
        User user = null;
        for (int i = 0; i < list.size(); i++) {
            user = (User) list.get(i);
            System.out.println("usernaem:" + user.getName());
            System.out.println("passsword:" + user.getPassword());
        }
    }

    @Test
    public void testLogin() {
        // fail("Not yet implemented");
        UserDao test = new UserDaolmpl();
        User user = test.login("汪d吉", "5545");
        System.out.println("usernaem:" + user.getName());
        System.out.println("passsword:" + user.getPassword());

    }

    @Test
    public void testCheckUserName() {
        // fail("Not yet implemented");
        UserDao test = new UserDaolmpl();
        System.out.println(test.checkUserName("汪吉"));

    }

}



这个例子虽然很简单,没有实现好多的功能,但是对于我来说的体会很强的,感受到了!模块的力量。以前上软件工程课的时候老师只是嘴巴上讲解这些东西的优势,自己没有去实现过,总是感觉不到好!嘿嘿!
hibernatetest 终于弄好了! 花了好几天的时候,把这个东西到底是有啥用搞清楚了,还是很有收获。期间还是发现了一些小问题,自己都把他们解决了,
逗逼程序员,就是不要怕错!
欢迎交流    QQ:983433479
1 0
原创粉丝点击