当前位置:   article > 正文

关于对hibernate使用以及简答CRUD操作方法的记录_使用hibernate对登陆系统中的数据进行crud操作

使用hibernate对登陆系统中的数据进行crud操作

关于对hibernate使用方法现在在网上的指南已经有很多了,但是这里我只是想给自己做一个记录,方便自己作为资料来查阅

①对于使用hibernate导入jar包的过程在这里就省略了-----

②在src文件下配置一个xml文件,将其命名为hibernate.cfg.xml,其中的配置基本内容如下:

  1. <span style="font-family:FangSong_GB2312;font-size:18px;"><?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE hibernate-configuration PUBLIC
  3. "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  4. "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
  5. <hibernate-configuration>
  6. <session-factory>
  7. <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  8. <property name="connection.url">jdbc:mysql://localhost/yhw_wx?characterEncoding=UTF-8</property> //数据库地址、数据库名称、编码格式
  9. <property name="connection.username">root</property> //数据库用户名
  10. <property name="connection.password">***</property> //数据库访问密码
  11. <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  12. <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
  13. <property name="show_sql">true</property>
  14. <mapping class="com.yihu.entry.AT_GZF" /> //用于建立数据库表和entry类的联系,首先需要实体类是存在的
  15. </session-factory>
  16. </hibernate-configuration> </span>

③有了以上的配置我们就能在dao实现对数据库表进行CRUD的操作了,简单代码如下:

查询操作:

  1. <span style="font-family:FangSong_GB2312;font-size:18px;">Configuration cfg = new AnnotationConfiguration();
  2. SessionFactory sf = cfg.configure().buildSessionFactory();
  3. Session session = sf.openSession();
  4. session.beginTransaction();
  5. Query query = session
  6. .createQuery("select useropenid from AT_GZF where useropenid=:openid");
  7. query.setString("openid", openid);
  8. String useropenid = (String) query.uniqueResult(); //返回为唯一字符时候可以采用uniqueResult()方法,同样可以采用返回对象的方式使用entry类解析
  9. System.out.println(useropenid);
  10. session.getTransaction().commit();
  11. session.close();
  12. sf.close();</span>

在上面写出了查询操作的代码实现,其实对于修改和删除操作实现方式也是和上面一样的,只不过是其中的HQL语句有所差异而已;


数据插入操作:

  1. <span style="font-family:FangSong_GB2312;font-size:18px;">Configuration cfg = new AnnotationConfiguration();
  2. SessionFactory sf = cfg.configure().buildSessionFactory();
  3. Session ssone = sf.openSession();
  4. ssone.beginTransaction();// OK,将操作放入事务中
  5. MD_Content content = new MD_Content();
  6. content.setMdhead(mdhead);
  7. content.setMdcontent(mdcontent);
  8. content.setMdid(mdid);
  9. content.setMdremark(mdremark);
  10. content.setMdurl(mdurl);
  11. content.setMdsendtime(System.currentTimeMillis() + "");
  12. ssone.save(content);// 保存对象
  13. ssone.getTransaction().commit();// 得到事务并提交
  14. ssone.close();// Session关闭
  15. sf.close();// 工厂关闭</span>
数据的插入操作其实是以对象的形式将用户数据做封装提交保存数据即可;
欢迎访问个人博客(http://cuiyongzhi.com)!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/运维做开发/article/detail/870854
推荐阅读
相关标签
  

闽ICP备14008679号