Hibernate- Session对象为NULL

时间:2018-01-09 07:03:47

标签: spring hibernate

我是后端开发的新手。我正在尝试使用注释开发Spring rest Web API。为此,我首先初始化我们的课程。我为会话对象获取 null

public class FordonWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getRootConfigClasses() {
    // TODO Auto-generated method stub
    return new Class<?>[] {RootConfig.class} ;
}

@Override
protected Class<?>[] getServletConfigClasses() {
    // TODO Auto-generated method stub
    return new Class<?>[] {WebConfig.class} ;
}

@Override
protected String[] getServletMappings() {
    // TODO Auto-generated method stub
    return new String[]{"/"};
}
} 

及以下是另外两个用于配置视图解析器的类。

@Configuration
@EnableWebMvc
@ComponentScan("")
public class WebConfig extends WebMvcConfigurerAdapter{

    @Bean
    public ViewResolver viewResolver(){
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

    @Override
    public void configureDefaultServletHandling(
            DefaultServletHandlerConfigurer configurer) {
        // TODO Auto-generated method stub
        super.configureDefaultServletHandling(configurer);
        configurer.enable();
    }
}

@Configuration
@ComponentScan(basePackages = {"com"},excludeFilters=
{@Filter(type=FilterType.ANNOTATION, value=EnableWebMvc.class)})

public class RootConfig {

}

我们对Spring rest API的初始配置的所有上述类。现在为hibernate配置xml。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/dbname</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">password</property>

        <mapping class="com.FordonTelematik.Entity.LocationTrack"/>
        <mapping class="com.FordonTelematik.Entity.LoginDetail"/>
        <mapping class="com.FordonTelematik.Entity.OBDdata"/>
        <mapping class="com.FordonTelematik.Entity.ParentChild"/>

    </session-factory>
</hibernate-configuration>

通过下面提到的类我正在初始化我的会话对象。

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buidSessionFactory();

    private static SessionFactory buidSessionFactory(){
        try{
            Configuration config = new Configuration();

            config.addAnnotatedClass(LocationTrack.class);
            config.addAnnotatedClass(LoginDetail.class);
            config.addAnnotatedClass(OBDdata.class);
            config.addAnnotatedClass(ParentChild.class);

            return config.buildSessionFactory(new StandardServiceRegistryBuilder().
                    applySetting("Config", config.getProperties()).build());


        } catch(Exception e){

        }
        return null;

    }

    public static SessionFactory getSessionFactory(){
        return sessionFactory;
    }
}

在这里我试图坚持数据

@Controller
public class FTController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home() {
        Session session = null;
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            session.beginTransaction();

            LoginDetail loginDetails = new LoginDetail();
            loginDetails.setCity("DC");
            loginDetails.setCountry("USA");
            loginDetails.setPassowrd("TKp1234");
            loginDetails.setTimeStamp(new Date());
            loginDetails.setPhoneNo("123456789");
            loginDetails.setUserID(1234);

            session.persist(loginDetails);
            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null && !session.beginTransaction().wasCommitted()) {
                session.beginTransaction().rollback();
            }
        }
        session.flush();
        session.close();

        return "home";
    }
}

但我为会话对象获得 Null 。请带我离开这个问题。

1 个答案:

答案 0 :(得分:0)

我得到了我的问题。下面提到代码正在运行。我忘了写

configuration.configure();

以及整个代码示例

private static SessionFactory buidSessionFactory(){
    try{
        Configuration configuration = new Configuration();
        configuration.configure();
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
                configuration.getProperties()).build();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        return sessionFactory;
    } catch(Exception e){

    }
    return null;
}