Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
spring引导应用程序中的application.properties与hibernate.cfg.xml_Hibernate_Spring Boot - Fatal编程技术网

spring引导应用程序中的application.properties与hibernate.cfg.xml

spring引导应用程序中的application.properties与hibernate.cfg.xml,hibernate,spring-boot,Hibernate,Spring Boot,我已经在spring boot应用程序的application.properties文件中配置了hibernate属性 应用程序属性 #hibernate config spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect spring.datasource.url=<db_url> spring.datasource.username=<username> spring.datasourc

我已经在spring boot应用程序的
application.properties
文件中配置了hibernate属性

应用程序属性

#hibernate config
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
spring.datasource.url=<db_url>
spring.datasource.username=<username>
spring.datasource.password=<password>
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
# Show or not log for each sql query
spring.jpa.show-sql = true
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy     

# ThymeLeaf
spring.thymeleaf.cache= false
spring.thymeleaf.mode=LEGACYHTML5   
public List getSelectedStudents(){
    final EntityManagerFactory emf = null;
    EntityManager em = emf.createEntityManager();

    Query q = em.createNativeQuery("SELECT s.student_id, s.first_name, s.last_name, s.city FROM Student s "
                                    + "where s.city=:city and s.last_name = :lname", Student.class);
    q.setParameter("city", "London");
    q.setParameter("lname", "Rizwan");

    List<Student> students = q.getResultList();

    for (Student s : students) {
        System.out.println("Student "
                + s.getFirstName()
                + " "
                + s.getLastName());
    }

    return students;
}   
错误:

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.hibernate.HibernateException: 
Could not parse configuration: application.properties] with root cause

org.dom4j.DocumentException: Error on line 1 of document  : Content is not allowed in prolog. Nested exception: Content is not allowed in prolog.
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause

java.lang.NullPointerException: null
    at com.school.service.StudentServiceImplementation.getSelectedStudents(StudentServiceImplementation.java:69) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_77]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_77] 
我想类路径中也应该有
hibernate.cfg.xml
文件

有没有办法只使用
application.properties
或将所有与hibernate相关的属性移动到
hibernate.cfg.xml
hibernate.properties
文件

getSelectedStudents

#hibernate config
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
spring.datasource.url=<db_url>
spring.datasource.username=<username>
spring.datasource.password=<password>
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
# Show or not log for each sql query
spring.jpa.show-sql = true
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy     

# ThymeLeaf
spring.thymeleaf.cache= false
spring.thymeleaf.mode=LEGACYHTML5   
public List getSelectedStudents(){
    final EntityManagerFactory emf = null;
    EntityManager em = emf.createEntityManager();

    Query q = em.createNativeQuery("SELECT s.student_id, s.first_name, s.last_name, s.city FROM Student s "
                                    + "where s.city=:city and s.last_name = :lname", Student.class);
    q.setParameter("city", "London");
    q.setParameter("lname", "Rizwan");

    List<Student> students = q.getResultList();

    for (Student s : students) {
        System.out.println("Student "
                + s.getFirstName()
                + " "
                + s.getLastName());
    }

    return students;
}   
编辑: 按照使用实体管理器的建议,我添加了getSelectedStudents方法。我仍然在
EntityManager em=emf.createEntityManager()处遇到错误

有关详细信息,请参阅错误2。

如果您在tandum中使用spring boot和spring autoconfigure,只需将Hibernate库放到类路径上,spring就会自动为您连接Hibernate。您只需在application.properties文件中提供一些spring jpa配置设置,就完成了

如果希望避免使用spring自动配置,则需要添加一个配置类,该类构造
LocalContainerEntityManagerFactoryBean
JpaTransactionManager
数据源

在任何一种情况下,要在应用程序中使用JPA,只需向存储库或服务类添加带注释的属性,即可将实例添加到
EntityManager
,如下所示:

@PersistentContext
private EntityManager entityManager;

Spring将确保为您注入此代码,您的代码只需根据需要使用它。

示例。在配置类中,您需要调用@PropertySources并声明一个环境变量

    import java.util.Properties;

    import javax.sql.DataSource; 
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.PropertySource;
    import org.springframework.context.annotation.PropertySources;
    import org.springframework.core.env.Environment; 
    import org.springframework.orm.hibernate4.LocalSessionFactoryBean; 
    import org.springframework.jndi.JndiTemplate;

    @Configuration
    @PropertySources(value = {@PropertySource("classpath:application.properties") })
    public class DataBaseConfig {

        @Autowired
        private Environment environment;

        @Bean(name = "dataSource")
        public DataSource dataSource() {
            ..........
            return dataSource;
        }



        @Bean
        public LocalSessionFactoryBean getSessionFactory() {
            LocalSessionFactoryBean asfb = new LocalSessionFactoryBean();
            asfb.setDataSource(dataSource());
            asfb.setHibernateProperties(getHibernateProperties());
            asfb.setPackagesToScan(new String[] { "your package domain class" });
            return asfb;
        }



        Properties getHibernateProperties() {
            Properties properties = new Properties();
            properties.put("schema", environment.getProperty("JNDI.SCHEMA"));
            properties.put("hibernate.dialect", environment.getProperty("HIBERNATE.DIALECT.PGSQL"));
            properties.put("hibernate.show_sql", environment.getProperty("HIBERNATE.SQL.SHOW"));
            properties.put("hibernate.format_sql", environment.getProperty("HIBERNATE.SQL.FORMAT"));
            properties.put("hibernate.hbm2ddl.auto", environment.getProperty("HIBERNATE.HBM2DDL.AUTO"));
            properties.put("hibernate.default_schema", environment.getProperty("JNDI.SCHEMA"));
            properties.put("hibernate.use_sql_comments", environment.getProperty("HIBERNATE.SQL.COMMENTS"));
            properties.put("hibernate.connection.CharSet", environment.getProperty("HIBERNATE.CHARSET"));
            properties.put("hibernate.generate_statistics", environment.getProperty("HIBERNATE.STATISTICS"));
            properties.put("hibernate.connection.autocommit", environment.getProperty("HIBERNATE.AUTOCOMMIT"));
            properties.put("hibernate.connection.useUnicode", environment.getProperty("HIBERNATE.UNICODE"));
            properties.put("hibernate.enable_lazy_load_no_trans", environment.getProperty("HIBERNATE.ENABLED.LAZY"));
            properties.put("hibernate.connection.characterEncoding", environment.getProperty("HIBERNATE.ENCODING"));
            return properties;

        }


    }
在您的“application.properties”文件中有这样的内容

        ################ CONFIGURACION HIBERNATE ################
        HIBERNATE.SEARCH.DEFAULT.PROVIDER=hibernate.search.default.directory_provider
        HIBERNATE.DIALECT.MYSQL=org.hibernate.dialect.MySQL5InnoDBDialect
        HIBERNATE.DIALECT.MSSQL=org.hibernate.dialect.SQLServerDialect
        HIBERNATE.DIALECT.PGSQL=org.hibernate.dialect.PostgreSQLDialect
        HIBERNATE.CACHE.SECONDLEVEL=false
        HIBERNATE.CACHE.QUERYCACHE=false
        HIBERNATE.ENABLED.LAZY=hibernate.enable_lazy_load_no_trans
        HIBERNATE.HBM2DDL.AUTO=none   
        HIBERNATE.SQL.COMMENTS=false
        HIBERNATE.SQL.FORMAT=false
        HIBERNATE.STATISTICS=false
        HIBERNATE.AUTOCOMMIT=true
        HIBERNATE.SQL.SHOW=true
        HIBERNATE.ENCODING=utf8
        HIBERNATE.CHARSET=utf8 
        HIBERNATE.UNICODE=true  

通过阅读文档,而不是尝试使用hibernate方式获取会话。另外,如果您使用的是Spring Boot,为什么要使用
SessionFactory
。。。改用
EntityManger
。Spring Boot为您预配置了JPA功能,除非您需要一些特定的hibernate功能,请从JPA开始。@M.Deinum,我使用的是
EntityManager
,但出现错误(错误2)请查看更新。不,您没有。。。您正在使用
null
。我强烈建议您阅读您试图使用的框架的文档。。。基本上,你只需要在你的类中声明一个类型为
EntityManager
的字段,将
@PersistenceContext
放在上面,然后就可以完成了,但它仍然对此发出警告。---------此行有多个标记-空指针访问:变量emf只能在此位置为空-局部变量emf可能尚未初始化hanks@M.Deinum,它正在工作。你能不能把它作为一个答案,我会承认这一点。关于这个话题,我在这里找到了更广泛的阐述:@Naros,我有一个问题。在第二个场景中,我们避免使用spring自动配置,我们可以使用hibernate.cfg.xml来创建EntityManagerFactory吗?您应该能够在config类中创建一个
LocalSessionFactoryBean
,然后加载配置资源并调用
LocalSessionFactoryBean#setConfigLocation
来指定它应该在哪里读取其配置,这将是一个指向您的
hibernate.cfg.xml
资源。请看一个例子。