我在Spring启动应用程序的application.properties
文件中配置了hibernate属性。
application.properties
#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
当我尝试将会话作为
时,我收到错误Configuration configuration = new Configuration();
configuration.configure("application.properties");
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration.buildSessionFactory(ssrb.build());
Session session = sessionFactory.openSession();
错误:
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.
我认为它在类路径中也期待hibernate.cfg.xml
个文件?
有什么方法我只能使用application.properties
或者我必须将所有与休眠相关的属性移动到hibernate.cfg.xml
或hibernate.properties
文件?
getSelectedStudents
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;
}
错误2:
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]
编辑:
建议使用实体管理器,我添加了getSelectedStudents方法。我仍在EntityManager em = emf.createEntityManager();
收到错误
有关详细信息,请参阅错误2。
答案 0 :(得分:1)
如果你在带有spring-autoconfigure的tandum中使用spring-boot,你可以简单地将Hibernate库放到你的类路径上,spring会自动连接Hibernate。您需要做的就是在application.properties文件中提供一些spring jpa配置设置,然后就完成了。
如果您想避免使用spring-autoconfigure,那么您需要添加一个构造LocalContainerEntityManagerFactoryBean
,JpaTransactionManager
和DataSource
的配置类。
在任何一种情况下,要在您的应用程序中使用JPA,您只需要在存储库或服务类中添加带注释的属性,以便为EntityManager
获取实例,如下所示:
@PersistentContext
private EntityManager entityManager;
Spring会确保为您注入此内容,您的代码只需根据需要使用它。
答案 1 :(得分:0)
实施例。在配置类中,您需要调用@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;
}
}
在你&#34; application.properties&#34;文件有这个。
################ 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