0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JPQLでLIMIT, OFFSET

Posted at

やりたいこと

Personテーブル(カラムはid, name, age)に100件レコードを用意し、指定した位置から任意の数だけレコードを取得したい。

@PostConstruct
	public void init() {
		for(int i = 1; i < 101; i++) {
			Person p = new Person("テストユーザー" + i, 18); //100人とも永遠の18さ(ry
			repository.saveAndFlush(p);
		}
	}

問題

public List<Person> find(){
		List<Person> list = null;
		String str = "from Person limit 20 offset 10";
		Query query = en.createQuery(str);
		list = (List<Person>)query.getResultList();
		return list;
	}

こんな感じで適当に11行目から20件取得しようとしたら、

There was an unexpected error (type=Internal Server Error, status=500).
org.hibernate.hql.internal.ast.QuerySyntaxException: 
unexpected token: 20 near line 1, column 36 [from com.example.demo.Person limit 20 offset 10]

構文エラーだと。。。

解決策

JPQLだと、

OFFSET => setFirstResult(n)
LIMIT => setMaxResults(n)

って記述らしい。。。
調べが足りなかった。

public List<Person> find(){
		List<Person> list = null;
		String str = "from Person";
		Query query = en.createQuery(str).setFirstResult(10).setMaxResults(20);
		list = (List<Person>)query.getResultList();
		return list;
	}

キャプチャ.PNG

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?