Hibernate 在Spring boot中编写自定义查询
我最近开始使用SpringBoot,遇到了一些问题。以前,当我在hibernate和JPA中使用Spring数据时,我可以创建一个hibernate.cfg.xml文件,该文件将提供一组可传递给配置对象的配置,然后最终创建一个SessionFactory对象,该对象将创建一个会话对象,该对象可用于将查询传递给hibernate:Hibernate 在Spring boot中编写自定义查询,hibernate,spring-boot,hql,Hibernate,Spring Boot,Hql,我最近开始使用SpringBoot,遇到了一些问题。以前,当我在hibernate和JPA中使用Spring数据时,我可以创建一个hibernate.cfg.xml文件,该文件将提供一组可传递给配置对象的配置,然后最终创建一个SessionFactory对象,该对象将创建一个会话对象,该对象可用于将查询传递给hibernate: package util; import org.hibernate.SessionFactory; import org.hibernate.boot.regist
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>
我可以将映射移到属性文件,但我不清楚如何编写查询,因为不再有会话对象。在spring boot应用程序中,您不需要创建xml配置,必须配置java文件本身。 以这个例子为例
import java.util.Properties;
导入javax.sql.DataSource;
导入org.hibernate.annotations.common.util.impl.LoggerFactory;
导入org.springframework.beans.factory.annotation.Value;
导入org.springframework.context.annotation.Bean;
导入org.springframework.context.annotation.Configuration;
导入org.springframework.jdbc.datasource.driverManager数据源;
导入org.springframework.orm.hibernate4.HibernateTransactionManager;
导入org.springframework.orm.hibernate4.LocalSessionFactoryBean;
@配置
公共类数据库配置{
private org.jboss.logging.Logger log=LoggerFactory.Logger(DatabaseConfig.class);
@值(“${db.driver}”)
私有字符串DB_驱动程序;
@值(“${db.username}”)
私有字符串DB_用户名;
@值(${db.password}”)
私有字符串DB_密码;
@值(“${db.url}”)
私有字符串DB_URL;
@值(${hibernate.dial}”)
私有字符串HIBERNATE_方言;
@值(${hibernate.show\u sql}”)
私有字符串HIBERNATE\u SHOW\u SQL;
@值(${hibernate.hbm2ddl.auto}”)
私有字符串休眠\u HBM2DDL\u自动;
@值(${entitymanager.packagesToScan}”)
私有字符串ENTITYMANAGER_包_到_扫描;
@豆子
公共数据源数据源(){
DriverManager数据源数据源=null;
试一试{
dataSource=新的DriverManager数据源();
setDriverClassName(DB_驱动程序);
setUrl(DB_URL);
dataSource.setUsername(DB_用户名);
dataSource.setPassword(DB_密码);
}捕获(例外e){
e、 getMessage();
}
返回数据源;
}
@豆子
公共LocalSessionFactoryBean sessionFactory(){
LocalSessionFactoryBean sessionFactoryBean=新的LocalSessionFactoryBean();
setDataSource(dataSource());
setPackagesToScan(ENTITYMANAGER_包到_扫描);
Properties hibernateProps=新属性();
hibernateProps.put(“hibernate.dial”,hibernate_方言);
hibernateProps.put(“hibernate.show\u sql”,hibernate\u show\u sql);
hibernateProps.put(“hibernate.hbm2ddl.auto”,hibernate\u hbm2ddl\u auto);
setHibernateProperties(hibernateProps);
返回sessionFactoryBean;
}
@豆子
公共HibernateTransactionManager事务管理器(){
HibernateTransactionManager transactionManager=新的HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
返回事务管理器;
}
}
如果您使用Spring Boot+Spring Data JPA,那么您可以通过使用将数据源(现在放在hibernate.cfg.xml中)配置到应用程序.properties
这将自动为您创建一个实体管理器。如果需要使用查询,可以使用Spring Data JPA的存储库,例如:
public interface ArticleRepository extends JpaRepository<Article, Long> {
@Query("select s from Article s where s.author like ?1 and s.title = ?2")
List<Article> findByAuthorAndTitle(String author, String title);
}
这允许您动态创建查询,尽管从您的问题来看,您似乎并不真正需要它。也许您需要自定义方法实现。我在这里解释了解决方案,可能会对您有所帮助
# ===============================
# = 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
public interface ArticleRepository extends JpaRepository<Article, Long> {
@Query("select s from Article s where s.author like ?1 and s.title = ?2")
List<Article> findByAuthorAndTitle(String author, String title);
}
List<Article> articles = repository.findByAuthorAndTitle("Joe%", "Spring boot");
Specification<Article> spec = Specifications.<Article>where((root, query, cb) -> {
return cb.and(
cb.like(root.get("author"), "Joe%"),
cb.equal(root.get("title"), "Spring boot"));
});
List<Article> articles = repository.findAll(spec);