10 Ekim 2022 Pazartesi

SpringData QueryDSL Kullanımı

Giriş
QueryDSL dinamik sorguları kolaylaştırır.
1. Maven veya gradle dependency eklenir
2. JPA Entity tanımlanır
3.  Q Sınıfları için kod üretilir
4. QuerydslPredicateExecutor sınıfından kalıtan bir repository yaratılır veya
JPAQueryFactory direkt kullanılır

Maven
Örnek
Şöyle yaparız
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Query DSL -->
<dependency>
  <groupId>com.querydsl</groupId>
  <artifactId>querydsl-apt</artifactId>
</dependency>
<dependency>
  <groupId>com.querydsl</groupId>
  <artifactId>querydsl-jpa</artifactId>
</dependency>
Örnek
Şöyle yaparız. Burada querydsl-apt provided olarak belirtiliyor.
<dependency>
  <groupId>com.querydsl</groupId>
  <artifactId>querydsl-jpa</artifactId>
  <version>5.0.0</version>
</dependency>
<dependency>
  <groupId>com.querydsl</groupId>
  <artifactId>querydsl-apt</artifactId>
  <version>5.0.0</version>
  <scope>provided</scope>
</dependency>

Maven Plugin
Örnek - JPAAnnotationProcessor
Şöyle yaparız
<plugin>
  <groupId>com.mysema.maven</groupId>
<artifactId>apt-maven-plugin</artifactId>
<version>1.1.3</version>
<executions>
<execution>
<goals>
<goal>process</goal>
</goals>
<configuration>
<outputDirectory>target/generated-sources/java</outputDirectory>
<processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
</configuration>
</execution>
</executions>
</plugin>
Kod üretmek için şöyle yaparız
mvn clean compile
JPAQueryFactory Kullanımı
Örnek
Şöyle yaparız
mport com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import java.util.List;

@Repository
public class PersonRepository {

    @Autowired
    private EntityManager entityManager;

    public List<Person> findPeopleByLastName(String lastName) {
        JPAQueryFactory queryFactory = new JPAQueryFactory(entityManager);
        QPerson person = QPerson.person;
        return queryFactory.selectFrom(person)
                .where(person.lastName.eq(lastName))
                .fetch();
    }
}
Test için şöyle yaparız
import com.querydsl.jpa.impl.JPAQueryFactory;

@SpringBootTest
@ActiveProfiles("test")
@Transactional
public class PersonRepositoryTest {

  @Autowired
  private PersonRepository personRepository;

  @Autowired
  private EntityManager entityManager;

  @Test
  void testFindPeopleByLastName() {
    Person person1 = new Person();
    person1.setFirstName("John");
    person1.setLastName("Smith");
    entityManager.persist(person1);

    Person person2 = new Person();
    person2.setFirstName("Jane");
    person2.setLastName("Doe");
    entityManager.persist(person2);

    List<Person> result = personRepository.findPeopleByLastName("Smith");

    assertThat(result).hasSize(1);
    assertThat(result.get(0).getFirstName()).isEqualTo("John");
    assertThat(result.get(0).getLastName()).isEqualTo("Smith");
  }
}


QuerydslPredicateExecutor Kullanımı
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.core.types.dsl.DatePath;
import com.querydsl.core.types.dsl.NumberPath;
import com.querydsl.core.types.dsl.PathBuilder;
import com.querydsl.core.types.dsl.StringPath;
gibi sınıflar ile bir path yaratılır

Örnek
Bir örnek burada.

Örnek
Elimizde şöyle bir Entity olsun
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;

import com.vladmihalcea.hibernate.type.json.JsonType;

import lombok.Data;

@Entity
@Table(name = "abhi_roles")
@Data
@TypeDef(name = "json", typeClass = JsonType.class)
public class Roles implements Serializable {

  private static final long serialVersionUID = 1L;
	
  @Id
  @Column(name = "employeeId", length = 10)
  private String employeeId;

  @Column(name = "username")
  private String username;

  @Type(type = "json")
  @Column(name = "roles", columnDefinition = "json")
  private List<String> roles;
}
Şöyle yaparız
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
@Repository public interface RolesRepository extends JpaRepository<Roles, String>, QuerydslPredicateExecutor<Roles> { }
Service kısmında şöyle yaparız
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.core.types.dsl.Expressions;

@Service
public class RolesService {

  @Autowired
  RolesRepository repository;

  public List<Roles> findUsersWithRoles(String role) {
    QRoles userRolesPath = QRoles.roles1;
    BooleanExpression exp = Expressions
      .booleanTemplate("json_contains_key({0}, {1})", userRolesPath.roles, 
        Expressions.constant(role))
      .isTrue();
    Iterable<Roles> lr = repository.findAll(exp);
List<Roles> result = new ArrayList<>(); lr.forEach(result::add); return result; } }

Hiç yorum yok:

Yorum Gönder