1

I created a Spring project and I would like to create multiple queries on a single file. After googling, I found this link https://www.petrikainulainen.net/programming/spring-framework/spring-data-jpa-tutorial-creating-database-queries-with-named-queries/

So, I should create the file orm.xml:

<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings
        xmlns="http://java.sun.com/xml/ns/persistence/orm"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_2_0.xsd"
        version="2.0">

    <named-query name="Todo.findByTitleIs">
        <query>SELECT t FROM Todo t WHERE t.title = 'title'</query>
    </named-query>
</entity-mappings>

Then, the interface TodoRepository.java

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;

import java.util.List;

interface TodoRepository extends Repository<Todo, Long> {

    @Query(nativeQuery = true)
    public List<Todo> findByTitleIs();
}

The spring.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="employeeDAO" class="com.journaldev.spring.jdbc.dao.EmployeeDAOImpl">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean id="employeeDAOJDBCTemplate" class="com.journaldev.spring.jdbc.dao.EmployeeDAOJDBCTemplateImpl">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean id="todoRepositoryBean" class="com.journaldev.spring.jdbc.dao.TodoRepositoryBeanImpl">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/springdb" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>

</beans>

The class SpringMain.java is:

public class SpringMain {

    public static void main(String[] args) 
    {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
        EmployeeDAO employeeDAO = ctx.getBean("todoRepositoryBean", EmployeeDAO.class);
        List<Employee> les = employeeDAO.getAll();
        System.out.println("The list size is: + les.size()"); 
        ctx.close();
    }
}

I think it was useful but I found a problem: How can I use the named query Todo.findByTitleIs on main class?

kryger
  • 12,906
  • 8
  • 44
  • 65
Rosa
  • 31
  • 10
  • 1
    Why would you want to put queries on the main class in the first place? Also, please take a look at the documentation, and I think that using annotations will improve your experience: http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.named-queries – Alexey Soshin Aug 28 '16 at 17:45
  • I agree, I think annotations would make the whole thing easier. Anyway, if you actually need the query in the main class (just why?) you can get your TodoRepository from the ApplicationContext, since it will simply be a bean. – Florian Schaetz Aug 28 '16 at 17:57
  • Hello, yes I need the query in the bean class not necessary in the main class. I added the files spring.xml and SpringMain.java in my question. Now I'm asking if you can give me an example of the class TodoRepositoryBeanImpl that should implement TodoRepository. Thanks for your help. – Rosa Aug 28 '16 at 18:51
  • If your query is SQL (i.e nativeQuery) then you should use "named-native-query" in the `orm.xml`. FWIW Whether to use annotations or XML is simply personal preference and irrelevant to this question; ample reasons for using XML. – Neil Stockton Aug 29 '16 at 08:26

1 Answers1

2

The tutorials of Petri Kainulainen are really good and you should achieve your goal by reading this one:

https://www.petrikainulainen.net/programming/spring-framework/spring-data-jpa-tutorial-part-eight-adding-functionality-to-a-repository/

He explaines how to implement the TodoRepository class.

To use queries defined in your repository, if you are developing a rest web app, you could use a @Controller class to handle the single functionalities (e.g. TodoController). In the controller you can autowire the repository:

@Autowired private TodoRepository todoRepository;

and then use it in your methods:

public void doSomething() { List<Todo> todoList = todoRepository.findByTitleIs(); }

Remember that you can autowire beans only in spring managed classes (Repository, Service, Controller, Component, Configuration ecc)

Otherwise you could get the repository directly from the ApplicationContext, but it's not recommended:

Why is Spring's ApplicationContext.getBean considered bad?

Personally i use this method only for testing purpose (to create a main test class).

Then i suggest you to write your queries directly in the repository interface, to me it's much simplier (this way you can avoid using the orm.xml file). For example:

@Repository
public interface TodoRepository extends JpaRepository<Todo, Long> {

       // define your custom query
        @Query("SELECT t FROM Todo t WHERE t.title = :title")
        public List<Todo> findByTitleIs(@Param("title") String title);


        // write here all the Todo queries
    }

You can also use the query creation from method names mechanism, and write the previous query like this:

public List<Todo> findByTitle(String title);

http://docs.spring.io/spring-data/jpa/docs/1.4.3.RELEASE/reference/html/jpa.repositories.html

Community
  • 1
  • 1
amicoderozer
  • 2,046
  • 6
  • 28
  • 44
  • Hello @amicoderozer, I agree that using annotations (@Query) is easier than using the method of orm.xml, but, now I'm trying to master both of them (at least working with the 2 ways). your reply seems so helpful, but if you don't mind, could you please tell me how mapping the file orm.xml to the file spring.xml – Rosa Aug 29 '16 at 13:42
  • if i understand correctly what you are asking, the accepted answer to this question should be helpful. http://stackoverflow.com/questions/12252088/unable-to-import-persistence-xml-within-applicationcontext-xml-file – amicoderozer Aug 29 '16 at 14:28