【发布时间】:2016-03-22 02:11:31
【问题描述】:
我最近开始使用 Spring boot,但遇到了一些问题。以前,当我只是将 Spring 数据与 hibernate 和 JPA 一起使用时,我可以创建一个 hibernate.cfg.xml 文件,该文件将提供一堆可以传递给配置对象的配置,然后最终创建一个 SessionFactory 对象,该对象将创建一个可用于将查询传递给休眠的会话对象:
package util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration().configure("hibernate.cfg.xml"); return configuration.buildSessionFactory( new
StandardServiceRegistryBuilder().applySettings( configuration.getProperties() ).build() );
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() { return sessionFactory; }
}
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hello-world</property>
<property name="connection.username">root</property>
<property name="connection.password">password</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Create/update tables automatically using mapping metadata -->
<property name="hbm2ddl.auto">update</property>
<!-- Use Annotation-based mapping metadata -->
<mapping class="entity.Author"/>
<mapping class="entity.Article"/>
</session-factory>
</hibernate-configuration>
Main.java
public class HelloWorldClient {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction txn = session.getTransaction();
EntityManagerFactory emf = Persiscance.createEntityManagerFactory("hibernate.cfg.xml");
EntityManager em = emf.createEntityManager();
EntityTransaction txn = em.getTransaction();
try {
txn.begin();
Author author = new Author("name", listOfArticlesWritten);
Article article = new Article("Article Title", author);
session.save(author);
session.save(article);
Query query = session.createQuery("select distinct a.authorName from Article s
where s.author like "Joe%" and title = 'Spring boot');
List<Article> articles = query.list();
txn.commit();
} catch(Exception e) {
if(txn != null) { txn.rollback(); }
e.printStackTrace();
} finally {
if(session != null) { session.close(); } }
}
}
这就是问题出现的地方。我不知道如何避免为自定义查询创建 hibernate.cfg.xml 文件或会话工厂。在 Spring 指南页面和我已经完成的一些教程中,他们采用了他们的 DAO 并扩展了 CrudRepository 接口,该接口已经提供了一堆方法,以及一种命名方法的方法,以便 Hibernate 可以自己构建 sql .
我想要完成的,至少在这篇文章中是能够在 Spring Boot 中执行上述查询。我可以创建一个属性文件
application.properties
# ===============================
# = DATA SOURCE
# ===============================
# Set here configurations for the database connection
spring.datasource.url = jdbc:mysql://localhost:3306/spring-boot-demo
spring.datasource.username = test
spring.datasource.password = test
# Mysql connector
spring.datasource.driverClassName = com.mysql.jdbc.Driver
# ===============================
# = JPA / HIBERNATE
# ===============================
# Specify the DBMS
spring.jpa.database = MYSQL
# Show or not log for each sql query
spring.jpa.show-sql = true
# Ddl auto must be set to "create" to ensure that Hibernate will run the
# import.sql file at application startup
#create-drop| update | validate | none
spring.jpa.hibernate.ddl-auto = update
# SQL dialect for generating optimized queries
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
# ===============================
# = THYMELEAF
# ===============================
spring.thymeleaf.cache = false
#debug=true
我可以将除映射之外的所有内容移至属性文件,但由于不再有会话对象,我不清楚如何编写查询。
【问题讨论】:
-
也许你需要自定义方法实现。 this is an stackoverflow answer
-
我在这里解释了解决方案,可能对你有帮助stackoverflow.com/a/48854352/4720910
标签: hibernate spring-boot hql