1、使用maven管理Hibernate实现自动装配jar包
2、需要在配置文件pom.xml中引入
如:引入hibaernate5.2.11.Final版本的jar包,需要做如下配置:
<!-- 添加Hibernate依赖 --> <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.2.11.Final</version> </dependency>
如果你不知到要如何配置各个版本,请参照:
http://mvnrepository.com/artifact/org.hibernate/hibernate-core 此网站
配置好后:也有可能会出现你在使用buildServiceReguistry是找不到该方法,
原因:可能你所需的包没导入【导入CTRL+SHIFT+O】,也可能是你的包就没下载下来,那你可以去你的本地仓库看看,如果没有进行下载。
导入的包是【import org.hibernate.boot.registry.StandardServiceRegistryBuilder;】
也有可能是版本4之后的Hibernate中buildServiceReguistry()方法被替换了。
解决方法:
(1)版本导入更换为: import org.hibernate.boot.registry.StandardServiceRegistryBuilder; (2)在版本4及以前中的用法: Configuration configuration = new Configuration().configure(); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); (3)在版本5中的用法: ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
3、完整代码如下:
测试代码如下: import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.junit.After; import org.junit.Before; import org.junit.Test; public class StudentTest { private SessionFactory sessionFactory; private Session session; private Transaction transction; @Test public void test() { Students stu=new Students(1,"张三", "wq","1995年9月1日", "云南曲靖","15709618888"); // Students(int sid, String name, String gender, String birthday, String address, String tel); session.save(stu); } @Before public void init() { Configuration config=new Configuration().configure(); //ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().applySettting(config.getProperties()).buildServiceRegistry(); //这是4及以前的用法 //ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build(); session= sessionFactory.openSession();//会话对象 transction=session.beginTransaction();//开启事务 } @After public void distort() { transction.commit();//提交事务 session.close();//关闭session会话 sessionFactory.close();//关闭会话工厂 } }