springboot hibernate运行原生sql语句

1.配置文件设置
spring.jpa.properties.hibernate.current_session_context_class = org.springframework.orm.hibernate5.SpringSessionContext

2.创建hibernate sessionFactory config

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;

@Configuration
@EnableAutoConfiguration
@EnableTransactionManagement
public class HibernateAutoConfiguration {
    @Bean
    public SessionFactory sessionFactory(EntityManagerFactory factory) {
        if (factory.unwrap(SessionFactory.class) == null) {
            throw new NullPointerException("factory is not a hibernate factory");
        }
        return factory.unwrap(SessionFactory.class);
    }
}

3.创建dao接口

public interface DemoDao {
    List selectBySql(String sql);
}

4.实现dao

@Repository
public class DemoDaoImpl implements DemoDao {

    @Resource(name = "sessionFactory")
    private SessionFactory sessionFactory;

    @Override
    public List selectBySql(String sql) {
        Session currentSession = sessionFactory.getCurrentSession();
        Query query = currentSession.createSQLQuery(sql);
        return query.list();
    }
}

这样就能在springboot中运行原生sql语句了

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容