【问题标题】:java hibernate storing sql queries in xml filejava hibernate在xml文件中存储sql查询
【发布时间】:2017-04-03 03:06:28
【问题描述】:

我正在尝试将所有 sql 查询放在 xml 文件中。我正在使用 Spring boot 和 hibernate 与本机 sqls

谁能给我提供如何在spring boot和hibernate中从xml文件加载和获取查询字符串的示例。

我在应用程序中使用基于 java 的配置。

配置文件如下所示:

@SpringBootApplication
@PropertySources({
        @PropertySource(value = "classpath:application.properties")
})

@EnableAutoConfiguration`enter code here`
@Configuration
public class BootApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(BootApplication.class);
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(BootApplication.class, args);
    }

    @Bean
    public SessionFactory sessionFactory(HibernateEntityManagerFactory hemf) {
        return hemf.getSessionFactory();
    }
}

xml文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<properties>
    <entry key="getUsersById">
        <![CDATA[
        Select * From User
        Where id =?
    ]]>

    </entry>
    <entry key="getPersonBySSN">
        <![CDATA[
    ]]>
    </entry>
</properties>

下面是Java hibernate代码,没有将sql移动到xml文件。我需要将sqls移动到xml,因为应用程序中有很多查询。

public List<User> getUsers(String id) {
                List<User> users = new ArrayList<User>();
                try {
                    String sql = "Select * From User Where id =?";
                    SQLQuery query = getSession().createSQLQuery(sql);
                    query.setParameter(0, id);                  query.setResultTransformer(Transformers.aliasToBean(User.class))
                    users = (List<User>) query.list();
                } catch (Exception e) {
                    logger.error("Error", e);
                }
                return users;
            }

有人可以提供示例,将 sql 查询移动到 xml 文件并使用它的 java 代码吗?

【问题讨论】:

    标签: java xml hibernate spring-boot spring-ioc


    【解决方案1】:

    为什么只使用命名查询:

    <sql-query name="getUsersById">
        <return alias="user" class="your class"/>
        <![CDATA[ Select * From User
            Where id =?]]>
    </sql-query>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-19
      • 2020-02-11
      • 1970-01-01
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      相关资源
      最近更新 更多