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语句了

原文地址:https://www.jianshu.com/p/7f4a6ee0d7ec

猜你喜欢

转载自blog.csdn.net/qq_32649581/article/details/84064599
今日推荐