[BAEL-1686] - Commiting final changes

This commit is contained in:
Jorge Collado
2018-05-09 18:35:14 +02:00
committed by José Carlos Valero Sánchez
parent 8a5ff707c5
commit f8b9555e42
12 changed files with 309 additions and 293 deletions

View File

@@ -1,23 +1,26 @@
package com.baeldung;
import com.baeldung.controller.repository.AddressAvailabilityRepository;
import com.baeldung.controller.repository.AddressRepository;
import com.baeldung.controller.repository.PersonRepository;
import com.baeldung.controller.repository.UserRepository;
import com.baeldung.entity.Address;
import com.baeldung.entity.Person;
import com.baeldung.entity.AddressAvailability;
import com.baeldung.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import javax.annotation.PostConstruct;
import java.util.UUID;
@SpringBootApplication @EntityScan("com.baeldung.entity") @EnableJpaRepositories("com.baeldung.controller.repository")
public class Application {
@EnableAutoConfiguration public class Application {
@Autowired private PersonRepository personRepository;
@Autowired private UserRepository personRepository;
@Autowired private AddressRepository addressRepository;
@Autowired private AddressAvailabilityRepository addressAvailabilityRepository;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
@@ -25,15 +28,18 @@ public class Application {
@PostConstruct private void initializeData() {
// Create John
final Address johnsAddress = new Address(UUID.randomUUID().toString(), "Fake Street 1", "Fake Country");
addressRepository.save(johnsAddress);
final Person john = new Person(UUID.randomUUID().toString(), "John", johnsAddress);
final AddressAvailability addressOneAvailability = new AddressAvailability(true, true, false, false, false, true, true);
addressAvailabilityRepository.save(addressOneAvailability);
final User john = new User("John");
personRepository.save(john);
final Address addressOne = new Address("Fake Street 1", "Fake Country", addressOneAvailability, john);
addressRepository.save(addressOne);
// Create Lisa
final Address lisasAddress = new Address(UUID.randomUUID().toString(), "Real Street 1", "Real Country");
addressRepository.save(lisasAddress);
final Person lisa = new Person(UUID.randomUUID().toString(), "Lisa", lisasAddress);
final AddressAvailability addressTwoAvailability = new AddressAvailability(false, false, false, false, false, true, true);
addressAvailabilityRepository.save(addressTwoAvailability);
final User lisa = new User("Lisa");
personRepository.save(lisa);
final Address addressTwo = new Address("Real Street 1", "Real Country", addressTwoAvailability, lisa);
addressRepository.save(addressTwo);
}
}

View File

@@ -1,7 +1,11 @@
package com.baeldung.controller;
import com.baeldung.controller.repository.PersonRepository;
import com.baeldung.entity.Person;
import com.baeldung.controller.repository.AddressAvailabilityRepository;
import com.baeldung.controller.repository.AddressRepository;
import com.baeldung.controller.repository.UserRepository;
import com.baeldung.entity.Address;
import com.baeldung.entity.AddressAvailability;
import com.baeldung.entity.User;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.Predicate;
import org.springframework.beans.factory.annotation.Autowired;
@@ -12,11 +16,26 @@ import org.springframework.web.bind.annotation.RestController;
@RestController public class QueryController {
@Autowired private PersonRepository personRepository;
@Autowired private UserRepository personRepository;
@Autowired private AddressRepository addressRepository;
@Autowired private AddressAvailabilityRepository addressAvailabilityRepository;
@GetMapping(value = "/personQuery", produces = MediaType.APPLICATION_JSON_VALUE)
public Iterable<Person> getFilteredEvents(@QuerydslPredicate(root = Person.class) Predicate predicate) {
@GetMapping(value = "/users", produces = MediaType.APPLICATION_JSON_VALUE)
public Iterable<User> queryOverUser(@QuerydslPredicate(root = User.class) Predicate predicate) {
final BooleanBuilder builder = new BooleanBuilder();
return personRepository.findAll(builder.and(predicate));
}
@GetMapping(value = "/addresses", produces = MediaType.APPLICATION_JSON_VALUE)
public Iterable<Address> queryOverAddress(@QuerydslPredicate(root = Address.class) Predicate predicate) {
final BooleanBuilder builder = new BooleanBuilder();
return addressRepository.findAll(builder.and(predicate));
}
@GetMapping(value = "/addressAvailabilities", produces = MediaType.APPLICATION_JSON_VALUE)
public Iterable<AddressAvailability> queryOverAddressAvailability(
@QuerydslPredicate(root = AddressAvailability.class) Predicate predicate) {
final BooleanBuilder builder = new BooleanBuilder();
return addressAvailabilityRepository.findAll(builder.and(predicate));
}
}

View File

@@ -0,0 +1,19 @@
package com.baeldung.controller.repository;
import com.baeldung.entity.AddressAvailability;
import com.baeldung.entity.QAddressAvailability;
import com.querydsl.core.types.dsl.StringExpression;
import com.querydsl.core.types.dsl.StringPath;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
import org.springframework.data.querydsl.binding.QuerydslBinderCustomizer;
import org.springframework.data.querydsl.binding.QuerydslBindings;
import org.springframework.data.querydsl.binding.SingleValueBinding;
public interface AddressAvailabilityRepository
extends JpaRepository<AddressAvailability, Long>, QueryDslPredicateExecutor<AddressAvailability>,
QuerydslBinderCustomizer<QAddressAvailability> {
@Override default void customize(final QuerydslBindings bindings, final QAddressAvailability root) {
bindings.bind(String.class).first((SingleValueBinding<StringPath, String>) StringExpression::eq);
}
}

View File

@@ -1,7 +1,7 @@
package com.baeldung.controller.repository;
import com.baeldung.entity.Person;
import com.baeldung.entity.QPerson;
import com.baeldung.entity.QUser;
import com.baeldung.entity.User;
import com.querydsl.core.types.dsl.StringExpression;
import com.querydsl.core.types.dsl.StringPath;
import org.springframework.data.jpa.repository.JpaRepository;
@@ -10,9 +10,9 @@ import org.springframework.data.querydsl.binding.QuerydslBinderCustomizer;
import org.springframework.data.querydsl.binding.QuerydslBindings;
import org.springframework.data.querydsl.binding.SingleValueBinding;
public interface PersonRepository
extends JpaRepository<Person, Long>, QueryDslPredicateExecutor<Person>, QuerydslBinderCustomizer<QPerson> {
@Override default void customize(final QuerydslBindings bindings, final QPerson root) {
public interface UserRepository
extends JpaRepository<User, Long>, QueryDslPredicateExecutor<User>, QuerydslBinderCustomizer<QUser> {
@Override default void customize(final QuerydslBindings bindings, final QUser root) {
bindings.bind(String.class).first((SingleValueBinding<StringPath, String>) StringExpression::eq);
}
}

View File

@@ -1,29 +1,36 @@
package com.baeldung.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@Entity public class Address {
import javax.persistence.*;
@Id private String id;
private String address;
private String country;
@Entity @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) public class Address {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", unique = true, nullable = false) private Long id;
@Column private String address;
@Column private String country;
@OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "address_id") @JsonBackReference private AddressAvailability
addressAvailability;
@ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "user_id") @JsonBackReference private User user;
public Address() {
}
public Address(String id, String address, String country) {
public Address(String address, String country, AddressAvailability addressAvailability, User user) {
this.id = id;
this.address = address;
this.country = country;
this.addressAvailability = addressAvailability;
this.user = user;
}
public String getId() {
public Long getId() {
return id;
}
public void setId(String id) {
public void setId(Long id) {
this.id = id;
}
@@ -42,4 +49,12 @@ import javax.persistence.Id;
public void setCountry(String country) {
this.country = country;
}
public AddressAvailability getAddressAvailability() {
return addressAvailability;
}
public void setAddressAvailability(AddressAvailability addressAvailability) {
this.addressAvailability = addressAvailability;
}
}

View File

@@ -0,0 +1,114 @@
package com.baeldung.entity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import javax.persistence.*;
@Table(name = "address_availability") @Entity @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class AddressAvailability {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", unique = true, nullable = false) private Long id;
@Column private Boolean monday;
@Column private Boolean tuesday;
@Column private Boolean wednesday;
@Column private Boolean thursday;
@Column private Boolean friday;
@Column private Boolean saturday;
@Column private Boolean sunday;
@OneToOne(mappedBy = "addressAvailability") @JsonManagedReference private Address address;
public AddressAvailability() {
}
public AddressAvailability(Boolean monday, Boolean tuesday, Boolean wednesday, Boolean thursday, Boolean friday,
Boolean saturday, Boolean sunday) {
this.monday = monday;
this.tuesday = tuesday;
this.wednesday = wednesday;
this.thursday = thursday;
this.friday = friday;
this.saturday = saturday;
this.sunday = sunday;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Boolean getMonday() {
return monday;
}
public void setMonday(Boolean monday) {
this.monday = monday;
}
public Boolean getTuesday() {
return tuesday;
}
public void setTuesday(Boolean tuesday) {
this.tuesday = tuesday;
}
public Boolean getWednesday() {
return wednesday;
}
public void setWednesday(Boolean wednesday) {
this.wednesday = wednesday;
}
public Boolean getThursday() {
return thursday;
}
public void setThursday(Boolean thursday) {
this.thursday = thursday;
}
public Boolean getFriday() {
return friday;
}
public void setFriday(Boolean friday) {
this.friday = friday;
}
public Boolean getSaturday() {
return saturday;
}
public void setSaturday(Boolean saturday) {
this.saturday = saturday;
}
public Boolean getSunday() {
return sunday;
}
public void setSunday(Boolean sunday) {
this.sunday = sunday;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}

View File

@@ -1,48 +0,0 @@
package com.baeldung.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
@Entity public class Person {
@Id private String id;
private String name;
@OneToOne @JoinColumn(name = "address") private com.baeldung.entity.Address address;
public Person() {
}
public Person(String id, String name, com.baeldung.entity.Address address) {
this.id = id;
this.name = name;
this.address = address;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public com.baeldung.entity.Address getAddress() {
return address;
}
public void setAddress(com.baeldung.entity.Address address) {
this.address = address;
}
}

View File

@@ -0,0 +1,46 @@
package com.baeldung.entity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import javax.persistence.*;
import java.util.List;
@Entity @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) public class User {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", unique = true, nullable = false) private Long id;
@Column private String name;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "user") @JsonManagedReference private List<Address> addresses;
public User() {
}
public User(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Address> getAddresses() {
return addresses;
}
public void setAddresses(List<Address> addresses) {
this.addresses = addresses;
}
}

View File

@@ -2,12 +2,10 @@ spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
hikari:
connection-timeout: 60000
maximum-pool-size: 5
pool-name: hikari-pool
url: jdbc:mysql://localhost:3306/baeldung?verifyServerCertificate=false&useSSL=false&requireSSL=false
username: root
password: admin
jpa:
hibernate:
ddl-auto: create-drop
ddl-auto: create

View File

@@ -1,66 +0,0 @@
package com.baeldung.springdatarestquerydsl;
import com.baeldung.Application;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import java.nio.charset.Charset;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = Application.class) @WebAppConfiguration
public class IntegrationTest {
final MediaType contentType =
new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
@Autowired private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before public void setupMockMvc() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test public void givenRequestHasBeenMade_whenQueryOverNameAttribute_thenGetJohn() throws Exception {
// Get John
mockMvc.perform(get("/personQuery?name=John")).andExpect(status().isOk()).andExpect(content().contentType(contentType))
.andExpect(jsonPath("$", hasSize(1))).andExpect(jsonPath("$[0].name", is("John")))
.andExpect(jsonPath("$[0].address.address", is("Fake Street 1")))
.andExpect(jsonPath("$[0].address.country", is("Fake Country")));
}
@Test public void givenRequestHasBeenMade_whenQueryOverNameAttribute_thenGetLisa() throws Exception {
// Get Lisa
mockMvc.perform(get("/personQuery?name=Lisa")).andExpect(status().isOk()).andExpect(content().contentType(contentType))
.andExpect(jsonPath("$", hasSize(1))).andExpect(jsonPath("$[0].name", is("Lisa")))
.andExpect(jsonPath("$[0].address.address", is("Real Street 1")))
.andExpect(jsonPath("$[0].address.country", is("Real Country")));
}
@Test public void givenRequestHasBeenMade_whenQueryWithoutAttribute_thenCorrect() throws Exception {
final MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(),
Charset.forName("utf8"));
mockMvc.perform(get("/personQuery")).andExpect(status().isOk()).andExpect(content().contentType(contentType))
.andExpect(jsonPath("$", hasSize(2)))
// Get John
.andExpect(jsonPath("$[0].name", is("John"))).andExpect(jsonPath("$[0].address.address", is("Fake Street 1")))
.andExpect(jsonPath("$[0].address.country", is("Fake Country")))
// Get Lisa
.andExpect(jsonPath("$[1].name", is("Lisa"))).andExpect(jsonPath("$[1].address.address", is("Real Street 1")))
.andExpect(jsonPath("$[1].address.country", is("Real Country")));
}
}

View File

@@ -0,0 +1,52 @@
package com.baeldung.springdatarestquerydsl;
import com.baeldung.Application;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import java.nio.charset.Charset;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = Application.class) @WebAppConfiguration
public class QuerydslIntegrationTest {
final MediaType contentType =
new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
@Autowired private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before public void setupMockMvc() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test public void givenRequestHasBeenMade_whenQueryAddressFilteringByUserName_thenGetJohn() throws Exception {
mockMvc.perform(get("/addresses?user.name=John")).andExpect(status().isOk()).andExpect(content().contentType(contentType))
.andExpect(jsonPath("$", hasSize(1))).andExpect(jsonPath("$[0].address", is("Fake Street 1")))
.andExpect(jsonPath("$[0].country", is("Fake Country")));
}
@Test public void givenRequestHasBeenMade_whenQueryOverAddressAvailabilityFilteringByAddressCountry_thenGetAvailability()
throws Exception {
mockMvc.perform(get("/addressAvailabilities?address.country=Real Country")).andExpect(status().isOk())
.andExpect(content().contentType(contentType)).andExpect(jsonPath("$", hasSize(1)))
.andExpect(jsonPath("$[0].monday", is(false))).andExpect(jsonPath("$[0].tuesday", is(false)))
.andExpect(jsonPath("$[0].wednesday", is(false))).andExpect(jsonPath("$[0].thursday", is(false)))
.andExpect(jsonPath("$[0].friday", is(false))).andExpect(jsonPath("$[0].saturday", is(true)))
.andExpect(jsonPath("$[0].sunday", is(true)));
}
}