使用hibernate5时的注意点

创建SessionFactory

private static SessionFactory createSessionFactory() {
        /*
            //创建SessionFactory
        //加载核心配置文件
        Configuration cfg = new Configuration().configure();
        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
            .applySettings(cfg.getProperties()).buildServiceRegistry();
        //基于线程安全的创建
        SessionFactory factory = cfg.buildSessionFactory(serviceRegistry);
          */

        StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
                .configure().build();
        Metadata metadata = new MetadataSources(standardRegistry)
                .getMetadataBuilder()
                .applyImplicitNamingStrategy(
                        ImplicitNamingStrategyJpaCompliantImpl.INSTANCE)
                .build();
        SessionFactory factory = metadata.getSessionFactoryBuilder().build();
        return factory;
    }

在数据库中建表

链接MySQL数据库时想要通过语句在数据库里建表时
配置数据库方言时应注意是:MySQL5Dialect
否则会引起:建表语句最后一句Type=MyISAM的错误


<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialectproperty>

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

一般都是hibernate.cfg.xml中链接数据库的信息有误

在列表范围中查询时使用setParameterList ,需要注意”in(:classroom)”中classroom的地方不能使用保留字,比如class

 @Test
    public void testSetParameterList10() {
        Session session = null;
        try {
            session = HibernateUtil.openSession();
            session.beginTransaction();
            /**
             * setParameterList可以替代一组数据
             */
            List students = session.createQuery("select stu from Student stu where stu.classRoom.id in(:classroom)")
                    .setParameterList("classroom", new Integer[]{1, 2}).list();
            for (Student student : students) {
                System.out.println(student.getName() + "   " + student.getClassRoom());
            }
            session.getTransaction().commit();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            if (session != null) {
                session.getTransaction().rollback();
            }
        } finally {
            HibernateUtil.close(session);
        }
    }

你可能感兴趣的:(SSH)