JAVA WEB 学习

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_25026989/article/details/80762711

Hibernate 学习小结

在Hibernate5.1中对sessionFactory获取的方法进行了改变

//最新Hibernate5代码这样写
StandardServiceRegistry  serviceRegistry=new StandardServiceRegistryBuilder().configure().build(); 
        SessionFactory sessionFactory=new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
        Session session=sessionFactory.getCurrentSession();
        Transaction tx =session.beginTransaction();
        Students s=new Students("张三","男");
        session.save(s);
        tx.commit();
        tx=null;
        StandardServiceRegistryBuilder.destroy(serviceRegistry);
//之前版本的传统代码这样写
import org.hibernate.cfg.Configuration;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.test.pojo.Book;
/** 
 * 测试hibernate框架 
 */
public class HibernateTest
{ 
    public static void main(String[] args)
    {    /** 
         * 1.先加载配置文件 
         * 2.创建SessionFactory对象,生成Session对象 
         * 3.创建Session对象 
         * 4.开启事务 
         * 5.编写保存代码 
         * 6.提交事务(事务回滚) 
         * 7.释放资源 
         */ 
         //获取配置文件
        Configuration cfg = new Configuration().configure(); 
        //获取factory
        SessionFactory factory = cfg.buildSessionFactory();
        //获取session
        Session session = factory.openSession();;
        //开启事务,严谨点可以用try-catch代码块,回滚失败
        session.beginTransaction();

        Book book  = new Book();
        book.setBook_name("轻量级JavaEE企业应用实战");
        book.setBook_editor("李刚");
        book.setBook_pub("电子工业出版社");
        book.setBook_price((float) 99.00);
        //保存数据
        session.save(book);
        //提交事务
        session.getTransaction().commit(); 
        //释放资源(session,SessionFactory)  
        session.close();  
        factory.close(); 
    }

}

可参考博客:
https://blog.csdn.net/m0_37520980/article/details/79927274

报错问题

  1. Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

错误原因:
提示说是数据源配置错误,dialect,driver_class,url,username,password。检查一下这五项

解决方法:
org.hibernate.dialect.MySQL5Dialect:新版本的mysql方言
org.hibernate.dialect.MySQLDialect :老版本的mysql方言
如果你配置的是老版本的方言,可以修改成新版本的方言

Hibernate5配置与使用详解 推荐系数 7.0

参考博客:
http://blog.csdn.net/tyhj_sf/article/details/51851163

Hibernate 5.2.x 中 sessionFactory 的获取方式 与本文差不多 巩固内容

参考博客:
https://blog.csdn.net/frgod/article/details/78419013

Spring整合Hibernate

推荐系数:6.0

一、概述
二、整合步骤
回到顶部
一、概述
  Spring整合Hibernate有什么好处?

  1、由IOC容器来管理Hibernate的SessionFactory

  2、让Hibernate使用上Spring的声明式事务
参考博客:
https://www.cnblogs.com/xujian2014/p/5282335.html

整合之道–Spring4整合Hibernate5 推荐系数:8.0

参考博客:https://blog.csdn.net/frankcheng5143/article/details/50634487
附项目地址
https://github.com/peer44/testwechat

猜你喜欢

转载自blog.csdn.net/qq_25026989/article/details/80762711
今日推荐