Samples for the Intro to QueryDSL article, merged with existing querydsl module. Updated module dependencies. (#476)

This commit is contained in:
Sergey Petunin 2016-07-06 01:44:00 +06:00 committed by Grzegorz Piwowarek
parent 010c6b3ace
commit 89373cd1eb
7 changed files with 377 additions and 59 deletions

View File

@ -14,30 +14,25 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.6</java.version>
<junit.version>4.10</junit.version>
<spring.version>3.1.0.RELEASE</spring.version>
<hibernate.version>4.3.11.Final</hibernate.version>
<querydsl.version>2.5.0</querydsl.version>
<slf4j.version>1.5.10</slf4j.version>
<java.version>1.8</java.version>
<junit.version>4.12</junit.version>
<spring.version>4.3.1.RELEASE</spring.version>
<hibernate.version>5.2.1.Final</hibernate.version>
<querydsl.version>4.1.3</querydsl.version>
<slf4j.version>1.7.21</slf4j.version>
</properties>
<dependencies>
<!-- QueryDSL -->
<dependency>
<groupId>com.mysema.querydsl</groupId>
<artifactId>querydsl-core</artifactId>
<version>${querydsl.version}</version>
</dependency>
<dependency>
<groupId>com.mysema.querydsl</groupId>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
<version>${querydsl.version}</version>
</dependency>
<dependency>
<groupId>com.mysema.querydsl</groupId>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>${querydsl.version}</version>
<scope>provided</scope>
@ -53,7 +48,7 @@
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
<scope>compile</scope>
</dependency>
@ -69,7 +64,7 @@
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.5.5</version>
<version>1.6</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
@ -77,8 +72,8 @@
<!-- HSQLDB Dependencies -->
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb-j5</artifactId>
<version>2.2.4</version>
<artifactId>hsqldb</artifactId>
<version>2.3.4</version>
</dependency>
<!-- Spring Dependencies -->
@ -118,9 +113,9 @@
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
@ -128,17 +123,6 @@
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<!-- Test Dependencies -->
<dependency>
@ -157,7 +141,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<version>3.5.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
@ -168,16 +152,16 @@
<!-- QueryDSL plugin -->
<plugin>
<groupId>com.mysema.maven</groupId>
<artifactId>maven-apt-plugin</artifactId>
<version>1.0.3</version>
<artifactId>apt-maven-plugin</artifactId>
<version>1.1.3</version>
<executions>
<execution>
<goals>
<goal>process</goal>
</goals>
<configuration>
<outputDirectory>target/metamodel</outputDirectory>
<processor>com.mysema.query.apt.jpa.JPAAnnotationProcessor</processor>
<outputDirectory>target/generated-sources/java</outputDirectory>
<processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
</configuration>
</execution>
</executions>

View File

@ -10,8 +10,8 @@ import org.baeldung.entity.Person;
import org.baeldung.entity.QPerson;
import org.springframework.stereotype.Repository;
import com.mysema.query.group.GroupBy;
import com.mysema.query.jpa.impl.JPAQuery;
import com.querydsl.core.group.GroupBy;
import com.querydsl.jpa.impl.JPAQuery;
@Repository
public class PersonDaoImpl implements PersonDao {
@ -27,39 +27,39 @@ public class PersonDaoImpl implements PersonDao {
@Override
public List<Person> findPersonsByFirstnameQueryDSL(final String firstname) {
final JPAQuery query = new JPAQuery(em);
final JPAQuery<Person> query = new JPAQuery<>(em);
final QPerson person = QPerson.person;
return query.from(person).where(person.firstname.eq(firstname)).list(person);
return query.from(person).where(person.firstname.eq(firstname)).fetch();
}
@Override
public List<Person> findPersonsByFirstnameAndSurnameQueryDSL(final String firstname, final String surname) {
final JPAQuery query = new JPAQuery(em);
final JPAQuery<Person> query = new JPAQuery<>(em);
final QPerson person = QPerson.person;
return query.from(person).where(person.firstname.eq(firstname).and(person.surname.eq(surname))).list(person);
return query.from(person).where(person.firstname.eq(firstname).and(person.surname.eq(surname))).fetch();
}
@Override
public List<Person> findPersonsByFirstnameInDescendingOrderQueryDSL(final String firstname) {
final JPAQuery query = new JPAQuery(em);
final JPAQuery<Person> query = new JPAQuery<>(em);
final QPerson person = QPerson.person;
return query.from(person).where(person.firstname.eq(firstname)).orderBy(person.surname.desc()).list(person);
return query.from(person).where(person.firstname.eq(firstname)).orderBy(person.surname.desc()).fetch();
}
@Override
public int findMaxAge() {
final JPAQuery query = new JPAQuery(em);
final JPAQuery<Person> query = new JPAQuery<>(em);
final QPerson person = QPerson.person;
return query.from(person).list(person.age.max()).get(0);
return query.from(person).select(person.age.max()).fetchFirst();
}
@Override
public Map<String, Integer> findMaxAgeByName() {
final JPAQuery query = new JPAQuery(em);
final JPAQuery<Person> query = new JPAQuery<>(em);
final QPerson person = QPerson.person;
return query.from(person).transform(GroupBy.groupBy(person.firstname).as(GroupBy.max(person.age)));

View File

@ -0,0 +1,56 @@
/*
* (c) Центр ИТ, 2016. Все права защищены.
*/
package org.baeldung.querydsl.intro.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@Entity
public class BlogPost {
@Id
@GeneratedValue
private Long id;
private String title;
private String body;
@ManyToOne
private User user;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String code) {
this.title = code;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}

View File

@ -0,0 +1,55 @@
/*
* (c) Центр ИТ, 2016. Все права защищены.
*/
package org.baeldung.querydsl.intro.entities;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.*;
@Entity
public class User {
@Id
@GeneratedValue
private Long id;
private String login;
private Boolean disabled;
@OneToMany(cascade = CascadeType.PERSIST, mappedBy = "user")
private Set<BlogPost> blogPosts = new HashSet<>(0);
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String name) {
this.login = name;
}
public Set<BlogPost> getBlogPosts() {
return blogPosts;
}
public void setBlogPosts(Set<BlogPost> blogPosts) {
this.blogPosts = blogPosts;
}
public Boolean getDisabled() {
return disabled;
}
public void setDisabled(Boolean disabled) {
this.disabled = disabled;
}
}

View File

@ -16,4 +16,17 @@
</properties>
</persistence-unit>
<!-- PersistenceUnit for Intro to QueryDSL -->
<persistence-unit name="org.baeldung.querydsl.intro">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:mem:test"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />
</properties>
</persistence-unit>
</persistence>

View File

@ -1,12 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<configuration>
<!-- Appenders -->
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p: %c - %m%n" />
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p: %c - %m%n</Pattern>
</layout>
</appender>
@ -33,10 +30,8 @@
<level value="warn" />
</logger>
<!-- Root Logger -->
<root>
<priority value="warn" />
<appender-ref ref="console" />
<root level="warn">
<appender-ref ref="STDOUT"/>
</root>
</log4j:configuration>
</configuration>

View File

@ -0,0 +1,215 @@
/*
* (c) Центр ИТ, 2016. Все права защищены.
*/
package org.baeldung.querydsl.intro;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.baeldung.querydsl.intro.entities.BlogPost;
import org.baeldung.querydsl.intro.entities.QBlogPost;
import org.baeldung.querydsl.intro.entities.QUser;
import org.baeldung.querydsl.intro.entities.User;
import com.querydsl.core.Tuple;
import com.querydsl.core.types.dsl.Expressions;
import com.querydsl.core.types.dsl.NumberPath;
import com.querydsl.jpa.JPAExpressions;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.junit.*;
import static org.junit.Assert.*;
public class QueryDSLTest {
private static EntityManagerFactory emf;
private EntityManager em;
private JPAQueryFactory queryFactory;
@BeforeClass
public static void populateDatabase() {
emf = Persistence.createEntityManagerFactory("org.baeldung.querydsl.intro");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
User user1 = new User();
user1.setLogin("David");
em.persist(user1);
User user2 = new User();
user2.setLogin("Ash");
em.persist(user2);
User user3 = new User();
user3.setLogin("Call");
em.persist(user3);
User user4 = new User();
user4.setLogin("Bishop");
em.persist(user4);
BlogPost blogPost1 = new BlogPost();
blogPost1.setTitle("Hello World!");
blogPost1.setUser(user1);
em.persist(blogPost1);
BlogPost blogPost2 = new BlogPost();
blogPost2.setTitle("My Second Post");
blogPost2.setUser(user1);
em.persist(blogPost2);
BlogPost blogPost3 = new BlogPost();
blogPost3.setTitle("Hello World!");
blogPost3.setUser(user3);
em.persist(blogPost3);
em.getTransaction().commit();
em.close();
}
@Before
public void setUp() {
em = emf.createEntityManager();
em.getTransaction().begin();
queryFactory = new JPAQueryFactory(em);
}
@Test
public void whenFindByLogin_thenShouldReturnUser() {
QUser user = QUser.user;
User aUser = queryFactory.selectFrom(user)
.where(user.login.eq("David"))
.fetchOne();
assertNotNull(aUser);
assertEquals(aUser.getLogin(), "David");
}
@Test
public void whenUsingOrderBy_thenResultsShouldBeOrdered() {
QUser user = QUser.user;
List<User> users = queryFactory.selectFrom(user)
.orderBy(user.login.asc())
.fetch();
assertEquals(users.size(), 4);
assertEquals(users.get(0).getLogin(), "Ash");
assertEquals(users.get(1).getLogin(), "Bishop");
assertEquals(users.get(2).getLogin(), "Call");
assertEquals(users.get(3).getLogin(), "David");
}
@Test
public void whenGroupingByTitle_thenReturnsTuples() {
QBlogPost blogPost = QBlogPost.blogPost;
NumberPath<Long> count = Expressions.numberPath(Long.class, "c");
List<Tuple> userTitleCounts = queryFactory.select(blogPost.title, blogPost.id.count().as(count))
.from(blogPost)
.groupBy(blogPost.title)
.orderBy(count.desc())
.fetch();
assertEquals("Hello World!", userTitleCounts.get(0).get(blogPost.title));
assertEquals(new Long(2), userTitleCounts.get(0).get(count));
assertEquals("My Second Post", userTitleCounts.get(1).get(blogPost.title));
assertEquals(new Long(1), userTitleCounts.get(1).get(count));
}
@Test
public void whenJoiningWithCondition_thenResultCountShouldMatch() {
QUser user = QUser.user;
QBlogPost blogPost = QBlogPost.blogPost;
List<User> users = queryFactory.selectFrom(user)
.innerJoin(user.blogPosts, blogPost)
.on(blogPost.title.eq("Hello World!"))
.fetch();
assertEquals(2, users.size());
}
@Test
public void whenRefiningWithSubquery_thenResultCountShouldMatch() {
QUser user = QUser.user;
QBlogPost blogPost = QBlogPost.blogPost;
List<User> users = queryFactory.selectFrom(user)
.where(user.id.in(
JPAExpressions.select(blogPost.user.id)
.from(blogPost)
.where(blogPost.title.eq("Hello World!"))))
.fetch();
assertEquals(2, users.size());
}
@Test
public void whenUpdating_thenTheRecordShouldChange() {
QUser user = QUser.user;
queryFactory.update(user)
.where(user.login.eq("Ash"))
.set(user.login, "Ash2")
.set(user.disabled, true)
.execute();
em.getTransaction().commit();
em.getTransaction().begin();
assertEquals(Boolean.TRUE,
queryFactory.select(user.disabled)
.from(user)
.where(user.login.eq("Ash2"))
.fetchOne());
}
@Test
public void whenDeleting_thenTheRecordShouldBeAbsent() {
QUser user = QUser.user;
queryFactory.delete(user)
.where(user.login.eq("Bishop"))
.execute();
em.getTransaction().commit();
em.getTransaction().begin();
assertNull(queryFactory.selectFrom(user)
.where(user.login.eq("Bishop"))
.fetchOne());
}
@After
public void tearDown() {
em.getTransaction().commit();
em.close();
}
@AfterClass
public static void afterClass() {
emf.close();
}
}