简体   繁体   中英

java hibernate storing sql queries in xml file

I am trying to place all sql queries in xml file.I am using Spring boot and hibernate with native sqls

Can someone provide me the example how to load and get the query string from xml file in spring boot and hibernate.

I am using java based configuration in the application.

The configuration file looks like below:

@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 file is below:

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

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

Below is the Java hibernate code without moving sql to xml file.I need to move sqls to xml as there are lot of queries in the application.

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;
            }

Can someone please provide example to it move the sql queries to xml file and use it java code?

Why just use named query:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM