formatting work
This commit is contained in:
parent
eb7650eead
commit
856be0a08a
|
@ -29,5 +29,4 @@ public class SpringExtension extends AbstractExtensionId<SpringExtension.SpringE
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -27,9 +27,7 @@ public class SpringAkkaTest extends AbstractJUnit4SpringContextTests {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCallingGreetingActor_thenActorGreetsTheCaller() throws Exception {
|
public void whenCallingGreetingActor_thenActorGreetsTheCaller() throws Exception {
|
||||||
ActorRef greeter = system.actorOf(
|
ActorRef greeter = system.actorOf(SPRING_EXTENSION_PROVIDER.get(system).props("greetingActor"), "greeter");
|
||||||
SPRING_EXTENSION_PROVIDER.get(system)
|
|
||||||
.props("greetingActor"), "greeter");
|
|
||||||
|
|
||||||
FiniteDuration duration = FiniteDuration.create(1, TimeUnit.SECONDS);
|
FiniteDuration duration = FiniteDuration.create(1, TimeUnit.SECONDS);
|
||||||
Timeout timeout = Timeout.durationToTimeout(duration);
|
Timeout timeout = Timeout.durationToTimeout(duration);
|
||||||
|
|
|
@ -12,20 +12,20 @@ import org.springframework.web.servlet.DispatcherServlet;
|
||||||
|
|
||||||
public class StudentControllerConfig implements WebApplicationInitializer {
|
public class StudentControllerConfig implements WebApplicationInitializer {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onStartup(ServletContext sc) throws ServletException {
|
public void onStartup(ServletContext sc) throws ServletException {
|
||||||
AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
|
AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
|
||||||
root.register(WebConfig.class);
|
root.register(WebConfig.class);
|
||||||
|
|
||||||
root.setServletContext(sc);
|
root.setServletContext(sc);
|
||||||
|
|
||||||
// Manages the lifecycle of the root application context
|
// Manages the lifecycle of the root application context
|
||||||
sc.addListener(new ContextLoaderListener(root));
|
sc.addListener(new ContextLoaderListener(root));
|
||||||
|
|
||||||
DispatcherServlet dv = new DispatcherServlet(new GenericWebApplicationContext());
|
DispatcherServlet dv = new DispatcherServlet(new GenericWebApplicationContext());
|
||||||
|
|
||||||
ServletRegistration.Dynamic appServlet = sc.addServlet("test-mvc", dv);
|
ServletRegistration.Dynamic appServlet = sc.addServlet("test-mvc", dv);
|
||||||
appServlet.setLoadOnStartup(1);
|
appServlet.setLoadOnStartup(1);
|
||||||
appServlet.addMapping("/test/*");
|
appServlet.addMapping("/test/*");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -11,7 +11,7 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver;
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
@EnableWebMvc
|
@EnableWebMvc
|
||||||
@ComponentScan(basePackages= {"org.baeldung.controller.controller","org.baeldung.controller.config" })
|
@ComponentScan(basePackages = { "org.baeldung.controller.controller", "org.baeldung.controller.config" })
|
||||||
public class WebConfig extends WebMvcConfigurerAdapter {
|
public class WebConfig extends WebMvcConfigurerAdapter {
|
||||||
@Override
|
@Override
|
||||||
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
|
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
|
||||||
|
|
|
@ -7,15 +7,15 @@ import org.springframework.web.bind.annotation.PathVariable;
|
||||||
import org.springframework.web.bind.annotation.ResponseBody;
|
import org.springframework.web.bind.annotation.ResponseBody;
|
||||||
|
|
||||||
@Controller
|
@Controller
|
||||||
public class RestController{
|
public class RestController {
|
||||||
|
|
||||||
@GetMapping(value="/student/{studentId}")
|
@GetMapping(value = "/student/{studentId}")
|
||||||
public @ResponseBody Student getTestData(@PathVariable Integer studentId) {
|
public @ResponseBody Student getTestData(@PathVariable Integer studentId) {
|
||||||
Student student = new Student();
|
Student student = new Student();
|
||||||
student.setName("Peter");
|
student.setName("Peter");
|
||||||
student.setId(studentId);
|
student.setId(studentId);
|
||||||
|
|
||||||
return student;
|
return student;
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,33 +1,33 @@
|
||||||
package org.baeldung.controller.student;
|
package org.baeldung.controller.student;
|
||||||
|
|
||||||
public class Student {
|
public class Student {
|
||||||
private String name;
|
private String name;
|
||||||
|
|
||||||
private int id;
|
private int id;
|
||||||
|
|
||||||
public String getName() {
|
public String getName() {
|
||||||
return name;
|
return name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setName(String name) {
|
public void setName(String name) {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getId() {
|
public int getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setId(int id) {
|
public void setId(int id) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int hashCode(){
|
public int hashCode() {
|
||||||
return this.id;
|
return this.id;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean equals(Object obj){
|
public boolean equals(Object obj) {
|
||||||
return this.name.equals(((Student)obj).getName());
|
return this.name.equals(((Student) obj).getName());
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -11,7 +11,6 @@ public class PropertiesWithPlaceHolderConfigurer {
|
||||||
super();
|
super();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public PropertyPlaceholderConfigurer propertyConfigurer() {
|
public PropertyPlaceholderConfigurer propertyConfigurer() {
|
||||||
final PropertyPlaceholderConfigurer props = new PropertyPlaceholderConfigurer();
|
final PropertyPlaceholderConfigurer props = new PropertyPlaceholderConfigurer();
|
||||||
|
|
|
@ -2,14 +2,14 @@ package org.baeldung.scopes;
|
||||||
|
|
||||||
public class HelloMessageGenerator {
|
public class HelloMessageGenerator {
|
||||||
|
|
||||||
private String message;
|
private String message;
|
||||||
|
|
||||||
public String getMessage() {
|
public String getMessage() {
|
||||||
return message;
|
return message;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setMessage(final String message) {
|
public void setMessage(final String message) {
|
||||||
this.message = message;
|
this.message = message;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,27 +1,27 @@
|
||||||
package org.baeldung.scopes;
|
package org.baeldung.scopes;
|
||||||
|
|
||||||
public class Person {
|
public class Person {
|
||||||
private String name;
|
private String name;
|
||||||
private int age;
|
private int age;
|
||||||
|
|
||||||
public Person() {
|
public Person() {
|
||||||
}
|
}
|
||||||
|
|
||||||
public Person(final String name, final int age) {
|
public Person(final String name, final int age) {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getName() {
|
public String getName() {
|
||||||
return name;
|
return name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setName(final String name) {
|
public void setName(final String name) {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "Person [name=" + name + "]";
|
return "Person [name=" + name + "]";
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -9,23 +9,23 @@ import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
|
||||||
@Controller
|
@Controller
|
||||||
public class ScopesController {
|
public class ScopesController {
|
||||||
public static final Logger LOG = Logger.getLogger(ScopesController.class);
|
public static final Logger LOG = Logger.getLogger(ScopesController.class);
|
||||||
|
|
||||||
@Resource(name = "requestMessage")
|
@Resource(name = "requestMessage")
|
||||||
HelloMessageGenerator requestMessage;
|
HelloMessageGenerator requestMessage;
|
||||||
|
|
||||||
@Resource(name = "sessionMessage")
|
@Resource(name = "sessionMessage")
|
||||||
HelloMessageGenerator sessionMessage;
|
HelloMessageGenerator sessionMessage;
|
||||||
|
|
||||||
@RequestMapping("/scopes")
|
@RequestMapping("/scopes")
|
||||||
public String getScopes(final Model model) {
|
public String getScopes(final Model model) {
|
||||||
LOG.info("Request Message:" + requestMessage.getMessage());
|
LOG.info("Request Message:" + requestMessage.getMessage());
|
||||||
LOG.info("Session Message" + sessionMessage.getMessage());
|
LOG.info("Session Message" + sessionMessage.getMessage());
|
||||||
requestMessage.setMessage("Good morning!");
|
requestMessage.setMessage("Good morning!");
|
||||||
sessionMessage.setMessage("Good afternoon!");
|
sessionMessage.setMessage("Good afternoon!");
|
||||||
model.addAttribute("requestMessage", requestMessage.getMessage());
|
model.addAttribute("requestMessage", requestMessage.getMessage());
|
||||||
model.addAttribute("sessionMessage", sessionMessage.getMessage());
|
model.addAttribute("sessionMessage", sessionMessage.getMessage());
|
||||||
return "scopesExample";
|
return "scopesExample";
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -16,42 +16,42 @@ import org.springframework.web.servlet.view.UrlBasedViewResolver;
|
||||||
@ComponentScan("org.baeldung.scopes")
|
@ComponentScan("org.baeldung.scopes")
|
||||||
@EnableWebMvc
|
@EnableWebMvc
|
||||||
public class ScopesConfig {
|
public class ScopesConfig {
|
||||||
@Bean
|
@Bean
|
||||||
public UrlBasedViewResolver setupViewResolver() {
|
public UrlBasedViewResolver setupViewResolver() {
|
||||||
final UrlBasedViewResolver resolver = new UrlBasedViewResolver();
|
final UrlBasedViewResolver resolver = new UrlBasedViewResolver();
|
||||||
resolver.setPrefix("/WEB-INF/view/");
|
resolver.setPrefix("/WEB-INF/view/");
|
||||||
resolver.setSuffix(".jsp");
|
resolver.setSuffix(".jsp");
|
||||||
resolver.setViewClass(JstlView.class);
|
resolver.setViewClass(JstlView.class);
|
||||||
return resolver;
|
return resolver;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
|
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
|
||||||
public HelloMessageGenerator requestMessage() {
|
public HelloMessageGenerator requestMessage() {
|
||||||
return new HelloMessageGenerator();
|
return new HelloMessageGenerator();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
|
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
|
||||||
public HelloMessageGenerator sessionMessage() {
|
public HelloMessageGenerator sessionMessage() {
|
||||||
return new HelloMessageGenerator();
|
return new HelloMessageGenerator();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@Scope(value = WebApplicationContext.SCOPE_GLOBAL_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
|
@Scope(value = WebApplicationContext.SCOPE_GLOBAL_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
|
||||||
public HelloMessageGenerator globalSessionMessage() {
|
public HelloMessageGenerator globalSessionMessage() {
|
||||||
return new HelloMessageGenerator();
|
return new HelloMessageGenerator();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@Scope("prototype")
|
@Scope("prototype")
|
||||||
public Person personPrototype() {
|
public Person personPrototype() {
|
||||||
return new Person();
|
return new Person();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@Scope("singleton")
|
@Scope("singleton")
|
||||||
public Person personSingleton() {
|
public Person personSingleton() {
|
||||||
return new Person();
|
return new Person();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -11,7 +11,6 @@ public class Foo {
|
||||||
|
|
||||||
private static final AtomicInteger instanceCount = new AtomicInteger(0);
|
private static final AtomicInteger instanceCount = new AtomicInteger(0);
|
||||||
|
|
||||||
|
|
||||||
private final int instanceNum;
|
private final int instanceNum;
|
||||||
|
|
||||||
public Foo() {
|
public Foo() {
|
||||||
|
|
|
@ -18,13 +18,12 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||||
import org.springframework.web.context.WebApplicationContext;
|
import org.springframework.web.context.WebApplicationContext;
|
||||||
import org.springframework.web.servlet.ModelAndView;
|
import org.springframework.web.servlet.ModelAndView;
|
||||||
|
|
||||||
|
|
||||||
@RunWith(SpringJUnit4ClassRunner.class)
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
@WebAppConfiguration
|
@WebAppConfiguration
|
||||||
@ContextConfiguration(classes={WebConfig.class}, loader=AnnotationConfigWebContextLoader.class )
|
@ContextConfiguration(classes = { WebConfig.class }, loader = AnnotationConfigWebContextLoader.class)
|
||||||
public class ControllerAnnotationTest {
|
public class ControllerAnnotationTest {
|
||||||
|
|
||||||
private MockMvc mockMvc;
|
private MockMvc mockMvc;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private WebApplicationContext wac;
|
private WebApplicationContext wac;
|
||||||
|
@ -43,9 +42,7 @@ public class ControllerAnnotationTest {
|
||||||
@Test
|
@Test
|
||||||
public void testTestController() throws Exception {
|
public void testTestController() throws Exception {
|
||||||
|
|
||||||
ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/"))
|
ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/")).andReturn().getModelAndView();
|
||||||
.andReturn()
|
|
||||||
.getModelAndView();
|
|
||||||
|
|
||||||
// validate modal data
|
// validate modal data
|
||||||
Assert.assertSame(mv.getModelMap().get("data").toString(), "Welcome home man");
|
Assert.assertSame(mv.getModelMap().get("data").toString(), "Welcome home man");
|
||||||
|
@ -57,9 +54,7 @@ public class ControllerAnnotationTest {
|
||||||
@Test
|
@Test
|
||||||
public void testRestController() throws Exception {
|
public void testRestController() throws Exception {
|
||||||
|
|
||||||
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1))
|
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1)).andReturn().getResponse().getContentAsString();
|
||||||
.andReturn().getResponse()
|
|
||||||
.getContentAsString();
|
|
||||||
|
|
||||||
ObjectMapper reader = new ObjectMapper();
|
ObjectMapper reader = new ObjectMapper();
|
||||||
|
|
||||||
|
@ -72,9 +67,7 @@ public class ControllerAnnotationTest {
|
||||||
@Test
|
@Test
|
||||||
public void testRestAnnotatedController() throws Exception {
|
public void testRestAnnotatedController() throws Exception {
|
||||||
|
|
||||||
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1))
|
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1)).andReturn().getResponse().getContentAsString();
|
||||||
.andReturn().getResponse()
|
|
||||||
.getContentAsString();
|
|
||||||
|
|
||||||
ObjectMapper reader = new ObjectMapper();
|
ObjectMapper reader = new ObjectMapper();
|
||||||
|
|
||||||
|
|
|
@ -19,7 +19,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
@RunWith(SpringJUnit4ClassRunner.class)
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
@WebAppConfiguration
|
@WebAppConfiguration
|
||||||
@ContextConfiguration({"classpath:test-mvc.xml"})
|
@ContextConfiguration({ "classpath:test-mvc.xml" })
|
||||||
public class ControllerTest {
|
public class ControllerTest {
|
||||||
|
|
||||||
private MockMvc mockMvc;
|
private MockMvc mockMvc;
|
||||||
|
@ -41,9 +41,7 @@ public class ControllerTest {
|
||||||
@Test
|
@Test
|
||||||
public void testTestController() throws Exception {
|
public void testTestController() throws Exception {
|
||||||
|
|
||||||
ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/"))
|
ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/")).andReturn().getModelAndView();
|
||||||
.andReturn()
|
|
||||||
.getModelAndView();
|
|
||||||
|
|
||||||
// validate modal data
|
// validate modal data
|
||||||
Assert.assertSame(mv.getModelMap().get("data").toString(), "Welcome home man");
|
Assert.assertSame(mv.getModelMap().get("data").toString(), "Welcome home man");
|
||||||
|
@ -55,9 +53,7 @@ public class ControllerTest {
|
||||||
@Test
|
@Test
|
||||||
public void testRestController() throws Exception {
|
public void testRestController() throws Exception {
|
||||||
|
|
||||||
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1))
|
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1)).andReturn().getResponse().getContentAsString();
|
||||||
.andReturn().getResponse()
|
|
||||||
.getContentAsString();
|
|
||||||
|
|
||||||
ObjectMapper reader = new ObjectMapper();
|
ObjectMapper reader = new ObjectMapper();
|
||||||
|
|
||||||
|
@ -70,9 +66,7 @@ public class ControllerTest {
|
||||||
@Test
|
@Test
|
||||||
public void testRestAnnotatedController() throws Exception {
|
public void testRestAnnotatedController() throws Exception {
|
||||||
|
|
||||||
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1))
|
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1)).andReturn().getResponse().getContentAsString();
|
||||||
.andReturn().getResponse()
|
|
||||||
.getContentAsString();
|
|
||||||
|
|
||||||
ObjectMapper reader = new ObjectMapper();
|
ObjectMapper reader = new ObjectMapper();
|
||||||
|
|
||||||
|
|
|
@ -8,36 +8,36 @@ import org.springframework.context.support.ClassPathXmlApplicationContext;
|
||||||
|
|
||||||
public class ScopesTest {
|
public class ScopesTest {
|
||||||
|
|
||||||
private static final String NAME = "John Smith";
|
private static final String NAME = "John Smith";
|
||||||
private static final String NAME_OTHER = "Anna Jones";
|
private static final String NAME_OTHER = "Anna Jones";
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testScopeSingleton() {
|
public void testScopeSingleton() {
|
||||||
final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml");
|
final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml");
|
||||||
|
|
||||||
final Person personSingletonA = (Person) applicationContext.getBean("personSingleton");
|
final Person personSingletonA = (Person) applicationContext.getBean("personSingleton");
|
||||||
final Person personSingletonB = (Person) applicationContext.getBean("personSingleton");
|
final Person personSingletonB = (Person) applicationContext.getBean("personSingleton");
|
||||||
|
|
||||||
personSingletonA.setName(NAME);
|
personSingletonA.setName(NAME);
|
||||||
Assert.assertEquals(NAME, personSingletonB.getName());
|
Assert.assertEquals(NAME, personSingletonB.getName());
|
||||||
|
|
||||||
((AbstractApplicationContext) applicationContext).close();
|
((AbstractApplicationContext) applicationContext).close();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testScopePrototype() {
|
public void testScopePrototype() {
|
||||||
final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml");
|
final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml");
|
||||||
|
|
||||||
final Person personPrototypeA = (Person) applicationContext.getBean("personPrototype");
|
final Person personPrototypeA = (Person) applicationContext.getBean("personPrototype");
|
||||||
final Person personPrototypeB = (Person) applicationContext.getBean("personPrototype");
|
final Person personPrototypeB = (Person) applicationContext.getBean("personPrototype");
|
||||||
|
|
||||||
personPrototypeA.setName(NAME);
|
personPrototypeA.setName(NAME);
|
||||||
personPrototypeB.setName(NAME_OTHER);
|
personPrototypeB.setName(NAME_OTHER);
|
||||||
|
|
||||||
Assert.assertEquals(NAME, personPrototypeA.getName());
|
Assert.assertEquals(NAME, personPrototypeA.getName());
|
||||||
Assert.assertEquals(NAME_OTHER, personPrototypeB.getName());
|
Assert.assertEquals(NAME_OTHER, personPrototypeB.getName());
|
||||||
|
|
||||||
((AbstractApplicationContext) applicationContext).close();
|
((AbstractApplicationContext) applicationContext).close();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -26,18 +26,12 @@ public class AttributeAnnotationTest extends AbstractJUnit4SpringContextTests {
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setup() {
|
public void setup() {
|
||||||
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac)
|
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
|
||||||
.build();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenInterceptorAddsRequestAndSessionParams_thenParamsInjectedWithAttributesAnnotations() throws Exception {
|
public void whenInterceptorAddsRequestAndSessionParams_thenParamsInjectedWithAttributesAnnotations() throws Exception {
|
||||||
String result = this.mockMvc.perform(get("/test")
|
String result = this.mockMvc.perform(get("/test").accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
|
||||||
.accept(MediaType.ALL))
|
|
||||||
.andExpect(status().isOk())
|
|
||||||
.andReturn()
|
|
||||||
.getResponse()
|
|
||||||
.getContentAsString();
|
|
||||||
|
|
||||||
Assert.assertEquals("login = john, query = invoices", result);
|
Assert.assertEquals("login = john, query = invoices", result);
|
||||||
}
|
}
|
||||||
|
|
|
@ -29,15 +29,12 @@ public class ComposedMappingTest extends AbstractJUnit4SpringContextTests {
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setup() {
|
public void setup() {
|
||||||
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac)
|
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
|
||||||
.build();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenRequestingMethodWithGetMapping_thenReceiving200Answer() throws Exception {
|
public void whenRequestingMethodWithGetMapping_thenReceiving200Answer() throws Exception {
|
||||||
this.mockMvc.perform(get("/appointments")
|
this.mockMvc.perform(get("/appointments").accept(MediaType.ALL)).andExpect(status().isOk());
|
||||||
.accept(MediaType.ALL))
|
|
||||||
.andExpect(status().isOk());
|
|
||||||
verify(appointmentService);
|
verify(appointmentService);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
|
||||||
|
|
||||||
import static org.junit.Assert.assertNotNull;
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
|
||||||
@ContextConfiguration(classes = {FooRepositoryConfiguration.class, FooServiceConfiguration.class})
|
@ContextConfiguration(classes = { FooRepositoryConfiguration.class, FooServiceConfiguration.class })
|
||||||
public class ConfigurationConstructorInjectionTest extends AbstractJUnit4SpringContextTests {
|
public class ConfigurationConstructorInjectionTest extends AbstractJUnit4SpringContextTests {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
|
|
|
@ -1,6 +1,5 @@
|
||||||
package org.baeldung.spring43.defaultmethods;
|
package org.baeldung.spring43.defaultmethods;
|
||||||
|
|
||||||
|
|
||||||
import javax.sql.DataSource;
|
import javax.sql.DataSource;
|
||||||
|
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
|
|
|
@ -28,27 +28,16 @@ public class ScopeAnnotationsTest extends AbstractJUnit4SpringContextTests {
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setup() {
|
public void setup() {
|
||||||
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac)
|
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
|
||||||
.build();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenDifferentRequests_thenDifferentInstancesOfRequestScopedBeans() throws Exception {
|
public void whenDifferentRequests_thenDifferentInstancesOfRequestScopedBeans() throws Exception {
|
||||||
MockHttpSession session = new MockHttpSession();
|
MockHttpSession session = new MockHttpSession();
|
||||||
|
|
||||||
String requestScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/request")
|
String requestScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/request").session(session).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
|
||||||
.session(session)
|
|
||||||
.accept(MediaType.ALL)).andExpect(status().isOk())
|
|
||||||
.andReturn()
|
|
||||||
.getResponse()
|
|
||||||
.getContentAsString();
|
|
||||||
|
|
||||||
String requestScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/request")
|
String requestScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/request").session(session).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
|
||||||
.session(session)
|
|
||||||
.accept(MediaType.ALL)).andExpect(status().isOk())
|
|
||||||
.andReturn()
|
|
||||||
.getResponse()
|
|
||||||
.getContentAsString();
|
|
||||||
|
|
||||||
assertNotEquals(requestScopedServiceInstanceNumber1, requestScopedServiceInstanceNumber2);
|
assertNotEquals(requestScopedServiceInstanceNumber1, requestScopedServiceInstanceNumber2);
|
||||||
}
|
}
|
||||||
|
@ -59,24 +48,9 @@ public class ScopeAnnotationsTest extends AbstractJUnit4SpringContextTests {
|
||||||
MockHttpSession session1 = new MockHttpSession();
|
MockHttpSession session1 = new MockHttpSession();
|
||||||
MockHttpSession session2 = new MockHttpSession();
|
MockHttpSession session2 = new MockHttpSession();
|
||||||
|
|
||||||
String sessionScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/session")
|
String sessionScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/session").session(session1).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
|
||||||
.session(session1)
|
String sessionScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/session").session(session1).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
|
||||||
.accept(MediaType.ALL)).andExpect(status().isOk())
|
String sessionScopedServiceInstanceNumber3 = this.mockMvc.perform(get("/appointments/session").session(session2).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
|
||||||
.andReturn()
|
|
||||||
.getResponse()
|
|
||||||
.getContentAsString();
|
|
||||||
String sessionScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/session")
|
|
||||||
.session(session1)
|
|
||||||
.accept(MediaType.ALL)).andExpect(status().isOk())
|
|
||||||
.andReturn()
|
|
||||||
.getResponse()
|
|
||||||
.getContentAsString();
|
|
||||||
String sessionScopedServiceInstanceNumber3 = this.mockMvc.perform(get("/appointments/session")
|
|
||||||
.session(session2)
|
|
||||||
.accept(MediaType.ALL)).andExpect(status().isOk())
|
|
||||||
.andReturn()
|
|
||||||
.getResponse()
|
|
||||||
.getContentAsString();
|
|
||||||
|
|
||||||
assertEquals(sessionScopedServiceInstanceNumber1, sessionScopedServiceInstanceNumber2);
|
assertEquals(sessionScopedServiceInstanceNumber1, sessionScopedServiceInstanceNumber2);
|
||||||
|
|
||||||
|
@ -90,18 +64,8 @@ public class ScopeAnnotationsTest extends AbstractJUnit4SpringContextTests {
|
||||||
MockHttpSession session1 = new MockHttpSession();
|
MockHttpSession session1 = new MockHttpSession();
|
||||||
MockHttpSession session2 = new MockHttpSession();
|
MockHttpSession session2 = new MockHttpSession();
|
||||||
|
|
||||||
String applicationScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/application")
|
String applicationScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/application").session(session1).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
|
||||||
.session(session1)
|
String applicationScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/application").session(session2).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
|
||||||
.accept(MediaType.ALL)).andExpect(status().isOk())
|
|
||||||
.andReturn()
|
|
||||||
.getResponse()
|
|
||||||
.getContentAsString();
|
|
||||||
String applicationScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/application")
|
|
||||||
.session(session2)
|
|
||||||
.accept(MediaType.ALL)).andExpect(status().isOk())
|
|
||||||
.andReturn()
|
|
||||||
.getResponse()
|
|
||||||
.getContentAsString();
|
|
||||||
|
|
||||||
assertEquals(applicationScopedServiceInstanceNumber1, applicationScopedServiceInstanceNumber2);
|
assertEquals(applicationScopedServiceInstanceNumber1, applicationScopedServiceInstanceNumber2);
|
||||||
|
|
||||||
|
|
|
@ -3,9 +3,9 @@ package com.baeldung.autowire.sample;
|
||||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||||
|
|
||||||
public class App {
|
public class App {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
|
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
|
||||||
FooService fooService = ctx.getBean(FooService.class);
|
FooService fooService = ctx.getBean(FooService.class);
|
||||||
fooService.doStuff();
|
fooService.doStuff();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,7 +10,7 @@ public class FooService {
|
||||||
@FormatterType("Foo")
|
@FormatterType("Foo")
|
||||||
private Formatter formatter;
|
private Formatter formatter;
|
||||||
|
|
||||||
public String doStuff(){
|
public String doStuff() {
|
||||||
return formatter.format();
|
return formatter.format();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -2,6 +2,6 @@ package com.baeldung.autowire.sample;
|
||||||
|
|
||||||
public interface Formatter {
|
public interface Formatter {
|
||||||
|
|
||||||
String format();
|
String format();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -8,7 +8,7 @@ import java.lang.annotation.Target;
|
||||||
import org.springframework.beans.factory.annotation.Qualifier;
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
|
|
||||||
@Qualifier
|
@Qualifier
|
||||||
@Target({ElementType.FIELD, ElementType.METHOD,ElementType.TYPE, ElementType.PARAMETER})
|
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER })
|
||||||
@Retention(RetentionPolicy.RUNTIME)
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
public @interface FormatterType {
|
public @interface FormatterType {
|
||||||
|
|
||||||
|
|
|
@ -9,14 +9,14 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||||
|
|
||||||
@RunWith(SpringJUnit4ClassRunner.class)
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
@ContextConfiguration(classes=AppConfig.class, loader=AnnotationConfigContextLoader.class)
|
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
|
||||||
public class FooServiceTest {
|
public class FooServiceTest {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
FooService fooService;
|
FooService fooService;
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenFooFormatterType_thenReturnFoo(){
|
public void whenFooFormatterType_thenReturnFoo() {
|
||||||
Assert.assertEquals("foo", fooService.doStuff());
|
Assert.assertEquals("foo", fooService.doStuff());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,9 +7,9 @@ import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
@Controller
|
@Controller
|
||||||
public class TestController {
|
public class TestController {
|
||||||
|
|
||||||
@RequestMapping(value="/")
|
@RequestMapping(value = "/")
|
||||||
public String welcome(Model model){
|
public String welcome(Model model) {
|
||||||
return "index";
|
return "index";
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -6,7 +6,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
public class WebjarsdemoApplication {
|
public class WebjarsdemoApplication {
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
SpringApplication.run(WebjarsdemoApplication.class, args);
|
SpringApplication.run(WebjarsdemoApplication.class, args);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -6,7 +6,7 @@ import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
|
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
|
||||||
import org.springframework.core.io.ClassPathResource;
|
import org.springframework.core.io.ClassPathResource;
|
||||||
|
|
||||||
@SpringBootApplication(scanBasePackages = { "com.baeldung.git"})
|
@SpringBootApplication(scanBasePackages = { "com.baeldung.git" })
|
||||||
public class CommitIdApplication {
|
public class CommitIdApplication {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
SpringApplication.run(CommitIdApplication.class, args);
|
SpringApplication.run(CommitIdApplication.class, args);
|
||||||
|
@ -21,6 +21,3 @@ public class CommitIdApplication {
|
||||||
return c;
|
return c;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -22,7 +22,7 @@ public class CommitInfoController {
|
||||||
@RequestMapping("/commitId")
|
@RequestMapping("/commitId")
|
||||||
public Map<String, String> getCommitId() {
|
public Map<String, String> getCommitId() {
|
||||||
Map<String, String> result = new HashMap<>();
|
Map<String, String> result = new HashMap<>();
|
||||||
result.put("Commit message",commitMessage);
|
result.put("Commit message", commitMessage);
|
||||||
result.put("Commit branch", branch);
|
result.put("Commit branch", branch);
|
||||||
result.put("Commit id", commitId);
|
result.put("Commit id", commitId);
|
||||||
return result;
|
return result;
|
||||||
|
|
|
@ -11,8 +11,8 @@ import org.springframework.test.context.web.WebAppConfiguration;
|
||||||
@WebAppConfiguration
|
@WebAppConfiguration
|
||||||
public class WebjarsdemoApplicationTests {
|
public class WebjarsdemoApplicationTests {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void contextLoads() {
|
public void contextLoads() {
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -32,13 +32,10 @@ public class CommitIdTest {
|
||||||
LOG.info(commitMessage);
|
LOG.info(commitMessage);
|
||||||
LOG.info(branch);
|
LOG.info(branch);
|
||||||
|
|
||||||
assertThat(commitMessage)
|
assertThat(commitMessage).isNotEqualTo("UNKNOWN");
|
||||||
.isNotEqualTo("UNKNOWN");
|
|
||||||
|
|
||||||
assertThat(branch)
|
assertThat(branch).isNotEqualTo("UNKNOWN");
|
||||||
.isNotEqualTo("UNKNOWN");
|
|
||||||
|
|
||||||
assertThat(commitId)
|
assertThat(commitId).isNotEqualTo("UNKNOWN");
|
||||||
.isNotEqualTo("UNKNOWN");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -31,22 +31,15 @@ public class SpringBootApplicationTest {
|
||||||
private WebApplicationContext webApplicationContext;
|
private WebApplicationContext webApplicationContext;
|
||||||
private MockMvc mockMvc;
|
private MockMvc mockMvc;
|
||||||
|
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setupMockMvc() {
|
public void setupMockMvc() {
|
||||||
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
|
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
|
||||||
.build();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenRequestHasBeenMade_whenMeetsAllOfGivenConditions_thenCorrect() throws Exception {
|
public void givenRequestHasBeenMade_whenMeetsAllOfGivenConditions_thenCorrect() throws Exception {
|
||||||
MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
|
MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
|
||||||
MediaType.APPLICATION_JSON.getSubtype(),
|
|
||||||
Charset.forName("utf8"));
|
|
||||||
|
|
||||||
mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")).
|
mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)).andExpect(jsonPath("$", hasSize(4)));
|
||||||
andExpect(MockMvcResultMatchers.status().isOk()).
|
|
||||||
andExpect(MockMvcResultMatchers.content().contentType(contentType)).
|
|
||||||
andExpect(jsonPath("$", hasSize(4)));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -69,7 +69,6 @@ public class SpringBootMailTest {
|
||||||
return wiserMessage.getMimeMessage().getSubject();
|
return wiserMessage.getMimeMessage().getSubject();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private SimpleMailMessage composeEmailMessage() {
|
private SimpleMailMessage composeEmailMessage() {
|
||||||
SimpleMailMessage mailMessage = new SimpleMailMessage();
|
SimpleMailMessage mailMessage = new SimpleMailMessage();
|
||||||
mailMessage.setTo(userTo);
|
mailMessage.setTo(userTo);
|
||||||
|
|
|
@ -30,8 +30,7 @@ public class DetailsServiceClientTest {
|
||||||
@Before
|
@Before
|
||||||
public void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
String detailsString = objectMapper.writeValueAsString(new Details("John Smith", "john"));
|
String detailsString = objectMapper.writeValueAsString(new Details("John Smith", "john"));
|
||||||
this.server.expect(requestTo("/john/details"))
|
this.server.expect(requestTo("/john/details")).andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON));
|
||||||
.andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|
|
@ -20,7 +20,7 @@ public class SpringDemoApplication extends SpringBootServletInitializer {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public RestTemplate getRestTemplate(){
|
public RestTemplate getRestTemplate() {
|
||||||
return new RestTemplate();
|
return new RestTemplate();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -23,18 +23,23 @@ public class Campus {
|
||||||
public String getId() {
|
public String getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setId(String id) {
|
public void setId(String id) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getName() {
|
public String getName() {
|
||||||
return name;
|
return name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setName(String name) {
|
public void setName(String name) {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Point getLocation() {
|
public Point getLocation() {
|
||||||
return location;
|
return location;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setLocation(Point location) {
|
public void setLocation(Point location) {
|
||||||
this.location = location;
|
this.location = location;
|
||||||
}
|
}
|
||||||
|
@ -42,13 +47,13 @@ public class Campus {
|
||||||
@Override
|
@Override
|
||||||
public int hashCode() {
|
public int hashCode() {
|
||||||
int hash = 1;
|
int hash = 1;
|
||||||
if(id != null) {
|
if (id != null) {
|
||||||
hash = hash * 31 + id.hashCode();
|
hash = hash * 31 + id.hashCode();
|
||||||
}
|
}
|
||||||
if(name != null) {
|
if (name != null) {
|
||||||
hash = hash * 31 + name.hashCode();
|
hash = hash * 31 + name.hashCode();
|
||||||
}
|
}
|
||||||
if(location != null) {
|
if (location != null) {
|
||||||
hash = hash * 31 + location.hashCode();
|
hash = hash * 31 + location.hashCode();
|
||||||
}
|
}
|
||||||
return hash;
|
return hash;
|
||||||
|
@ -56,14 +61,17 @@ public class Campus {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean equals(Object obj) {
|
public boolean equals(Object obj) {
|
||||||
if((obj == null) || (obj.getClass() != this.getClass())) return false;
|
if ((obj == null) || (obj.getClass() != this.getClass()))
|
||||||
if(obj == this) return true;
|
return false;
|
||||||
|
if (obj == this)
|
||||||
|
return true;
|
||||||
Campus other = (Campus) obj;
|
Campus other = (Campus) obj;
|
||||||
return this.hashCode() == other.hashCode();
|
return this.hashCode() == other.hashCode();
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
private Campus() {}
|
private Campus() {
|
||||||
|
}
|
||||||
|
|
||||||
public Campus(Builder b) {
|
public Campus(Builder b) {
|
||||||
this.id = b.id;
|
this.id = b.id;
|
||||||
|
|
|
@ -34,30 +34,39 @@ public class Person {
|
||||||
public String getId() {
|
public String getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setId(String id) {
|
public void setId(String id) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getFirstName() {
|
public String getFirstName() {
|
||||||
return firstName;
|
return firstName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setFirstName(String firstName) {
|
public void setFirstName(String firstName) {
|
||||||
this.firstName = firstName;
|
this.firstName = firstName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getLastName() {
|
public String getLastName() {
|
||||||
return lastName;
|
return lastName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setLastName(String lastName) {
|
public void setLastName(String lastName) {
|
||||||
this.lastName = lastName;
|
this.lastName = lastName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public DateTime getCreated() {
|
public DateTime getCreated() {
|
||||||
return created;
|
return created;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setCreated(DateTime created) {
|
public void setCreated(DateTime created) {
|
||||||
this.created = created;
|
this.created = created;
|
||||||
}
|
}
|
||||||
|
|
||||||
public DateTime getUpdated() {
|
public DateTime getUpdated() {
|
||||||
return updated;
|
return updated;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setUpdated(DateTime updated) {
|
public void setUpdated(DateTime updated) {
|
||||||
this.updated = updated;
|
this.updated = updated;
|
||||||
}
|
}
|
||||||
|
@ -65,13 +74,13 @@ public class Person {
|
||||||
@Override
|
@Override
|
||||||
public int hashCode() {
|
public int hashCode() {
|
||||||
int hash = 1;
|
int hash = 1;
|
||||||
if(id != null) {
|
if (id != null) {
|
||||||
hash = hash * 31 + id.hashCode();
|
hash = hash * 31 + id.hashCode();
|
||||||
}
|
}
|
||||||
if(firstName != null) {
|
if (firstName != null) {
|
||||||
hash = hash * 31 + firstName.hashCode();
|
hash = hash * 31 + firstName.hashCode();
|
||||||
}
|
}
|
||||||
if(lastName != null) {
|
if (lastName != null) {
|
||||||
hash = hash * 31 + lastName.hashCode();
|
hash = hash * 31 + lastName.hashCode();
|
||||||
}
|
}
|
||||||
return hash;
|
return hash;
|
||||||
|
@ -79,8 +88,10 @@ public class Person {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean equals(Object obj) {
|
public boolean equals(Object obj) {
|
||||||
if((obj == null) || (obj.getClass() != this.getClass())) return false;
|
if ((obj == null) || (obj.getClass() != this.getClass()))
|
||||||
if(obj == this) return true;
|
return false;
|
||||||
|
if (obj == this)
|
||||||
|
return true;
|
||||||
Person other = (Person) obj;
|
Person other = (Person) obj;
|
||||||
return this.hashCode() == other.hashCode();
|
return this.hashCode() == other.hashCode();
|
||||||
}
|
}
|
||||||
|
|
|
@ -20,13 +20,13 @@ public class Student {
|
||||||
private String id;
|
private String id;
|
||||||
@Field
|
@Field
|
||||||
@NotNull
|
@NotNull
|
||||||
@Size(min=1, max=20)
|
@Size(min = 1, max = 20)
|
||||||
@Pattern(regexp=NAME_REGEX)
|
@Pattern(regexp = NAME_REGEX)
|
||||||
private String firstName;
|
private String firstName;
|
||||||
@Field
|
@Field
|
||||||
@NotNull
|
@NotNull
|
||||||
@Size(min=1, max=20)
|
@Size(min = 1, max = 20)
|
||||||
@Pattern(regexp=NAME_REGEX)
|
@Pattern(regexp = NAME_REGEX)
|
||||||
private String lastName;
|
private String lastName;
|
||||||
@Field
|
@Field
|
||||||
@Past
|
@Past
|
||||||
|
@ -39,7 +39,8 @@ public class Student {
|
||||||
@Version
|
@Version
|
||||||
private long version;
|
private long version;
|
||||||
|
|
||||||
public Student() {}
|
public Student() {
|
||||||
|
}
|
||||||
|
|
||||||
public Student(String id, String firstName, String lastName, DateTime dateOfBirth) {
|
public Student(String id, String firstName, String lastName, DateTime dateOfBirth) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
|
@ -51,36 +52,47 @@ public class Student {
|
||||||
public String getId() {
|
public String getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setId(String id) {
|
public void setId(String id) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getFirstName() {
|
public String getFirstName() {
|
||||||
return firstName;
|
return firstName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setFirstName(String firstName) {
|
public void setFirstName(String firstName) {
|
||||||
this.firstName = firstName;
|
this.firstName = firstName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getLastName() {
|
public String getLastName() {
|
||||||
return lastName;
|
return lastName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setLastName(String lastName) {
|
public void setLastName(String lastName) {
|
||||||
this.lastName = lastName;
|
this.lastName = lastName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public DateTime getDateOfBirth() {
|
public DateTime getDateOfBirth() {
|
||||||
return dateOfBirth;
|
return dateOfBirth;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setDateOfBirth(DateTime dateOfBirth) {
|
public void setDateOfBirth(DateTime dateOfBirth) {
|
||||||
this.dateOfBirth = dateOfBirth;
|
this.dateOfBirth = dateOfBirth;
|
||||||
}
|
}
|
||||||
|
|
||||||
public DateTime getCreated() {
|
public DateTime getCreated() {
|
||||||
return created;
|
return created;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setCreated(DateTime created) {
|
public void setCreated(DateTime created) {
|
||||||
this.created = created;
|
this.created = created;
|
||||||
}
|
}
|
||||||
|
|
||||||
public DateTime getUpdated() {
|
public DateTime getUpdated() {
|
||||||
return updated;
|
return updated;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setUpdated(DateTime updated) {
|
public void setUpdated(DateTime updated) {
|
||||||
this.updated = updated;
|
this.updated = updated;
|
||||||
}
|
}
|
||||||
|
@ -88,16 +100,16 @@ public class Student {
|
||||||
@Override
|
@Override
|
||||||
public int hashCode() {
|
public int hashCode() {
|
||||||
int hash = 1;
|
int hash = 1;
|
||||||
if(id != null) {
|
if (id != null) {
|
||||||
hash = hash * 31 + id.hashCode();
|
hash = hash * 31 + id.hashCode();
|
||||||
}
|
}
|
||||||
if(firstName != null) {
|
if (firstName != null) {
|
||||||
hash = hash * 31 + firstName.hashCode();
|
hash = hash * 31 + firstName.hashCode();
|
||||||
}
|
}
|
||||||
if(lastName != null) {
|
if (lastName != null) {
|
||||||
hash = hash * 31 + lastName.hashCode();
|
hash = hash * 31 + lastName.hashCode();
|
||||||
}
|
}
|
||||||
if(dateOfBirth != null) {
|
if (dateOfBirth != null) {
|
||||||
hash = hash * 31 + dateOfBirth.hashCode();
|
hash = hash * 31 + dateOfBirth.hashCode();
|
||||||
}
|
}
|
||||||
return hash;
|
return hash;
|
||||||
|
@ -105,8 +117,10 @@ public class Student {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean equals(Object obj) {
|
public boolean equals(Object obj) {
|
||||||
if((obj == null) || (obj.getClass() != this.getClass())) return false;
|
if ((obj == null) || (obj.getClass() != this.getClass()))
|
||||||
if(obj == this) return true;
|
return false;
|
||||||
|
if (obj == this)
|
||||||
|
return true;
|
||||||
Student other = (Student) obj;
|
Student other = (Student) obj;
|
||||||
return this.hashCode() == other.hashCode();
|
return this.hashCode() == other.hashCode();
|
||||||
}
|
}
|
||||||
|
|
|
@ -17,9 +17,6 @@ public class CustomStudentRepositoryImpl implements CustomStudentRepository {
|
||||||
private CouchbaseTemplate template;
|
private CouchbaseTemplate template;
|
||||||
|
|
||||||
public List<Student> findByFirstNameStartsWith(String s) {
|
public List<Student> findByFirstNameStartsWith(String s) {
|
||||||
return template.findByView(ViewQuery.from(DESIGN_DOC, "byFirstName")
|
return template.findByView(ViewQuery.from(DESIGN_DOC, "byFirstName").startKey(s).stale(Stale.FALSE), Student.class);
|
||||||
.startKey(s)
|
|
||||||
.stale(Stale.FALSE),
|
|
||||||
Student.class);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository;
|
||||||
|
|
||||||
public interface PersonRepository extends CrudRepository<Person, String> {
|
public interface PersonRepository extends CrudRepository<Person, String> {
|
||||||
List<Person> findByFirstName(String firstName);
|
List<Person> findByFirstName(String firstName);
|
||||||
|
|
||||||
List<Person> findByLastName(String lastName);
|
List<Person> findByLastName(String lastName);
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository;
|
||||||
|
|
||||||
public interface StudentRepository extends CrudRepository<Student, String>, CustomStudentRepository {
|
public interface StudentRepository extends CrudRepository<Student, String>, CustomStudentRepository {
|
||||||
List<Student> findByFirstName(String firstName);
|
List<Student> findByFirstName(String firstName);
|
||||||
|
|
||||||
List<Student> findByLastName(String lastName);
|
List<Student> findByLastName(String lastName);
|
||||||
}
|
}
|
||||||
|
|
|
@ -16,6 +16,7 @@ import org.springframework.stereotype.Service;
|
||||||
public class PersonRepositoryService implements PersonService {
|
public class PersonRepositoryService implements PersonService {
|
||||||
|
|
||||||
private PersonRepository repo;
|
private PersonRepository repo;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public void setPersonRepository(PersonRepository repo) {
|
public void setPersonRepository(PersonRepository repo) {
|
||||||
this.repo = repo;
|
this.repo = repo;
|
||||||
|
@ -28,7 +29,7 @@ public class PersonRepositoryService implements PersonService {
|
||||||
public List<Person> findAll() {
|
public List<Person> findAll() {
|
||||||
List<Person> people = new ArrayList<Person>();
|
List<Person> people = new ArrayList<Person>();
|
||||||
Iterator<Person> it = repo.findAll().iterator();
|
Iterator<Person> it = repo.findAll().iterator();
|
||||||
while(it.hasNext()) {
|
while (it.hasNext()) {
|
||||||
people.add(it.next());
|
people.add(it.next());
|
||||||
}
|
}
|
||||||
return people;
|
return people;
|
||||||
|
|
|
@ -18,13 +18,14 @@ public class PersonTemplateService implements PersonService {
|
||||||
private static final String DESIGN_DOC = "person";
|
private static final String DESIGN_DOC = "person";
|
||||||
|
|
||||||
private CouchbaseTemplate template;
|
private CouchbaseTemplate template;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public void setCouchbaseTemplate(CouchbaseTemplate template) {
|
public void setCouchbaseTemplate(CouchbaseTemplate template) {
|
||||||
this.template = template;
|
this.template = template;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Person findOne(String id) {
|
public Person findOne(String id) {
|
||||||
return template.findById(id, Person.class);
|
return template.findById(id, Person.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<Person> findAll() {
|
public List<Person> findAll() {
|
||||||
|
|
|
@ -16,6 +16,7 @@ import org.springframework.stereotype.Service;
|
||||||
public class StudentRepositoryService implements StudentService {
|
public class StudentRepositoryService implements StudentService {
|
||||||
|
|
||||||
private StudentRepository repo;
|
private StudentRepository repo;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public void setStudentRepository(StudentRepository repo) {
|
public void setStudentRepository(StudentRepository repo) {
|
||||||
this.repo = repo;
|
this.repo = repo;
|
||||||
|
@ -28,7 +29,7 @@ public class StudentRepositoryService implements StudentService {
|
||||||
public List<Student> findAll() {
|
public List<Student> findAll() {
|
||||||
List<Student> people = new ArrayList<Student>();
|
List<Student> people = new ArrayList<Student>();
|
||||||
Iterator<Student> it = repo.findAll().iterator();
|
Iterator<Student> it = repo.findAll().iterator();
|
||||||
while(it.hasNext()) {
|
while (it.hasNext()) {
|
||||||
people.add(it.next());
|
people.add(it.next());
|
||||||
}
|
}
|
||||||
return people;
|
return people;
|
||||||
|
|
|
@ -18,13 +18,14 @@ public class StudentTemplateService implements StudentService {
|
||||||
private static final String DESIGN_DOC = "student";
|
private static final String DESIGN_DOC = "student";
|
||||||
|
|
||||||
private CouchbaseTemplate template;
|
private CouchbaseTemplate template;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public void setCouchbaseTemplate(CouchbaseTemplate template) {
|
public void setCouchbaseTemplate(CouchbaseTemplate template) {
|
||||||
this.template = template;
|
this.template = template;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Student findOne(String id) {
|
public Student findOne(String id) {
|
||||||
return template.findById(id, Student.class);
|
return template.findById(id, Student.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<Student> findAll() {
|
public List<Student> findAll() {
|
||||||
|
|
|
@ -11,9 +11,9 @@ import org.springframework.data.repository.CrudRepository;
|
||||||
|
|
||||||
public interface CampusRepository extends CrudRepository<Campus, String> {
|
public interface CampusRepository extends CrudRepository<Campus, String> {
|
||||||
|
|
||||||
@View(designDocument="campus", viewName="byName")
|
@View(designDocument = "campus", viewName = "byName")
|
||||||
Set<Campus> findByName(String name);
|
Set<Campus> findByName(String name);
|
||||||
|
|
||||||
@Dimensional(dimensions=2, designDocument="campus_spatial", spatialViewName="byLocation")
|
@Dimensional(dimensions = 2, designDocument = "campus_spatial", spatialViewName = "byLocation")
|
||||||
Set<Campus> findByLocationNear(Point point, Distance distance);
|
Set<Campus> findByLocationNear(Point point, Distance distance);
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository;
|
||||||
|
|
||||||
public interface PersonRepository extends CrudRepository<Person, String> {
|
public interface PersonRepository extends CrudRepository<Person, String> {
|
||||||
List<Person> findByFirstName(String firstName);
|
List<Person> findByFirstName(String firstName);
|
||||||
|
|
||||||
List<Person> findByLastName(String lastName);
|
List<Person> findByLastName(String lastName);
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository;
|
||||||
|
|
||||||
public interface StudentRepository extends CrudRepository<Student, String> {
|
public interface StudentRepository extends CrudRepository<Student, String> {
|
||||||
List<Student> findByFirstName(String firstName);
|
List<Student> findByFirstName(String firstName);
|
||||||
|
|
||||||
List<Student> findByLastName(String lastName);
|
List<Student> findByLastName(String lastName);
|
||||||
}
|
}
|
||||||
|
|
|
@ -15,6 +15,7 @@ import org.springframework.stereotype.Service;
|
||||||
public class CampusServiceImpl implements CampusService {
|
public class CampusServiceImpl implements CampusService {
|
||||||
|
|
||||||
private CampusRepository repo;
|
private CampusRepository repo;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public void setCampusRepository(CampusRepository repo) {
|
public void setCampusRepository(CampusRepository repo) {
|
||||||
this.repo = repo;
|
this.repo = repo;
|
||||||
|
@ -39,7 +40,7 @@ public class CampusServiceImpl implements CampusService {
|
||||||
public Set<Campus> findAll() {
|
public Set<Campus> findAll() {
|
||||||
Set<Campus> campuses = new HashSet<>();
|
Set<Campus> campuses = new HashSet<>();
|
||||||
Iterator<Campus> it = repo.findAll().iterator();
|
Iterator<Campus> it = repo.findAll().iterator();
|
||||||
while(it.hasNext()) {
|
while (it.hasNext()) {
|
||||||
campuses.add(it.next());
|
campuses.add(it.next());
|
||||||
}
|
}
|
||||||
return campuses;
|
return campuses;
|
||||||
|
|
|
@ -14,6 +14,7 @@ import org.springframework.stereotype.Service;
|
||||||
public class PersonServiceImpl implements PersonService {
|
public class PersonServiceImpl implements PersonService {
|
||||||
|
|
||||||
private PersonRepository repo;
|
private PersonRepository repo;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public void setPersonRepository(PersonRepository repo) {
|
public void setPersonRepository(PersonRepository repo) {
|
||||||
this.repo = repo;
|
this.repo = repo;
|
||||||
|
@ -26,7 +27,7 @@ public class PersonServiceImpl implements PersonService {
|
||||||
public List<Person> findAll() {
|
public List<Person> findAll() {
|
||||||
List<Person> people = new ArrayList<Person>();
|
List<Person> people = new ArrayList<Person>();
|
||||||
Iterator<Person> it = repo.findAll().iterator();
|
Iterator<Person> it = repo.findAll().iterator();
|
||||||
while(it.hasNext()) {
|
while (it.hasNext()) {
|
||||||
people.add(it.next());
|
people.add(it.next());
|
||||||
}
|
}
|
||||||
return people;
|
return people;
|
||||||
|
|
|
@ -14,6 +14,7 @@ import org.springframework.stereotype.Service;
|
||||||
public class StudentServiceImpl implements StudentService {
|
public class StudentServiceImpl implements StudentService {
|
||||||
|
|
||||||
private StudentRepository repo;
|
private StudentRepository repo;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public void setStudentRepository(StudentRepository repo) {
|
public void setStudentRepository(StudentRepository repo) {
|
||||||
this.repo = repo;
|
this.repo = repo;
|
||||||
|
@ -26,7 +27,7 @@ public class StudentServiceImpl implements StudentService {
|
||||||
public List<Student> findAll() {
|
public List<Student> findAll() {
|
||||||
List<Student> people = new ArrayList<Student>();
|
List<Student> people = new ArrayList<Student>();
|
||||||
Iterator<Student> it = repo.findAll().iterator();
|
Iterator<Student> it = repo.findAll().iterator();
|
||||||
while(it.hasNext()) {
|
while (it.hasNext()) {
|
||||||
people.add(it.next());
|
people.add(it.next());
|
||||||
}
|
}
|
||||||
return people;
|
return people;
|
||||||
|
|
|
@ -12,7 +12,7 @@ import org.springframework.data.couchbase.repository.config.EnableCouchbaseRepos
|
||||||
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
|
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
@EnableCouchbaseRepositories(basePackages={"org.baeldung.spring.data.couchbase"})
|
@EnableCouchbaseRepositories(basePackages = { "org.baeldung.spring.data.couchbase" })
|
||||||
public class MyCouchbaseConfig extends AbstractCouchbaseConfiguration {
|
public class MyCouchbaseConfig extends AbstractCouchbaseConfiguration {
|
||||||
|
|
||||||
public static final List<String> NODE_LIST = Arrays.asList("localhost");
|
public static final List<String> NODE_LIST = Arrays.asList("localhost");
|
||||||
|
|
|
@ -30,24 +30,14 @@ public abstract class StudentServiceTest extends IntegrationTest {
|
||||||
static final String joeCollegeId = "student:" + joe + ":" + college;
|
static final String joeCollegeId = "student:" + joe + ":" + college;
|
||||||
static final DateTime joeCollegeDob = DateTime.now().minusYears(21);
|
static final DateTime joeCollegeDob = DateTime.now().minusYears(21);
|
||||||
static final Student joeCollege = new Student(joeCollegeId, joe, college, joeCollegeDob);
|
static final Student joeCollege = new Student(joeCollegeId, joe, college, joeCollegeDob);
|
||||||
static final JsonObject jsonJoeCollege = JsonObject.empty()
|
static final JsonObject jsonJoeCollege = JsonObject.empty().put(typeField, Student.class.getName()).put("firstName", joe).put("lastName", college).put("created", DateTime.now().getMillis()).put("version", 1);
|
||||||
.put(typeField, Student.class.getName())
|
|
||||||
.put("firstName", joe)
|
|
||||||
.put("lastName", college)
|
|
||||||
.put("created", DateTime.now().getMillis())
|
|
||||||
.put("version", 1);
|
|
||||||
|
|
||||||
static final String judy = "Judy";
|
static final String judy = "Judy";
|
||||||
static final String jetson = "Jetson";
|
static final String jetson = "Jetson";
|
||||||
static final String judyJetsonId = "student:" + judy + ":" + jetson;
|
static final String judyJetsonId = "student:" + judy + ":" + jetson;
|
||||||
static final DateTime judyJetsonDob = DateTime.now().minusYears(19).minusMonths(5).minusDays(3);
|
static final DateTime judyJetsonDob = DateTime.now().minusYears(19).minusMonths(5).minusDays(3);
|
||||||
static final Student judyJetson = new Student(judyJetsonId, judy, jetson, judyJetsonDob);
|
static final Student judyJetson = new Student(judyJetsonId, judy, jetson, judyJetsonDob);
|
||||||
static final JsonObject jsonJudyJetson = JsonObject.empty()
|
static final JsonObject jsonJudyJetson = JsonObject.empty().put(typeField, Student.class.getName()).put("firstName", judy).put("lastName", jetson).put("created", DateTime.now().getMillis()).put("version", 1);
|
||||||
.put(typeField, Student.class.getName())
|
|
||||||
.put("firstName", judy)
|
|
||||||
.put("lastName", jetson)
|
|
||||||
.put("created", DateTime.now().getMillis())
|
|
||||||
.put("version", 1);
|
|
||||||
|
|
||||||
StudentService studentService;
|
StudentService studentService;
|
||||||
|
|
||||||
|
@ -75,7 +65,7 @@ public abstract class StudentServiceTest extends IntegrationTest {
|
||||||
assertEquals(expectedStudent.getId(), actualStudent.getId());
|
assertEquals(expectedStudent.getId(), actualStudent.getId());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test(expected=ConstraintViolationException.class)
|
@Test(expected = ConstraintViolationException.class)
|
||||||
public void whenCreatingStudentWithInvalidFirstName_thenConstraintViolationException() {
|
public void whenCreatingStudentWithInvalidFirstName_thenConstraintViolationException() {
|
||||||
String firstName = "Er+ic";
|
String firstName = "Er+ic";
|
||||||
String lastName = "Stratton";
|
String lastName = "Stratton";
|
||||||
|
@ -85,7 +75,7 @@ public abstract class StudentServiceTest extends IntegrationTest {
|
||||||
studentService.create(student);
|
studentService.create(student);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test(expected=ConstraintViolationException.class)
|
@Test(expected = ConstraintViolationException.class)
|
||||||
public void whenCreatingStudentWithFutureDob_thenConstraintViolationException() {
|
public void whenCreatingStudentWithFutureDob_thenConstraintViolationException() {
|
||||||
String firstName = "Jane";
|
String firstName = "Jane";
|
||||||
String lastName = "Doe";
|
String lastName = "Doe";
|
||||||
|
@ -133,8 +123,8 @@ public abstract class StudentServiceTest extends IntegrationTest {
|
||||||
|
|
||||||
private boolean resultContains(List<Student> resultList, Student student) {
|
private boolean resultContains(List<Student> resultList, Student student) {
|
||||||
boolean found = false;
|
boolean found = false;
|
||||||
for(Student p : resultList) {
|
for (Student p : resultList) {
|
||||||
if(p.getId().equals(student.getId())) {
|
if (p.getId().equals(student.getId())) {
|
||||||
found = true;
|
found = true;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
@ -144,8 +134,8 @@ public abstract class StudentServiceTest extends IntegrationTest {
|
||||||
|
|
||||||
private boolean allResultsContainExpectedFirstName(List<Student> resultList, String firstName) {
|
private boolean allResultsContainExpectedFirstName(List<Student> resultList, String firstName) {
|
||||||
boolean found = false;
|
boolean found = false;
|
||||||
for(Student p : resultList) {
|
for (Student p : resultList) {
|
||||||
if(p.getFirstName().equals(firstName)) {
|
if (p.getFirstName().equals(firstName)) {
|
||||||
found = true;
|
found = true;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
@ -155,8 +145,8 @@ public abstract class StudentServiceTest extends IntegrationTest {
|
||||||
|
|
||||||
private boolean allResultsContainExpectedLastName(List<Student> resultList, String lastName) {
|
private boolean allResultsContainExpectedLastName(List<Student> resultList, String lastName) {
|
||||||
boolean found = false;
|
boolean found = false;
|
||||||
for(Student p : resultList) {
|
for (Student p : resultList) {
|
||||||
if(p.getLastName().equals(lastName)) {
|
if (p.getLastName().equals(lastName)) {
|
||||||
found = true;
|
found = true;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
|
@ -46,11 +46,7 @@ public class MultiBucketCouchbaseConfig extends AbstractCouchbaseConfiguration {
|
||||||
|
|
||||||
@Bean(name = "campusTemplate")
|
@Bean(name = "campusTemplate")
|
||||||
public CouchbaseTemplate campusTemplate() throws Exception {
|
public CouchbaseTemplate campusTemplate() throws Exception {
|
||||||
CouchbaseTemplate template = new CouchbaseTemplate(
|
CouchbaseTemplate template = new CouchbaseTemplate(couchbaseClusterInfo(), campusBucket(), mappingCouchbaseConverter(), translationService());
|
||||||
couchbaseClusterInfo(),
|
|
||||||
campusBucket(),
|
|
||||||
mappingCouchbaseConverter(),
|
|
||||||
translationService());
|
|
||||||
template.setDefaultConsistency(getDefaultConsistency());
|
template.setDefaultConsistency(getDefaultConsistency());
|
||||||
return template;
|
return template;
|
||||||
}
|
}
|
||||||
|
@ -60,7 +56,7 @@ public class MultiBucketCouchbaseConfig extends AbstractCouchbaseConfiguration {
|
||||||
try {
|
try {
|
||||||
baseMapping.mapEntity(Campus.class, campusTemplate());
|
baseMapping.mapEntity(Campus.class, campusTemplate());
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
//custom Exception handling
|
// custom Exception handling
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -26,53 +26,21 @@ public class CampusServiceImplTest extends MultiBucketIntegationTest {
|
||||||
@Autowired
|
@Autowired
|
||||||
private CampusRepository campusRepo;
|
private CampusRepository campusRepo;
|
||||||
|
|
||||||
private final Campus Brown = Campus.Builder.newInstance()
|
private final Campus Brown = Campus.Builder.newInstance().id("campus:Brown").name("Brown").location(new Point(71.4025, 51.8268)).build();
|
||||||
.id("campus:Brown")
|
|
||||||
.name("Brown")
|
|
||||||
.location(new Point(71.4025, 51.8268))
|
|
||||||
.build();
|
|
||||||
|
|
||||||
private final Campus Cornell = Campus.Builder.newInstance()
|
private final Campus Cornell = Campus.Builder.newInstance().id("campus:Cornell").name("Cornell").location(new Point(76.4833, 42.4459)).build();
|
||||||
.id("campus:Cornell")
|
|
||||||
.name("Cornell")
|
|
||||||
.location(new Point(76.4833, 42.4459))
|
|
||||||
.build();
|
|
||||||
|
|
||||||
private final Campus Columbia = Campus.Builder.newInstance()
|
private final Campus Columbia = Campus.Builder.newInstance().id("campus:Columbia").name("Columbia").location(new Point(73.9626, 40.8075)).build();
|
||||||
.id("campus:Columbia")
|
|
||||||
.name("Columbia")
|
|
||||||
.location(new Point(73.9626, 40.8075))
|
|
||||||
.build();
|
|
||||||
|
|
||||||
private final Campus Dartmouth = Campus.Builder.newInstance()
|
private final Campus Dartmouth = Campus.Builder.newInstance().id("campus:Dartmouth").name("Dartmouth").location(new Point(72.2887, 43.7044)).build();
|
||||||
.id("campus:Dartmouth")
|
|
||||||
.name("Dartmouth")
|
|
||||||
.location(new Point(72.2887, 43.7044))
|
|
||||||
.build();
|
|
||||||
|
|
||||||
private final Campus Harvard = Campus.Builder.newInstance()
|
private final Campus Harvard = Campus.Builder.newInstance().id("campus:Harvard").name("Harvard").location(new Point(71.1167, 42.3770)).build();
|
||||||
.id("campus:Harvard")
|
|
||||||
.name("Harvard")
|
|
||||||
.location(new Point(71.1167, 42.3770))
|
|
||||||
.build();
|
|
||||||
|
|
||||||
private final Campus Penn = Campus.Builder.newInstance()
|
private final Campus Penn = Campus.Builder.newInstance().id("campus:Penn").name("Penn").location(new Point(75.1932, 39.9522)).build();
|
||||||
.id("campus:Penn")
|
|
||||||
.name("Penn")
|
|
||||||
.location(new Point(75.1932, 39.9522))
|
|
||||||
.build();
|
|
||||||
|
|
||||||
private final Campus Princeton = Campus.Builder.newInstance()
|
private final Campus Princeton = Campus.Builder.newInstance().id("campus:Princeton").name("Princeton").location(new Point(74.6514, 40.3340)).build();
|
||||||
.id("campus:Princeton")
|
|
||||||
.name("Princeton")
|
|
||||||
.location(new Point(74.6514, 40.3340))
|
|
||||||
.build();
|
|
||||||
|
|
||||||
private final Campus Yale = Campus.Builder.newInstance()
|
private final Campus Yale = Campus.Builder.newInstance().id("campus:Yale").name("Yale").location(new Point(72.9223, 41.3163)).build();
|
||||||
.id("campus:Yale")
|
|
||||||
.name("Yale")
|
|
||||||
.location(new Point(72.9223, 41.3163))
|
|
||||||
.build();
|
|
||||||
|
|
||||||
private final Point Boston = new Point(71.0589, 42.3601);
|
private final Point Boston = new Point(71.0589, 42.3601);
|
||||||
private final Point NewYorkCity = new Point(74.0059, 40.7128);
|
private final Point NewYorkCity = new Point(74.0059, 40.7128);
|
||||||
|
|
|
@ -31,24 +31,14 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest {
|
||||||
static final String joeCollegeId = "student:" + joe + ":" + college;
|
static final String joeCollegeId = "student:" + joe + ":" + college;
|
||||||
static final DateTime joeCollegeDob = DateTime.now().minusYears(21);
|
static final DateTime joeCollegeDob = DateTime.now().minusYears(21);
|
||||||
static final Student joeCollege = new Student(joeCollegeId, joe, college, joeCollegeDob);
|
static final Student joeCollege = new Student(joeCollegeId, joe, college, joeCollegeDob);
|
||||||
static final JsonObject jsonJoeCollege = JsonObject.empty()
|
static final JsonObject jsonJoeCollege = JsonObject.empty().put(typeField, Student.class.getName()).put("firstName", joe).put("lastName", college).put("created", DateTime.now().getMillis()).put("version", 1);
|
||||||
.put(typeField, Student.class.getName())
|
|
||||||
.put("firstName", joe)
|
|
||||||
.put("lastName", college)
|
|
||||||
.put("created", DateTime.now().getMillis())
|
|
||||||
.put("version", 1);
|
|
||||||
|
|
||||||
static final String judy = "Judy";
|
static final String judy = "Judy";
|
||||||
static final String jetson = "Jetson";
|
static final String jetson = "Jetson";
|
||||||
static final String judyJetsonId = "student:" + judy + ":" + jetson;
|
static final String judyJetsonId = "student:" + judy + ":" + jetson;
|
||||||
static final DateTime judyJetsonDob = DateTime.now().minusYears(19).minusMonths(5).minusDays(3);
|
static final DateTime judyJetsonDob = DateTime.now().minusYears(19).minusMonths(5).minusDays(3);
|
||||||
static final Student judyJetson = new Student(judyJetsonId, judy, jetson, judyJetsonDob);
|
static final Student judyJetson = new Student(judyJetsonId, judy, jetson, judyJetsonDob);
|
||||||
static final JsonObject jsonJudyJetson = JsonObject.empty()
|
static final JsonObject jsonJudyJetson = JsonObject.empty().put(typeField, Student.class.getName()).put("firstName", judy).put("lastName", jetson).put("created", DateTime.now().getMillis()).put("version", 1);
|
||||||
.put(typeField, Student.class.getName())
|
|
||||||
.put("firstName", judy)
|
|
||||||
.put("lastName", jetson)
|
|
||||||
.put("created", DateTime.now().getMillis())
|
|
||||||
.put("version", 1);
|
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
StudentServiceImpl studentService;
|
StudentServiceImpl studentService;
|
||||||
|
@ -77,7 +67,7 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest {
|
||||||
assertEquals(expectedStudent.getId(), actualStudent.getId());
|
assertEquals(expectedStudent.getId(), actualStudent.getId());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test(expected=ConstraintViolationException.class)
|
@Test(expected = ConstraintViolationException.class)
|
||||||
public void whenCreatingStudentWithInvalidFirstName_thenConstraintViolationException() {
|
public void whenCreatingStudentWithInvalidFirstName_thenConstraintViolationException() {
|
||||||
String firstName = "Er+ic";
|
String firstName = "Er+ic";
|
||||||
String lastName = "Stratton";
|
String lastName = "Stratton";
|
||||||
|
@ -87,7 +77,7 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest {
|
||||||
studentService.create(student);
|
studentService.create(student);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test(expected=ConstraintViolationException.class)
|
@Test(expected = ConstraintViolationException.class)
|
||||||
public void whenCreatingStudentWithFutureDob_thenConstraintViolationException() {
|
public void whenCreatingStudentWithFutureDob_thenConstraintViolationException() {
|
||||||
String firstName = "Jane";
|
String firstName = "Jane";
|
||||||
String lastName = "Doe";
|
String lastName = "Doe";
|
||||||
|
@ -135,8 +125,8 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest {
|
||||||
|
|
||||||
private boolean resultContains(List<Student> resultList, Student student) {
|
private boolean resultContains(List<Student> resultList, Student student) {
|
||||||
boolean found = false;
|
boolean found = false;
|
||||||
for(Student p : resultList) {
|
for (Student p : resultList) {
|
||||||
if(p.getId().equals(student.getId())) {
|
if (p.getId().equals(student.getId())) {
|
||||||
found = true;
|
found = true;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
@ -146,8 +136,8 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest {
|
||||||
|
|
||||||
private boolean allResultsContainExpectedFirstName(List<Student> resultList, String firstName) {
|
private boolean allResultsContainExpectedFirstName(List<Student> resultList, String firstName) {
|
||||||
boolean found = false;
|
boolean found = false;
|
||||||
for(Student p : resultList) {
|
for (Student p : resultList) {
|
||||||
if(p.getFirstName().equals(firstName)) {
|
if (p.getFirstName().equals(firstName)) {
|
||||||
found = true;
|
found = true;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
@ -157,8 +147,8 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest {
|
||||||
|
|
||||||
private boolean allResultsContainExpectedLastName(List<Student> resultList, String lastName) {
|
private boolean allResultsContainExpectedLastName(List<Student> resultList, String lastName) {
|
||||||
boolean found = false;
|
boolean found = false;
|
||||||
for(Student p : resultList) {
|
for (Student p : resultList) {
|
||||||
if(p.getLastName().equals(lastName)) {
|
if (p.getLastName().equals(lastName)) {
|
||||||
found = true;
|
found = true;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
|
@ -43,8 +43,7 @@ public class ElasticSearchUnitTests {
|
||||||
@Test
|
@Test
|
||||||
public void givenJsonString_whenJavaObject_thenIndexDocument() {
|
public void givenJsonString_whenJavaObject_thenIndexDocument() {
|
||||||
String jsonObject = "{\"age\":20,\"dateOfBirth\":1471466076564,\"fullName\":\"John Doe\"}";
|
String jsonObject = "{\"age\":20,\"dateOfBirth\":1471466076564,\"fullName\":\"John Doe\"}";
|
||||||
IndexResponse response = client.prepareIndex("people", "Doe")
|
IndexResponse response = client.prepareIndex("people", "Doe").setSource(jsonObject).get();
|
||||||
.setSource(jsonObject).get();
|
|
||||||
String index = response.getIndex();
|
String index = response.getIndex();
|
||||||
String type = response.getType();
|
String type = response.getType();
|
||||||
assertTrue(response.isCreated());
|
assertTrue(response.isCreated());
|
||||||
|
@ -55,8 +54,7 @@ public class ElasticSearchUnitTests {
|
||||||
@Test
|
@Test
|
||||||
public void givenDocumentId_whenJavaObject_thenDeleteDocument() {
|
public void givenDocumentId_whenJavaObject_thenDeleteDocument() {
|
||||||
String jsonObject = "{\"age\":10,\"dateOfBirth\":1471455886564,\"fullName\":\"Johan Doe\"}";
|
String jsonObject = "{\"age\":10,\"dateOfBirth\":1471455886564,\"fullName\":\"Johan Doe\"}";
|
||||||
IndexResponse response = client.prepareIndex("people", "Doe")
|
IndexResponse response = client.prepareIndex("people", "Doe").setSource(jsonObject).get();
|
||||||
.setSource(jsonObject).get();
|
|
||||||
String id = response.getId();
|
String id = response.getId();
|
||||||
DeleteResponse deleteResponse = client.prepareDelete("people", "Doe", id).get();
|
DeleteResponse deleteResponse = client.prepareDelete("people", "Doe", id).get();
|
||||||
assertTrue(deleteResponse.isFound());
|
assertTrue(deleteResponse.isFound());
|
||||||
|
@ -77,29 +75,11 @@ public class ElasticSearchUnitTests {
|
||||||
@Test
|
@Test
|
||||||
public void givenSearchParamters_thenReturnResults() {
|
public void givenSearchParamters_thenReturnResults() {
|
||||||
boolean isExecutedSuccessfully = true;
|
boolean isExecutedSuccessfully = true;
|
||||||
SearchResponse response = client.prepareSearch()
|
SearchResponse response = client.prepareSearch().setTypes().setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setPostFilter(QueryBuilders.rangeQuery("age").from(5).to(15)).setFrom(0).setSize(60).setExplain(true).execute().actionGet();
|
||||||
.setTypes()
|
|
||||||
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
|
|
||||||
.setPostFilter(QueryBuilders.rangeQuery("age").from(5).to(15))
|
|
||||||
.setFrom(0).setSize(60).setExplain(true)
|
|
||||||
.execute()
|
|
||||||
.actionGet();
|
|
||||||
|
|
||||||
SearchResponse response2 = client.prepareSearch()
|
SearchResponse response2 = client.prepareSearch().setTypes().setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setPostFilter(QueryBuilders.simpleQueryStringQuery("+John -Doe OR Janette")).setFrom(0).setSize(60).setExplain(true).execute().actionGet();
|
||||||
.setTypes()
|
|
||||||
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
|
|
||||||
.setPostFilter(QueryBuilders.simpleQueryStringQuery("+John -Doe OR Janette"))
|
|
||||||
.setFrom(0).setSize(60).setExplain(true)
|
|
||||||
.execute()
|
|
||||||
.actionGet();
|
|
||||||
|
|
||||||
SearchResponse response3 = client.prepareSearch()
|
SearchResponse response3 = client.prepareSearch().setTypes().setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setPostFilter(QueryBuilders.matchQuery("John", "Name*")).setFrom(0).setSize(60).setExplain(true).execute().actionGet();
|
||||||
.setTypes()
|
|
||||||
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
|
|
||||||
.setPostFilter(QueryBuilders.matchQuery("John", "Name*"))
|
|
||||||
.setFrom(0).setSize(60).setExplain(true)
|
|
||||||
.execute()
|
|
||||||
.actionGet();
|
|
||||||
try {
|
try {
|
||||||
response2.getHits();
|
response2.getHits();
|
||||||
response3.getHits();
|
response3.getHits();
|
||||||
|
@ -114,14 +94,8 @@ public class ElasticSearchUnitTests {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenContentBuilder_whenHelpers_thanIndexJson() throws IOException {
|
public void givenContentBuilder_whenHelpers_thanIndexJson() throws IOException {
|
||||||
XContentBuilder builder = XContentFactory.jsonBuilder()
|
XContentBuilder builder = XContentFactory.jsonBuilder().startObject().field("fullName", "Test").field("salary", "11500").field("age", "10").endObject();
|
||||||
.startObject()
|
IndexResponse response = client.prepareIndex("people", "Doe").setSource(builder).get();
|
||||||
.field("fullName", "Test")
|
|
||||||
.field("salary", "11500")
|
|
||||||
.field("age", "10")
|
|
||||||
.endObject();
|
|
||||||
IndexResponse response = client.prepareIndex("people", "Doe")
|
|
||||||
.setSource(builder).get();
|
|
||||||
assertTrue(response.isCreated());
|
assertTrue(response.isCreated());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -9,8 +9,7 @@ import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
|
||||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||||
|
|
||||||
|
@ComponentScan(basePackages = { "com.baeldung.spring.data.neo4j.services" })
|
||||||
@ComponentScan(basePackages = {"com.baeldung.spring.data.neo4j.services"})
|
|
||||||
@Configuration
|
@Configuration
|
||||||
@EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repostory")
|
@EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repostory")
|
||||||
public class MovieDatabaseNeo4jConfiguration extends Neo4jConfiguration {
|
public class MovieDatabaseNeo4jConfiguration extends Neo4jConfiguration {
|
||||||
|
@ -20,10 +19,7 @@ public class MovieDatabaseNeo4jConfiguration extends Neo4jConfiguration {
|
||||||
@Bean
|
@Bean
|
||||||
public org.neo4j.ogm.config.Configuration getConfiguration() {
|
public org.neo4j.ogm.config.Configuration getConfiguration() {
|
||||||
org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration();
|
org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration();
|
||||||
config
|
config.driverConfiguration().setDriverClassName("org.neo4j.ogm.drivers.http.driver.HttpDriver").setURI(URL);
|
||||||
.driverConfiguration()
|
|
||||||
.setDriverClassName("org.neo4j.ogm.drivers.http.driver.HttpDriver")
|
|
||||||
.setURI(URL);
|
|
||||||
return config;
|
return config;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -10,20 +10,17 @@ import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
|
||||||
import org.springframework.data.neo4j.server.Neo4jServer;
|
import org.springframework.data.neo4j.server.Neo4jServer;
|
||||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||||
|
|
||||||
|
|
||||||
@EnableTransactionManagement
|
@EnableTransactionManagement
|
||||||
@ComponentScan(basePackages = {"com.baeldung.spring.data.neo4j.services"})
|
@ComponentScan(basePackages = { "com.baeldung.spring.data.neo4j.services" })
|
||||||
@Configuration
|
@Configuration
|
||||||
@EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repostory")
|
@EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repostory")
|
||||||
@Profile({"embedded", "test"})
|
@Profile({ "embedded", "test" })
|
||||||
public class MovieDatabaseNeo4jTestConfiguration extends Neo4jConfiguration {
|
public class MovieDatabaseNeo4jTestConfiguration extends Neo4jConfiguration {
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public org.neo4j.ogm.config.Configuration getConfiguration() {
|
public org.neo4j.ogm.config.Configuration getConfiguration() {
|
||||||
org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration();
|
org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration();
|
||||||
config
|
config.driverConfiguration().setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver");
|
||||||
.driverConfiguration()
|
|
||||||
.setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver");
|
|
||||||
return config;
|
return config;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -9,7 +9,7 @@ import org.neo4j.ogm.annotation.Relationship;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@JsonIdentityInfo(generator=JSOGGenerator.class)
|
@JsonIdentityInfo(generator = JSOGGenerator.class)
|
||||||
|
|
||||||
@NodeEntity
|
@NodeEntity
|
||||||
public class Movie {
|
public class Movie {
|
||||||
|
@ -21,9 +21,11 @@ public class Movie {
|
||||||
private int released;
|
private int released;
|
||||||
private String tagline;
|
private String tagline;
|
||||||
|
|
||||||
@Relationship(type="ACTED_IN", direction = Relationship.INCOMING) private List<Role> roles;
|
@Relationship(type = "ACTED_IN", direction = Relationship.INCOMING)
|
||||||
|
private List<Role> roles;
|
||||||
|
|
||||||
public Movie() { }
|
public Movie() {
|
||||||
|
}
|
||||||
|
|
||||||
public String getTitle() {
|
public String getTitle() {
|
||||||
return title;
|
return title;
|
||||||
|
@ -57,5 +59,4 @@ public class Movie {
|
||||||
this.roles = roles;
|
this.roles = roles;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,6 +1,5 @@
|
||||||
package com.baeldung.spring.data.neo4j.domain;
|
package com.baeldung.spring.data.neo4j.domain;
|
||||||
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
|
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
|
||||||
import com.voodoodyne.jackson.jsog.JSOGGenerator;
|
import com.voodoodyne.jackson.jsog.JSOGGenerator;
|
||||||
import org.neo4j.ogm.annotation.GraphId;
|
import org.neo4j.ogm.annotation.GraphId;
|
||||||
|
@ -9,7 +8,7 @@ import org.neo4j.ogm.annotation.Relationship;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@JsonIdentityInfo(generator=JSOGGenerator.class)
|
@JsonIdentityInfo(generator = JSOGGenerator.class)
|
||||||
@NodeEntity
|
@NodeEntity
|
||||||
public class Person {
|
public class Person {
|
||||||
@GraphId
|
@GraphId
|
||||||
|
@ -21,7 +20,8 @@ public class Person {
|
||||||
@Relationship(type = "ACTED_IN")
|
@Relationship(type = "ACTED_IN")
|
||||||
private List<Movie> movies;
|
private List<Movie> movies;
|
||||||
|
|
||||||
public Person() { }
|
public Person() {
|
||||||
|
}
|
||||||
|
|
||||||
public String getName() {
|
public String getName() {
|
||||||
return name;
|
return name;
|
||||||
|
|
|
@ -1,6 +1,5 @@
|
||||||
package com.baeldung.spring.data.neo4j.domain;
|
package com.baeldung.spring.data.neo4j.domain;
|
||||||
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
|
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
|
||||||
import com.voodoodyne.jackson.jsog.JSOGGenerator;
|
import com.voodoodyne.jackson.jsog.JSOGGenerator;
|
||||||
import org.neo4j.ogm.annotation.EndNode;
|
import org.neo4j.ogm.annotation.EndNode;
|
||||||
|
@ -10,7 +9,7 @@ import org.neo4j.ogm.annotation.StartNode;
|
||||||
|
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
|
|
||||||
@JsonIdentityInfo(generator=JSOGGenerator.class)
|
@JsonIdentityInfo(generator = JSOGGenerator.class)
|
||||||
@RelationshipEntity(type = "ACTED_IN")
|
@RelationshipEntity(type = "ACTED_IN")
|
||||||
public class Role {
|
public class Role {
|
||||||
@GraphId
|
@GraphId
|
||||||
|
|
|
@ -18,7 +18,5 @@ public interface MovieRepository extends GraphRepository<Movie> {
|
||||||
Collection<Movie> findByTitleContaining(@Param("title") String title);
|
Collection<Movie> findByTitleContaining(@Param("title") String title);
|
||||||
|
|
||||||
@Query("MATCH (m:Movie)<-[:ACTED_IN]-(a:Person) RETURN m.title as movie, collect(a.name) as cast LIMIT {limit}")
|
@Query("MATCH (m:Movie)<-[:ACTED_IN]-(a:Person) RETURN m.title as movie, collect(a.name) as cast LIMIT {limit}")
|
||||||
List<Map<String,Object>> graph(@Param("limit") int limit);
|
List<Map<String, Object>> graph(@Param("limit") int limit);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -4,7 +4,6 @@ import com.baeldung.spring.data.neo4j.domain.Person;
|
||||||
import org.springframework.data.neo4j.repository.GraphRepository;
|
import org.springframework.data.neo4j.repository.GraphRepository;
|
||||||
import org.springframework.stereotype.Repository;
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
|
||||||
@Repository
|
@Repository
|
||||||
public interface PersonRepository extends GraphRepository<Person> {
|
public interface PersonRepository extends GraphRepository<Person> {
|
||||||
|
|
||||||
|
|
|
@ -15,31 +15,31 @@ public class MovieService {
|
||||||
MovieRepository movieRepository;
|
MovieRepository movieRepository;
|
||||||
|
|
||||||
private Map<String, Object> toD3Format(Iterator<Map<String, Object>> result) {
|
private Map<String, Object> toD3Format(Iterator<Map<String, Object>> result) {
|
||||||
List<Map<String,Object>> nodes = new ArrayList<Map<String,Object>>();
|
List<Map<String, Object>> nodes = new ArrayList<Map<String, Object>>();
|
||||||
List<Map<String,Object>> rels= new ArrayList<Map<String,Object>>();
|
List<Map<String, Object>> rels = new ArrayList<Map<String, Object>>();
|
||||||
int i=0;
|
int i = 0;
|
||||||
while (result.hasNext()) {
|
while (result.hasNext()) {
|
||||||
Map<String, Object> row = result.next();
|
Map<String, Object> row = result.next();
|
||||||
nodes.add(map("title",row.get("movie"),"label","movie"));
|
nodes.add(map("title", row.get("movie"), "label", "movie"));
|
||||||
int target=i;
|
int target = i;
|
||||||
i++;
|
i++;
|
||||||
for (Object name : (Collection) row.get("cast")) {
|
for (Object name : (Collection) row.get("cast")) {
|
||||||
Map<String, Object> actor = map("title", name,"label","actor");
|
Map<String, Object> actor = map("title", name, "label", "actor");
|
||||||
int source = nodes.indexOf(actor);
|
int source = nodes.indexOf(actor);
|
||||||
if (source == -1) {
|
if (source == -1) {
|
||||||
nodes.add(actor);
|
nodes.add(actor);
|
||||||
source = i++;
|
source = i++;
|
||||||
}
|
}
|
||||||
rels.add(map("source",source,"target",target));
|
rels.add(map("source", source, "target", target));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return map("nodes", nodes, "links", rels);
|
return map("nodes", nodes, "links", rels);
|
||||||
}
|
}
|
||||||
|
|
||||||
private Map<String, Object> map(String key1, Object value1, String key2, Object value2) {
|
private Map<String, Object> map(String key1, Object value1, String key2, Object value2) {
|
||||||
Map<String, Object> result = new HashMap<String,Object>(2);
|
Map<String, Object> result = new HashMap<String, Object>(2);
|
||||||
result.put(key1,value1);
|
result.put(key1, value1);
|
||||||
result.put(key2,value2);
|
result.put(key2, value2);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -82,8 +82,7 @@ public class MovieRepositoryTest {
|
||||||
@DirtiesContext
|
@DirtiesContext
|
||||||
public void testFindAll() {
|
public void testFindAll() {
|
||||||
System.out.println("findAll");
|
System.out.println("findAll");
|
||||||
Collection<Movie> result =
|
Collection<Movie> result = (Collection<Movie>) movieRepository.findAll();
|
||||||
(Collection<Movie>) movieRepository.findAll();
|
|
||||||
assertNotNull(result);
|
assertNotNull(result);
|
||||||
assertEquals(1, result.size());
|
assertEquals(1, result.size());
|
||||||
}
|
}
|
||||||
|
@ -93,8 +92,7 @@ public class MovieRepositoryTest {
|
||||||
public void testFindByTitleContaining() {
|
public void testFindByTitleContaining() {
|
||||||
System.out.println("findByTitleContaining");
|
System.out.println("findByTitleContaining");
|
||||||
String title = "Italian";
|
String title = "Italian";
|
||||||
Collection<Movie> result =
|
Collection<Movie> result = movieRepository.findByTitleContaining(title);
|
||||||
movieRepository.findByTitleContaining(title);
|
|
||||||
assertNotNull(result);
|
assertNotNull(result);
|
||||||
assertEquals(1, result.size());
|
assertEquals(1, result.size());
|
||||||
}
|
}
|
||||||
|
@ -126,8 +124,7 @@ public class MovieRepositoryTest {
|
||||||
public void testDeleteAll() {
|
public void testDeleteAll() {
|
||||||
System.out.println("deleteAll");
|
System.out.println("deleteAll");
|
||||||
movieRepository.deleteAll();
|
movieRepository.deleteAll();
|
||||||
Collection<Movie> result =
|
Collection<Movie> result = (Collection<Movie>) movieRepository.findAll();
|
||||||
(Collection<Movie>) movieRepository.findAll();
|
|
||||||
assertEquals(0, result.size());
|
assertEquals(0, result.size());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,6 +1,5 @@
|
||||||
package com.baeldung.spring.data.redis.queue;
|
package com.baeldung.spring.data.redis.queue;
|
||||||
|
|
||||||
|
|
||||||
public interface MessagePublisher {
|
public interface MessagePublisher {
|
||||||
|
|
||||||
void publish(final String message);
|
void publish(final String message);
|
||||||
|
|
|
@ -16,8 +16,7 @@ public class RedisMessagePublisher implements MessagePublisher {
|
||||||
public RedisMessagePublisher() {
|
public RedisMessagePublisher() {
|
||||||
}
|
}
|
||||||
|
|
||||||
public RedisMessagePublisher(final RedisTemplate<String, Object> redisTemplate,
|
public RedisMessagePublisher(final RedisTemplate<String, Object> redisTemplate, final ChannelTopic topic) {
|
||||||
final ChannelTopic topic) {
|
|
||||||
this.redisTemplate = redisTemplate;
|
this.redisTemplate = redisTemplate;
|
||||||
this.topic = topic;
|
this.topic = topic;
|
||||||
}
|
}
|
||||||
|
|
|
@ -18,16 +18,16 @@ import javax.sql.DataSource;
|
||||||
@ContextConfiguration(classes = { Cause1NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class)
|
@ContextConfiguration(classes = { Cause1NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||||
public class InvalidResourceUsageExceptionTest {
|
public class InvalidResourceUsageExceptionTest {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private IFooService fooService;
|
private IFooService fooService;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private DataSource restDataSource;
|
private DataSource restDataSource;
|
||||||
|
|
||||||
@Test(expected = InvalidDataAccessResourceUsageException.class)
|
@Test(expected = InvalidDataAccessResourceUsageException.class)
|
||||||
public void whenRetrievingDataUserNoSelectRights_thenInvalidResourceUsageException() {
|
public void whenRetrievingDataUserNoSelectRights_thenInvalidResourceUsageException() {
|
||||||
final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource);
|
final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource);
|
||||||
jdbcTemplate.execute("revoke select from tutorialuser");
|
jdbcTemplate.execute("revoke select from tutorialuser");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
fooService.findAll();
|
fooService.findAll();
|
||||||
|
@ -36,11 +36,11 @@ public class InvalidResourceUsageExceptionTest {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test(expected = BadSqlGrammarException.class)
|
@Test(expected = BadSqlGrammarException.class)
|
||||||
public void whenIncorrectSql_thenBadSqlGrammarException() {
|
public void whenIncorrectSql_thenBadSqlGrammarException() {
|
||||||
final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource);
|
final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource);
|
||||||
|
|
||||||
jdbcTemplate.queryForObject("select * fro foo where id=3", Integer.class);
|
jdbcTemplate.queryForObject("select * fro foo where id=3", Integer.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -4,78 +4,78 @@ import java.io.Serializable;
|
||||||
|
|
||||||
public class Item implements Serializable {
|
public class Item implements Serializable {
|
||||||
|
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
private Integer itemId;
|
private Integer itemId;
|
||||||
private String itemName;
|
private String itemName;
|
||||||
private String itemDescription;
|
private String itemDescription;
|
||||||
private Integer itemPrice;
|
private Integer itemPrice;
|
||||||
|
|
||||||
// constructors
|
// constructors
|
||||||
public Item() {
|
public Item() {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public Item(final Integer itemId, final String itemName, final String itemDescription) {
|
public Item(final Integer itemId, final String itemName, final String itemDescription) {
|
||||||
super();
|
super();
|
||||||
this.itemId = itemId;
|
this.itemId = itemId;
|
||||||
this.itemName = itemName;
|
this.itemName = itemName;
|
||||||
this.itemDescription = itemDescription;
|
this.itemDescription = itemDescription;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int hashCode() {
|
public int hashCode() {
|
||||||
final int prime = 31;
|
final int prime = 31;
|
||||||
int result = 1;
|
int result = 1;
|
||||||
result = prime * result + ((itemId == null) ? 0 : itemId.hashCode());
|
result = prime * result + ((itemId == null) ? 0 : itemId.hashCode());
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean equals(final Object obj) {
|
public boolean equals(final Object obj) {
|
||||||
if (this == obj)
|
if (this == obj)
|
||||||
return true;
|
return true;
|
||||||
if (obj == null)
|
if (obj == null)
|
||||||
return false;
|
return false;
|
||||||
if (getClass() != obj.getClass())
|
if (getClass() != obj.getClass())
|
||||||
return false;
|
return false;
|
||||||
final Item other = (Item) obj;
|
final Item other = (Item) obj;
|
||||||
if (itemId == null) {
|
if (itemId == null) {
|
||||||
if (other.itemId != null)
|
if (other.itemId != null)
|
||||||
return false;
|
return false;
|
||||||
} else if (!itemId.equals(other.itemId))
|
} else if (!itemId.equals(other.itemId))
|
||||||
return false;
|
return false;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Integer getItemId() {
|
public Integer getItemId() {
|
||||||
return itemId;
|
return itemId;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setItemId(final Integer itemId) {
|
public void setItemId(final Integer itemId) {
|
||||||
this.itemId = itemId;
|
this.itemId = itemId;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getItemName() {
|
public String getItemName() {
|
||||||
return itemName;
|
return itemName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setItemName(final String itemName) {
|
public void setItemName(final String itemName) {
|
||||||
this.itemName = itemName;
|
this.itemName = itemName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getItemDescription() {
|
public String getItemDescription() {
|
||||||
return itemDescription;
|
return itemDescription;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Integer getItemPrice() {
|
public Integer getItemPrice() {
|
||||||
return itemPrice;
|
return itemPrice;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setItemPrice(final Integer itemPrice) {
|
public void setItemPrice(final Integer itemPrice) {
|
||||||
this.itemPrice = itemPrice;
|
this.itemPrice = itemPrice;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setItemDescription(final String itemDescription) {
|
public void setItemDescription(final String itemDescription) {
|
||||||
this.itemDescription = itemDescription;
|
this.itemDescription = itemDescription;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -9,12 +9,11 @@ public class HibernateUtil {
|
||||||
@SuppressWarnings("deprecation")
|
@SuppressWarnings("deprecation")
|
||||||
public static Session getHibernateSession() {
|
public static Session getHibernateSession() {
|
||||||
|
|
||||||
final SessionFactory sf = new Configuration()
|
final SessionFactory sf = new Configuration().configure("criteria.cfg.xml").buildSessionFactory();
|
||||||
.configure("criteria.cfg.xml").buildSessionFactory();
|
|
||||||
|
|
||||||
// factory = new Configuration().configure().buildSessionFactory();
|
// factory = new Configuration().configure().buildSessionFactory();
|
||||||
final Session session = sf.openSession();
|
final Session session = sf.openSession();
|
||||||
return session;
|
return session;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -26,228 +26,226 @@ import com.baeldung.hibernate.criteria.util.HibernateUtil;
|
||||||
|
|
||||||
public class ApplicationView {
|
public class ApplicationView {
|
||||||
|
|
||||||
// default Constructor
|
// default Constructor
|
||||||
public ApplicationView() {
|
public ApplicationView() {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean checkIfCriteriaTimeLower() {
|
public boolean checkIfCriteriaTimeLower() {
|
||||||
final Session session = HibernateUtil.getHibernateSession();
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
final Criteria cr = session.createCriteria(Item.class);
|
final Criteria cr = session.createCriteria(Item.class);
|
||||||
Transaction tx = null;
|
Transaction tx = null;
|
||||||
|
|
||||||
// calculate the time taken by criteria
|
// calculate the time taken by criteria
|
||||||
final long startTimeCriteria = System.nanoTime();
|
final long startTimeCriteria = System.nanoTime();
|
||||||
cr.add(Restrictions.like("itemName", "%item One%"));
|
cr.add(Restrictions.like("itemName", "%item One%"));
|
||||||
final List results = cr.list();
|
final List results = cr.list();
|
||||||
final long endTimeCriteria = System.nanoTime();
|
final long endTimeCriteria = System.nanoTime();
|
||||||
final long durationCriteria = (endTimeCriteria - startTimeCriteria) / 1000;
|
final long durationCriteria = (endTimeCriteria - startTimeCriteria) / 1000;
|
||||||
|
|
||||||
// calculate the time taken by HQL
|
// calculate the time taken by HQL
|
||||||
final long startTimeHQL = System.nanoTime();
|
final long startTimeHQL = System.nanoTime();
|
||||||
tx = session.beginTransaction();
|
tx = session.beginTransaction();
|
||||||
final List items = session.createQuery("FROM Item where itemName like '%item One%'").list();
|
final List items = session.createQuery("FROM Item where itemName like '%item One%'").list();
|
||||||
final long endTimeHQL = System.nanoTime();
|
final long endTimeHQL = System.nanoTime();
|
||||||
final long durationHQL = (endTimeHQL - startTimeHQL) / 1000;
|
final long durationHQL = (endTimeHQL - startTimeHQL) / 1000;
|
||||||
|
|
||||||
if (durationCriteria > durationHQL) {
|
if (durationCriteria > durationHQL) {
|
||||||
return false;
|
return false;
|
||||||
} else {
|
} else {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// To get items having price more than 1000
|
// To get items having price more than 1000
|
||||||
public String[] greaterThanCriteria() {
|
public String[] greaterThanCriteria() {
|
||||||
final Session session = HibernateUtil.getHibernateSession();
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
final Criteria cr = session.createCriteria(Item.class);
|
final Criteria cr = session.createCriteria(Item.class);
|
||||||
cr.add(Restrictions.gt("itemPrice", 1000));
|
cr.add(Restrictions.gt("itemPrice", 1000));
|
||||||
final List<Item> greaterThanItemsList = cr.list();
|
final List<Item> greaterThanItemsList = cr.list();
|
||||||
final String greaterThanItems[] = new String[greaterThanItemsList.size()];
|
final String greaterThanItems[] = new String[greaterThanItemsList.size()];
|
||||||
for (int i = 0; i < greaterThanItemsList.size(); i++) {
|
for (int i = 0; i < greaterThanItemsList.size(); i++) {
|
||||||
greaterThanItems[i] = greaterThanItemsList.get(i).getItemName();
|
greaterThanItems[i] = greaterThanItemsList.get(i).getItemName();
|
||||||
}
|
}
|
||||||
session.close();
|
session.close();
|
||||||
return greaterThanItems;
|
return greaterThanItems;
|
||||||
}
|
}
|
||||||
|
|
||||||
// To get items having price less than 1000
|
// To get items having price less than 1000
|
||||||
public String[] lessThanCriteria() {
|
public String[] lessThanCriteria() {
|
||||||
final Session session = HibernateUtil.getHibernateSession();
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
final Criteria cr = session.createCriteria(Item.class);
|
final Criteria cr = session.createCriteria(Item.class);
|
||||||
cr.add(Restrictions.lt("itemPrice", 1000));
|
cr.add(Restrictions.lt("itemPrice", 1000));
|
||||||
final List<Item> lessThanItemsList = cr.list();
|
final List<Item> lessThanItemsList = cr.list();
|
||||||
final String lessThanItems[] = new String[lessThanItemsList.size()];
|
final String lessThanItems[] = new String[lessThanItemsList.size()];
|
||||||
for (int i = 0; i < lessThanItemsList.size(); i++) {
|
for (int i = 0; i < lessThanItemsList.size(); i++) {
|
||||||
lessThanItems[i] = lessThanItemsList.get(i).getItemName();
|
lessThanItems[i] = lessThanItemsList.get(i).getItemName();
|
||||||
}
|
}
|
||||||
session.close();
|
session.close();
|
||||||
return lessThanItems;
|
return lessThanItems;
|
||||||
}
|
}
|
||||||
|
|
||||||
// To get items whose Name start with Chair
|
// To get items whose Name start with Chair
|
||||||
public String[] likeCriteria() {
|
public String[] likeCriteria() {
|
||||||
final Session session = HibernateUtil.getHibernateSession();
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
|
|
||||||
final Criteria cr = session.createCriteria(Item.class);
|
final Criteria cr = session.createCriteria(Item.class);
|
||||||
cr.add(Restrictions.like("itemName", "%chair%"));
|
cr.add(Restrictions.like("itemName", "%chair%"));
|
||||||
final List<Item> likeItemsList = cr.list();
|
final List<Item> likeItemsList = cr.list();
|
||||||
final String likeItems[] = new String[likeItemsList.size()];
|
final String likeItems[] = new String[likeItemsList.size()];
|
||||||
for (int i = 0; i < likeItemsList.size(); i++) {
|
for (int i = 0; i < likeItemsList.size(); i++) {
|
||||||
likeItems[i] = likeItemsList.get(i).getItemName();
|
likeItems[i] = likeItemsList.get(i).getItemName();
|
||||||
}
|
}
|
||||||
session.close();
|
session.close();
|
||||||
return likeItems;
|
return likeItems;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Case sensitive search
|
// Case sensitive search
|
||||||
public String[] likeCaseCriteria() {
|
public String[] likeCaseCriteria() {
|
||||||
final Session session = HibernateUtil.getHibernateSession();
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
final Criteria cr = session.createCriteria(Item.class);
|
final Criteria cr = session.createCriteria(Item.class);
|
||||||
cr.add(Restrictions.ilike("itemName", "%Chair%"));
|
cr.add(Restrictions.ilike("itemName", "%Chair%"));
|
||||||
final List<Item> ilikeItemsList = cr.list();
|
final List<Item> ilikeItemsList = cr.list();
|
||||||
final String ilikeItems[] = new String[ilikeItemsList.size()];
|
final String ilikeItems[] = new String[ilikeItemsList.size()];
|
||||||
for (int i = 0; i < ilikeItemsList.size(); i++) {
|
for (int i = 0; i < ilikeItemsList.size(); i++) {
|
||||||
ilikeItems[i] = ilikeItemsList.get(i).getItemName();
|
ilikeItems[i] = ilikeItemsList.get(i).getItemName();
|
||||||
}
|
}
|
||||||
session.close();
|
session.close();
|
||||||
return ilikeItems;
|
return ilikeItems;
|
||||||
}
|
}
|
||||||
|
|
||||||
// To get records having itemPrice in between 100 and 200
|
// To get records having itemPrice in between 100 and 200
|
||||||
public String[] betweenCriteria() {
|
public String[] betweenCriteria() {
|
||||||
final Session session = HibernateUtil.getHibernateSession();
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
final Criteria cr = session.createCriteria(Item.class);
|
final Criteria cr = session.createCriteria(Item.class);
|
||||||
// To get items having price more than 1000
|
// To get items having price more than 1000
|
||||||
cr.add(Restrictions.between("itemPrice", 100, 200));
|
cr.add(Restrictions.between("itemPrice", 100, 200));
|
||||||
final List<Item> betweenItemsList = cr.list();
|
final List<Item> betweenItemsList = cr.list();
|
||||||
final String betweenItems[] = new String[betweenItemsList.size()];
|
final String betweenItems[] = new String[betweenItemsList.size()];
|
||||||
for (int i = 0; i < betweenItemsList.size(); i++) {
|
for (int i = 0; i < betweenItemsList.size(); i++) {
|
||||||
betweenItems[i] = betweenItemsList.get(i).getItemName();
|
betweenItems[i] = betweenItemsList.get(i).getItemName();
|
||||||
}
|
}
|
||||||
session.close();
|
session.close();
|
||||||
return betweenItems;
|
return betweenItems;
|
||||||
}
|
}
|
||||||
|
|
||||||
// To check if the given property is null
|
// To check if the given property is null
|
||||||
public String[] nullCriteria() {
|
public String[] nullCriteria() {
|
||||||
final Session session = HibernateUtil.getHibernateSession();
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
final Criteria cr = session.createCriteria(Item.class);
|
final Criteria cr = session.createCriteria(Item.class);
|
||||||
cr.add(Restrictions.isNull("itemDescription"));
|
cr.add(Restrictions.isNull("itemDescription"));
|
||||||
final List<Item> nullItemsList = cr.list();
|
final List<Item> nullItemsList = cr.list();
|
||||||
final String nullDescItems[] = new String[nullItemsList.size()];
|
final String nullDescItems[] = new String[nullItemsList.size()];
|
||||||
for (int i = 0; i < nullItemsList.size(); i++) {
|
for (int i = 0; i < nullItemsList.size(); i++) {
|
||||||
nullDescItems[i] = nullItemsList.get(i).getItemName();
|
nullDescItems[i] = nullItemsList.get(i).getItemName();
|
||||||
}
|
}
|
||||||
session.close();
|
session.close();
|
||||||
return nullDescItems;
|
return nullDescItems;
|
||||||
}
|
}
|
||||||
|
|
||||||
// To check if the given property is not null
|
// To check if the given property is not null
|
||||||
public String[] notNullCriteria() {
|
public String[] notNullCriteria() {
|
||||||
final Session session = HibernateUtil.getHibernateSession();
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
final Criteria cr = session.createCriteria(Item.class);
|
final Criteria cr = session.createCriteria(Item.class);
|
||||||
cr.add(Restrictions.isNotNull("itemDescription"));
|
cr.add(Restrictions.isNotNull("itemDescription"));
|
||||||
final List<Item> notNullItemsList = cr.list();
|
final List<Item> notNullItemsList = cr.list();
|
||||||
final String notNullDescItems[] = new String[notNullItemsList.size()];
|
final String notNullDescItems[] = new String[notNullItemsList.size()];
|
||||||
for (int i = 0; i < notNullItemsList.size(); i++) {
|
for (int i = 0; i < notNullItemsList.size(); i++) {
|
||||||
notNullDescItems[i] = notNullItemsList.get(i).getItemName();
|
notNullDescItems[i] = notNullItemsList.get(i).getItemName();
|
||||||
}
|
}
|
||||||
session.close();
|
session.close();
|
||||||
return notNullDescItems;
|
return notNullDescItems;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Adding more than one expression in one cr
|
// Adding more than one expression in one cr
|
||||||
public String[] twoCriteria() {
|
public String[] twoCriteria() {
|
||||||
final Session session = HibernateUtil.getHibernateSession();
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
final Criteria cr = session.createCriteria(Item.class);
|
final Criteria cr = session.createCriteria(Item.class);
|
||||||
cr.add(Restrictions.isNull("itemDescription"));
|
cr.add(Restrictions.isNull("itemDescription"));
|
||||||
cr.add(Restrictions.like("itemName", "chair%"));
|
cr.add(Restrictions.like("itemName", "chair%"));
|
||||||
final List<Item> notNullItemsList = cr.list();
|
final List<Item> notNullItemsList = cr.list();
|
||||||
final String notNullDescItems[] = new String[notNullItemsList.size()];
|
final String notNullDescItems[] = new String[notNullItemsList.size()];
|
||||||
for (int i = 0; i < notNullItemsList.size(); i++) {
|
for (int i = 0; i < notNullItemsList.size(); i++) {
|
||||||
notNullDescItems[i] = notNullItemsList.get(i).getItemName();
|
notNullDescItems[i] = notNullItemsList.get(i).getItemName();
|
||||||
}
|
}
|
||||||
session.close();
|
session.close();
|
||||||
return notNullDescItems;
|
return notNullDescItems;
|
||||||
}
|
}
|
||||||
|
|
||||||
// To get items matching with the above defined conditions joined
|
// To get items matching with the above defined conditions joined
|
||||||
// with Logical AND
|
// with Logical AND
|
||||||
public String[] andLogicalCriteria() {
|
public String[] andLogicalCriteria() {
|
||||||
final Session session = HibernateUtil.getHibernateSession();
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
final Criteria cr = session.createCriteria(Item.class);
|
final Criteria cr = session.createCriteria(Item.class);
|
||||||
final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000);
|
final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000);
|
||||||
final Criterion chairItems = Restrictions.like("itemName", "Chair%");
|
final Criterion chairItems = Restrictions.like("itemName", "Chair%");
|
||||||
final LogicalExpression andExample = Restrictions.and(greaterThanPrice, chairItems);
|
final LogicalExpression andExample = Restrictions.and(greaterThanPrice, chairItems);
|
||||||
cr.add(andExample);
|
cr.add(andExample);
|
||||||
final List<Item> andItemsList = cr.list();
|
final List<Item> andItemsList = cr.list();
|
||||||
final String andItems[] = new String[andItemsList.size()];
|
final String andItems[] = new String[andItemsList.size()];
|
||||||
for (int i = 0; i < andItemsList.size(); i++) {
|
for (int i = 0; i < andItemsList.size(); i++) {
|
||||||
andItems[i] = andItemsList.get(i).getItemName();
|
andItems[i] = andItemsList.get(i).getItemName();
|
||||||
}
|
}
|
||||||
session.close();
|
session.close();
|
||||||
return andItems;
|
return andItems;
|
||||||
}
|
}
|
||||||
|
|
||||||
// To get items matching with the above defined conditions joined
|
// To get items matching with the above defined conditions joined
|
||||||
// with Logical OR
|
// with Logical OR
|
||||||
public String[] orLogicalCriteria() {
|
public String[] orLogicalCriteria() {
|
||||||
final Session session = HibernateUtil.getHibernateSession();
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
final Criteria cr = session.createCriteria(Item.class);
|
final Criteria cr = session.createCriteria(Item.class);
|
||||||
final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000);
|
final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000);
|
||||||
final Criterion chairItems = Restrictions.like("itemName", "Chair%");
|
final Criterion chairItems = Restrictions.like("itemName", "Chair%");
|
||||||
final LogicalExpression orExample = Restrictions.or(greaterThanPrice, chairItems);
|
final LogicalExpression orExample = Restrictions.or(greaterThanPrice, chairItems);
|
||||||
cr.add(orExample);
|
cr.add(orExample);
|
||||||
final List<Item> orItemsList = cr.list();
|
final List<Item> orItemsList = cr.list();
|
||||||
final String orItems[] = new String[orItemsList.size()];
|
final String orItems[] = new String[orItemsList.size()];
|
||||||
for (int i = 0; i < orItemsList.size(); i++) {
|
for (int i = 0; i < orItemsList.size(); i++) {
|
||||||
orItems[i] = orItemsList.get(i).getItemName();
|
orItems[i] = orItemsList.get(i).getItemName();
|
||||||
}
|
}
|
||||||
session.close();
|
session.close();
|
||||||
return orItems;
|
return orItems;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sorting example
|
// Sorting example
|
||||||
public String[] sortingCriteria() {
|
public String[] sortingCriteria() {
|
||||||
final Session session = HibernateUtil.getHibernateSession();
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
final Criteria cr = session.createCriteria(Item.class);
|
final Criteria cr = session.createCriteria(Item.class);
|
||||||
cr.addOrder(Order.asc("itemName"));
|
cr.addOrder(Order.asc("itemName"));
|
||||||
cr.addOrder(Order.desc("itemPrice")).list();
|
cr.addOrder(Order.desc("itemPrice")).list();
|
||||||
final List<Item> sortedItemsList = cr.list();
|
final List<Item> sortedItemsList = cr.list();
|
||||||
final String sortedItems[] = new String[sortedItemsList.size()];
|
final String sortedItems[] = new String[sortedItemsList.size()];
|
||||||
for (int i = 0; i < sortedItemsList.size(); i++) {
|
for (int i = 0; i < sortedItemsList.size(); i++) {
|
||||||
sortedItems[i] = sortedItemsList.get(i).getItemName();
|
sortedItems[i] = sortedItemsList.get(i).getItemName();
|
||||||
}
|
}
|
||||||
session.close();
|
session.close();
|
||||||
return sortedItems;
|
return sortedItems;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set projections Row Count
|
// Set projections Row Count
|
||||||
public Long[] projectionRowCount() {
|
public Long[] projectionRowCount() {
|
||||||
final Session session = HibernateUtil.getHibernateSession();
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
final List<Long> itemProjected = session.createCriteria(Item.class).setProjection(Projections.rowCount())
|
final List<Long> itemProjected = session.createCriteria(Item.class).setProjection(Projections.rowCount()).list();
|
||||||
.list();
|
final Long projectedRowCount[] = new Long[itemProjected.size()];
|
||||||
final Long projectedRowCount[] = new Long[itemProjected.size()];
|
for (int i = 0; i < itemProjected.size(); i++) {
|
||||||
for (int i = 0; i < itemProjected.size(); i++) {
|
projectedRowCount[i] = itemProjected.get(i);
|
||||||
projectedRowCount[i] = itemProjected.get(i);
|
}
|
||||||
}
|
session.close();
|
||||||
session.close();
|
return projectedRowCount;
|
||||||
return projectedRowCount;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// Set projections average of itemPrice
|
// Set projections average of itemPrice
|
||||||
public Double[] projectionAverage() {
|
public Double[] projectionAverage() {
|
||||||
final Session session = HibernateUtil.getHibernateSession();
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
final List avgItemPriceList = session.createCriteria(Item.class)
|
final List avgItemPriceList = session.createCriteria(Item.class).setProjection(Projections.projectionList().add(Projections.avg("itemPrice"))).list();
|
||||||
.setProjection(Projections.projectionList().add(Projections.avg("itemPrice"))).list();
|
|
||||||
|
|
||||||
final Double avgItemPrice[] = new Double[avgItemPriceList.size()];
|
final Double avgItemPrice[] = new Double[avgItemPriceList.size()];
|
||||||
for (int i = 0; i < avgItemPriceList.size(); i++) {
|
for (int i = 0; i < avgItemPriceList.size(); i++) {
|
||||||
avgItemPrice[i] = (Double) avgItemPriceList.get(i);
|
avgItemPrice[i] = (Double) avgItemPriceList.get(i);
|
||||||
}
|
}
|
||||||
session.close();
|
session.close();
|
||||||
return avgItemPrice;
|
return avgItemPrice;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -5,54 +5,54 @@ import java.io.Serializable;
|
||||||
import java.sql.Date;
|
import java.sql.Date;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
@Table (name = "USER_ORDER")
|
@Table(name = "USER_ORDER")
|
||||||
public class OrderDetail implements Serializable{
|
public class OrderDetail implements Serializable {
|
||||||
|
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
@Id
|
@Id
|
||||||
@GeneratedValue
|
@GeneratedValue
|
||||||
@Column(name="ORDER_ID")
|
@Column(name = "ORDER_ID")
|
||||||
private Long orderId;
|
private Long orderId;
|
||||||
|
|
||||||
public OrderDetail(){
|
public OrderDetail() {
|
||||||
}
|
}
|
||||||
|
|
||||||
public OrderDetail(Date orderDate, String orderDesc) {
|
public OrderDetail(Date orderDate, String orderDesc) {
|
||||||
super();
|
super();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int hashCode() {
|
public int hashCode() {
|
||||||
final int prime = 31;
|
final int prime = 31;
|
||||||
int result = 1;
|
int result = 1;
|
||||||
result = prime * result + ((orderId == null) ? 0 : orderId.hashCode());
|
result = prime * result + ((orderId == null) ? 0 : orderId.hashCode());
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
@Override
|
|
||||||
public boolean equals(Object obj) {
|
|
||||||
if (this == obj)
|
|
||||||
return true;
|
|
||||||
if (obj == null)
|
|
||||||
return false;
|
|
||||||
if (getClass() != obj.getClass())
|
|
||||||
return false;
|
|
||||||
OrderDetail other = (OrderDetail) obj;
|
|
||||||
if (orderId == null) {
|
|
||||||
if (other.orderId != null)
|
|
||||||
return false;
|
|
||||||
} else if (!orderId.equals(other.orderId))
|
|
||||||
return false;
|
|
||||||
|
|
||||||
return true;
|
@Override
|
||||||
}
|
public boolean equals(Object obj) {
|
||||||
|
if (this == obj)
|
||||||
|
return true;
|
||||||
|
if (obj == null)
|
||||||
|
return false;
|
||||||
|
if (getClass() != obj.getClass())
|
||||||
|
return false;
|
||||||
|
OrderDetail other = (OrderDetail) obj;
|
||||||
|
if (orderId == null) {
|
||||||
|
if (other.orderId != null)
|
||||||
|
return false;
|
||||||
|
} else if (!orderId.equals(other.orderId))
|
||||||
|
return false;
|
||||||
|
|
||||||
public Long getOrderId() {
|
return true;
|
||||||
return orderId;
|
}
|
||||||
}
|
|
||||||
public void setOrderId(Long orderId) {
|
public Long getOrderId() {
|
||||||
this.orderId = orderId;
|
return orderId;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void setOrderId(Long orderId) {
|
||||||
|
this.orderId = orderId;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -6,66 +6,66 @@ import java.util.HashSet;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
@Table (name = "USER")
|
@Table(name = "USER")
|
||||||
public class UserEager implements Serializable {
|
public class UserEager implements Serializable {
|
||||||
|
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
@Id
|
@Id
|
||||||
@GeneratedValue
|
@GeneratedValue
|
||||||
@Column(name="USER_ID")
|
@Column(name = "USER_ID")
|
||||||
private Long userId;
|
private Long userId;
|
||||||
|
|
||||||
@OneToMany(fetch = FetchType.EAGER, mappedBy = "user")
|
@OneToMany(fetch = FetchType.EAGER, mappedBy = "user")
|
||||||
private Set<OrderDetail> orderDetail = new HashSet();
|
private Set<OrderDetail> orderDetail = new HashSet();
|
||||||
|
|
||||||
public UserEager() {
|
public UserEager() {
|
||||||
}
|
}
|
||||||
|
|
||||||
public UserEager(final Long userId) {
|
public UserEager(final Long userId) {
|
||||||
super();
|
super();
|
||||||
this.userId = userId;
|
this.userId = userId;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int hashCode() {
|
public int hashCode() {
|
||||||
final int prime = 31;
|
final int prime = 31;
|
||||||
int result = 1;
|
int result = 1;
|
||||||
result = prime * result + ((userId == null) ? 0 : userId.hashCode());
|
result = prime * result + ((userId == null) ? 0 : userId.hashCode());
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean equals(final Object obj) {
|
public boolean equals(final Object obj) {
|
||||||
if (this == obj)
|
if (this == obj)
|
||||||
return true;
|
return true;
|
||||||
if (obj == null)
|
if (obj == null)
|
||||||
return false;
|
return false;
|
||||||
if (getClass() != obj.getClass())
|
if (getClass() != obj.getClass())
|
||||||
return false;
|
return false;
|
||||||
final UserEager other = (UserEager) obj;
|
final UserEager other = (UserEager) obj;
|
||||||
if (userId == null) {
|
if (userId == null) {
|
||||||
if (other.userId != null)
|
if (other.userId != null)
|
||||||
return false;
|
return false;
|
||||||
} else if (!userId.equals(other.userId))
|
} else if (!userId.equals(other.userId))
|
||||||
return false;
|
return false;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Long getUserId() {
|
public Long getUserId() {
|
||||||
return userId;
|
return userId;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setUserId(final Long userId) {
|
public void setUserId(final Long userId) {
|
||||||
this.userId = userId;
|
this.userId = userId;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Set<OrderDetail> getOrderDetail() {
|
public Set<OrderDetail> getOrderDetail() {
|
||||||
return orderDetail;
|
return orderDetail;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setOrderDetail(Set<OrderDetail> orderDetail) {
|
public void setOrderDetail(Set<OrderDetail> orderDetail) {
|
||||||
this.orderDetail = orderDetail;
|
this.orderDetail = orderDetail;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -6,67 +6,66 @@ import java.util.HashSet;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
@Table (name = "USER")
|
@Table(name = "USER")
|
||||||
public class UserLazy implements Serializable {
|
public class UserLazy implements Serializable {
|
||||||
|
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
@Id
|
@Id
|
||||||
@GeneratedValue
|
@GeneratedValue
|
||||||
@Column(name="USER_ID")
|
@Column(name = "USER_ID")
|
||||||
private Long userId;
|
private Long userId;
|
||||||
|
|
||||||
@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
|
@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
|
||||||
private Set<OrderDetail> orderDetail = new HashSet();
|
private Set<OrderDetail> orderDetail = new HashSet();
|
||||||
|
|
||||||
public UserLazy() {
|
public UserLazy() {
|
||||||
}
|
}
|
||||||
|
|
||||||
public UserLazy(final Long userId) {
|
public UserLazy(final Long userId) {
|
||||||
super();
|
super();
|
||||||
this.userId = userId;
|
this.userId = userId;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int hashCode() {
|
public int hashCode() {
|
||||||
final int prime = 31;
|
final int prime = 31;
|
||||||
int result = 1;
|
int result = 1;
|
||||||
result = prime * result + ((userId == null) ? 0 : userId.hashCode());
|
result = prime * result + ((userId == null) ? 0 : userId.hashCode());
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean equals(final Object obj) {
|
public boolean equals(final Object obj) {
|
||||||
if (this == obj)
|
if (this == obj)
|
||||||
return true;
|
return true;
|
||||||
if (obj == null)
|
if (obj == null)
|
||||||
return false;
|
return false;
|
||||||
if (getClass() != obj.getClass())
|
if (getClass() != obj.getClass())
|
||||||
return false;
|
return false;
|
||||||
final UserLazy other = (UserLazy) obj;
|
final UserLazy other = (UserLazy) obj;
|
||||||
if (userId == null) {
|
if (userId == null) {
|
||||||
if (other.userId != null)
|
if (other.userId != null)
|
||||||
return false;
|
return false;
|
||||||
} else if (!userId.equals(other.userId))
|
} else if (!userId.equals(other.userId))
|
||||||
return false;
|
return false;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Long getUserId() {
|
public Long getUserId() {
|
||||||
return userId;
|
return userId;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setUserId(final Long userId) {
|
public void setUserId(final Long userId) {
|
||||||
this.userId = userId;
|
this.userId = userId;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Set<OrderDetail> getOrderDetail() {
|
||||||
|
return orderDetail;
|
||||||
|
}
|
||||||
|
|
||||||
public Set<OrderDetail> getOrderDetail() {
|
public void setOrderDetail(Set<OrderDetail> orderDetail) {
|
||||||
return orderDetail;
|
this.orderDetail = orderDetail;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setOrderDetail(Set<OrderDetail> orderDetail) {
|
|
||||||
this.orderDetail = orderDetail;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -6,27 +6,24 @@ import org.hibernate.cfg.Configuration;
|
||||||
|
|
||||||
public class HibernateUtil {
|
public class HibernateUtil {
|
||||||
|
|
||||||
@SuppressWarnings("deprecation")
|
@SuppressWarnings("deprecation")
|
||||||
public static Session getHibernateSession(String fetchMethod) {
|
public static Session getHibernateSession(String fetchMethod) {
|
||||||
//two config files are there
|
// two config files are there
|
||||||
//one with lazy loading enabled
|
// one with lazy loading enabled
|
||||||
//another lazy = false
|
// another lazy = false
|
||||||
SessionFactory sf;
|
SessionFactory sf;
|
||||||
if ("lazy".equals(fetchMethod)) {
|
if ("lazy".equals(fetchMethod)) {
|
||||||
sf = new Configuration().configure("fetchingLazy.cfg.xml").buildSessionFactory();
|
sf = new Configuration().configure("fetchingLazy.cfg.xml").buildSessionFactory();
|
||||||
} else {
|
} else {
|
||||||
sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory();
|
sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory();
|
||||||
}
|
}
|
||||||
|
|
||||||
// fetching.cfg.xml is used for this example
|
// fetching.cfg.xml is used for this example
|
||||||
return sf.openSession();
|
return sf.openSession();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Session getHibernateSession() {
|
public static Session getHibernateSession() {
|
||||||
return new Configuration()
|
return new Configuration().configure("fetching.cfg.xml").buildSessionFactory().openSession();
|
||||||
.configure("fetching.cfg.xml")
|
|
||||||
.buildSessionFactory()
|
|
||||||
.openSession();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -16,92 +16,90 @@ import javax.persistence.NamedNativeQuery;
|
||||||
|
|
||||||
import org.hibernate.envers.Audited;
|
import org.hibernate.envers.Audited;
|
||||||
|
|
||||||
@NamedNativeQueries({
|
@NamedNativeQueries({ @NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class), @NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class) })
|
||||||
@NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class),
|
|
||||||
@NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class) })
|
|
||||||
@Entity
|
@Entity
|
||||||
@Audited
|
@Audited
|
||||||
// @Proxy(lazy = false)
|
// @Proxy(lazy = false)
|
||||||
public class Foo implements Serializable {
|
public class Foo implements Serializable {
|
||||||
|
|
||||||
@Id
|
@Id
|
||||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||||
@Column(name = "id")
|
@Column(name = "id")
|
||||||
private long id;
|
private long id;
|
||||||
|
|
||||||
@Column(name = "name")
|
@Column(name = "name")
|
||||||
private String name;
|
private String name;
|
||||||
|
|
||||||
@ManyToOne(targetEntity = Bar.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
|
@ManyToOne(targetEntity = Bar.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
|
||||||
@JoinColumn(name = "BAR_ID")
|
@JoinColumn(name = "BAR_ID")
|
||||||
private Bar bar = new Bar();
|
private Bar bar = new Bar();
|
||||||
|
|
||||||
public Foo() {
|
public Foo() {
|
||||||
super();
|
super();
|
||||||
}
|
}
|
||||||
|
|
||||||
public Foo(final String name) {
|
public Foo(final String name) {
|
||||||
super();
|
super();
|
||||||
this.name = name;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
|
|
||||||
public Bar getBar() {
|
public Bar getBar() {
|
||||||
return bar;
|
return bar;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setBar(final Bar bar) {
|
public void setBar(final Bar bar) {
|
||||||
this.bar = bar;
|
this.bar = bar;
|
||||||
}
|
}
|
||||||
|
|
||||||
public long getId() {
|
public long getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setId(final long id) {
|
public void setId(final long id) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getName() {
|
public String getName() {
|
||||||
return name;
|
return name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setName(final String name) {
|
public void setName(final String name) {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
|
||||||
//
|
//
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int hashCode() {
|
public int hashCode() {
|
||||||
final int prime = 31;
|
final int prime = 31;
|
||||||
int result = 1;
|
int result = 1;
|
||||||
result = prime * result + ((name == null) ? 0 : name.hashCode());
|
result = prime * result + ((name == null) ? 0 : name.hashCode());
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean equals(final Object obj) {
|
public boolean equals(final Object obj) {
|
||||||
if (this == obj)
|
if (this == obj)
|
||||||
return true;
|
return true;
|
||||||
if (obj == null)
|
if (obj == null)
|
||||||
return false;
|
return false;
|
||||||
if (getClass() != obj.getClass())
|
if (getClass() != obj.getClass())
|
||||||
return false;
|
return false;
|
||||||
final Foo other = (Foo) obj;
|
final Foo other = (Foo) obj;
|
||||||
if (name == null) {
|
if (name == null) {
|
||||||
if (other.name != null)
|
if (other.name != null)
|
||||||
return false;
|
return false;
|
||||||
} else if (!name.equals(other.name))
|
} else if (!name.equals(other.name))
|
||||||
return false;
|
return false;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
final StringBuilder builder = new StringBuilder();
|
final StringBuilder builder = new StringBuilder();
|
||||||
builder.append("Foo [name=").append(name).append("]");
|
builder.append("Foo [name=").append(name).append("]");
|
||||||
return builder.toString();
|
return builder.toString();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -14,178 +14,170 @@ import com.baeldung.hibernate.criteria.view.ApplicationView;
|
||||||
|
|
||||||
public class HibernateCriteriaTest {
|
public class HibernateCriteriaTest {
|
||||||
|
|
||||||
final private ApplicationView av = new ApplicationView();
|
final private ApplicationView av = new ApplicationView();
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testPerformanceOfCriteria() {
|
public void testPerformanceOfCriteria() {
|
||||||
assertTrue(av.checkIfCriteriaTimeLower());
|
assertTrue(av.checkIfCriteriaTimeLower());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testLikeCriteriaQuery() {
|
public void testLikeCriteriaQuery() {
|
||||||
final Session session = HibernateUtil.getHibernateSession();
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
final List<Item> expectedLikeList = session.createQuery("From Item where itemName like '%chair%'").list();
|
final List<Item> expectedLikeList = session.createQuery("From Item where itemName like '%chair%'").list();
|
||||||
final String expectedLikeItems[] = new String[expectedLikeList.size()];
|
final String expectedLikeItems[] = new String[expectedLikeList.size()];
|
||||||
for (int i = 0; i < expectedLikeList.size(); i++) {
|
for (int i = 0; i < expectedLikeList.size(); i++) {
|
||||||
expectedLikeItems[i] = expectedLikeList.get(i).getItemName();
|
expectedLikeItems[i] = expectedLikeList.get(i).getItemName();
|
||||||
}
|
}
|
||||||
session.close();
|
session.close();
|
||||||
assertArrayEquals(expectedLikeItems, av.likeCriteria());
|
assertArrayEquals(expectedLikeItems, av.likeCriteria());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testILikeCriteriaQuery() {
|
public void testILikeCriteriaQuery() {
|
||||||
final Session session = HibernateUtil.getHibernateSession();
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
final List<Item> expectedChairCaseList = session.createQuery("From Item where itemName like '%Chair%'").list();
|
final List<Item> expectedChairCaseList = session.createQuery("From Item where itemName like '%Chair%'").list();
|
||||||
final String expectedChairCaseItems[] = new String[expectedChairCaseList.size()];
|
final String expectedChairCaseItems[] = new String[expectedChairCaseList.size()];
|
||||||
for (int i = 0; i < expectedChairCaseList.size(); i++) {
|
for (int i = 0; i < expectedChairCaseList.size(); i++) {
|
||||||
expectedChairCaseItems[i] = expectedChairCaseList.get(i).getItemName();
|
expectedChairCaseItems[i] = expectedChairCaseList.get(i).getItemName();
|
||||||
}
|
}
|
||||||
session.close();
|
session.close();
|
||||||
assertArrayEquals(expectedChairCaseItems, av.likeCaseCriteria());
|
assertArrayEquals(expectedChairCaseItems, av.likeCaseCriteria());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testNullCriteriaQuery() {
|
public void testNullCriteriaQuery() {
|
||||||
final Session session = HibernateUtil.getHibernateSession();
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
final List<Item> expectedIsNullDescItemsList = session.createQuery("From Item where itemDescription is null")
|
final List<Item> expectedIsNullDescItemsList = session.createQuery("From Item where itemDescription is null").list();
|
||||||
.list();
|
final String expectedIsNullDescItems[] = new String[expectedIsNullDescItemsList.size()];
|
||||||
final String expectedIsNullDescItems[] = new String[expectedIsNullDescItemsList.size()];
|
for (int i = 0; i < expectedIsNullDescItemsList.size(); i++) {
|
||||||
for (int i = 0; i < expectedIsNullDescItemsList.size(); i++) {
|
expectedIsNullDescItems[i] = expectedIsNullDescItemsList.get(i).getItemName();
|
||||||
expectedIsNullDescItems[i] = expectedIsNullDescItemsList.get(i).getItemName();
|
}
|
||||||
}
|
session.close();
|
||||||
session.close();
|
assertArrayEquals(expectedIsNullDescItems, av.nullCriteria());
|
||||||
assertArrayEquals(expectedIsNullDescItems, av.nullCriteria());
|
}
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testIsNotNullCriteriaQuery() {
|
public void testIsNotNullCriteriaQuery() {
|
||||||
final Session session = HibernateUtil.getHibernateSession();
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
final List<Item> expectedIsNotNullDescItemsList = session
|
final List<Item> expectedIsNotNullDescItemsList = session.createQuery("From Item where itemDescription is not null").list();
|
||||||
.createQuery("From Item where itemDescription is not null").list();
|
final String expectedIsNotNullDescItems[] = new String[expectedIsNotNullDescItemsList.size()];
|
||||||
final String expectedIsNotNullDescItems[] = new String[expectedIsNotNullDescItemsList.size()];
|
for (int i = 0; i < expectedIsNotNullDescItemsList.size(); i++) {
|
||||||
for (int i = 0; i < expectedIsNotNullDescItemsList.size(); i++) {
|
expectedIsNotNullDescItems[i] = expectedIsNotNullDescItemsList.get(i).getItemName();
|
||||||
expectedIsNotNullDescItems[i] = expectedIsNotNullDescItemsList.get(i).getItemName();
|
}
|
||||||
}
|
session.close();
|
||||||
session.close();
|
assertArrayEquals(expectedIsNotNullDescItems, av.notNullCriteria());
|
||||||
assertArrayEquals(expectedIsNotNullDescItems, av.notNullCriteria());
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testAverageProjection() {
|
public void testAverageProjection() {
|
||||||
final Session session = HibernateUtil.getHibernateSession();
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
final List<Double> expectedAvgProjItemsList = session.createQuery("Select avg(itemPrice) from Item item")
|
final List<Double> expectedAvgProjItemsList = session.createQuery("Select avg(itemPrice) from Item item").list();
|
||||||
.list();
|
|
||||||
|
|
||||||
final Double expectedAvgProjItems[] = new Double[expectedAvgProjItemsList.size()];
|
final Double expectedAvgProjItems[] = new Double[expectedAvgProjItemsList.size()];
|
||||||
for (int i = 0; i < expectedAvgProjItemsList.size(); i++) {
|
for (int i = 0; i < expectedAvgProjItemsList.size(); i++) {
|
||||||
expectedAvgProjItems[i] = expectedAvgProjItemsList.get(i);
|
expectedAvgProjItems[i] = expectedAvgProjItemsList.get(i);
|
||||||
}
|
}
|
||||||
session.close();
|
session.close();
|
||||||
assertArrayEquals(expectedAvgProjItems, av.projectionAverage());
|
assertArrayEquals(expectedAvgProjItems, av.projectionAverage());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testRowCountProjection() {
|
public void testRowCountProjection() {
|
||||||
final Session session = HibernateUtil.getHibernateSession();
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
final List<Long> expectedCountProjItemsList = session.createQuery("Select count(*) from Item").list();
|
final List<Long> expectedCountProjItemsList = session.createQuery("Select count(*) from Item").list();
|
||||||
final Long expectedCountProjItems[] = new Long[expectedCountProjItemsList.size()];
|
final Long expectedCountProjItems[] = new Long[expectedCountProjItemsList.size()];
|
||||||
for (int i = 0; i < expectedCountProjItemsList.size(); i++) {
|
for (int i = 0; i < expectedCountProjItemsList.size(); i++) {
|
||||||
expectedCountProjItems[i] = expectedCountProjItemsList.get(i);
|
expectedCountProjItems[i] = expectedCountProjItemsList.get(i);
|
||||||
}
|
}
|
||||||
session.close();
|
session.close();
|
||||||
assertArrayEquals(expectedCountProjItems, av.projectionRowCount());
|
assertArrayEquals(expectedCountProjItems, av.projectionRowCount());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testOrCriteriaQuery() {
|
public void testOrCriteriaQuery() {
|
||||||
final Session session = HibernateUtil.getHibernateSession();
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
final List<Item> expectedOrCritItemsList = session
|
final List<Item> expectedOrCritItemsList = session.createQuery("From Item where itemPrice>1000 or itemName like 'Chair%'").list();
|
||||||
.createQuery("From Item where itemPrice>1000 or itemName like 'Chair%'").list();
|
final String expectedOrCritItems[] = new String[expectedOrCritItemsList.size()];
|
||||||
final String expectedOrCritItems[] = new String[expectedOrCritItemsList.size()];
|
for (int i = 0; i < expectedOrCritItemsList.size(); i++) {
|
||||||
for (int i = 0; i < expectedOrCritItemsList.size(); i++) {
|
expectedOrCritItems[i] = expectedOrCritItemsList.get(i).getItemName();
|
||||||
expectedOrCritItems[i] = expectedOrCritItemsList.get(i).getItemName();
|
}
|
||||||
}
|
session.close();
|
||||||
session.close();
|
assertArrayEquals(expectedOrCritItems, av.orLogicalCriteria());
|
||||||
assertArrayEquals(expectedOrCritItems, av.orLogicalCriteria());
|
}
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testAndCriteriaQuery() {
|
public void testAndCriteriaQuery() {
|
||||||
final Session session = HibernateUtil.getHibernateSession();
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
final List<Item> expectedAndCritItemsList = session
|
final List<Item> expectedAndCritItemsList = session.createQuery("From Item where itemPrice>1000 and itemName like 'Chair%'").list();
|
||||||
.createQuery("From Item where itemPrice>1000 and itemName like 'Chair%'").list();
|
final String expectedAndCritItems[] = new String[expectedAndCritItemsList.size()];
|
||||||
final String expectedAndCritItems[] = new String[expectedAndCritItemsList.size()];
|
for (int i = 0; i < expectedAndCritItemsList.size(); i++) {
|
||||||
for (int i = 0; i < expectedAndCritItemsList.size(); i++) {
|
expectedAndCritItems[i] = expectedAndCritItemsList.get(i).getItemName();
|
||||||
expectedAndCritItems[i] = expectedAndCritItemsList.get(i).getItemName();
|
}
|
||||||
}
|
session.close();
|
||||||
session.close();
|
assertArrayEquals(expectedAndCritItems, av.andLogicalCriteria());
|
||||||
assertArrayEquals(expectedAndCritItems, av.andLogicalCriteria());
|
}
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testMultiCriteriaQuery() {
|
public void testMultiCriteriaQuery() {
|
||||||
final Session session = HibernateUtil.getHibernateSession();
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
final List<Item> expectedMultiCritItemsList = session
|
final List<Item> expectedMultiCritItemsList = session.createQuery("From Item where itemDescription is null and itemName like'chair%'").list();
|
||||||
.createQuery("From Item where itemDescription is null and itemName like'chair%'").list();
|
final String expectedMultiCritItems[] = new String[expectedMultiCritItemsList.size()];
|
||||||
final String expectedMultiCritItems[] = new String[expectedMultiCritItemsList.size()];
|
for (int i = 0; i < expectedMultiCritItemsList.size(); i++) {
|
||||||
for (int i = 0; i < expectedMultiCritItemsList.size(); i++) {
|
expectedMultiCritItems[i] = expectedMultiCritItemsList.get(i).getItemName();
|
||||||
expectedMultiCritItems[i] = expectedMultiCritItemsList.get(i).getItemName();
|
}
|
||||||
}
|
session.close();
|
||||||
session.close();
|
assertArrayEquals(expectedMultiCritItems, av.twoCriteria());
|
||||||
assertArrayEquals(expectedMultiCritItems, av.twoCriteria());
|
}
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testSortCriteriaQuery() {
|
public void testSortCriteriaQuery() {
|
||||||
final Session session = HibernateUtil.getHibernateSession();
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
final List<Item> expectedSortCritItemsList = session
|
final List<Item> expectedSortCritItemsList = session.createQuery("From Item order by itemName asc, itemPrice desc").list();
|
||||||
.createQuery("From Item order by itemName asc, itemPrice desc").list();
|
final String expectedSortCritItems[] = new String[expectedSortCritItemsList.size()];
|
||||||
final String expectedSortCritItems[] = new String[expectedSortCritItemsList.size()];
|
for (int i = 0; i < expectedSortCritItemsList.size(); i++) {
|
||||||
for (int i = 0; i < expectedSortCritItemsList.size(); i++) {
|
expectedSortCritItems[i] = expectedSortCritItemsList.get(i).getItemName();
|
||||||
expectedSortCritItems[i] = expectedSortCritItemsList.get(i).getItemName();
|
}
|
||||||
}
|
session.close();
|
||||||
session.close();
|
assertArrayEquals(expectedSortCritItems, av.sortingCriteria());
|
||||||
assertArrayEquals(expectedSortCritItems, av.sortingCriteria());
|
}
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testGreaterThanCriteriaQuery() {
|
public void testGreaterThanCriteriaQuery() {
|
||||||
final Session session = HibernateUtil.getHibernateSession();
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
final List<Item> expectedGreaterThanList = session.createQuery("From Item where itemPrice>1000").list();
|
final List<Item> expectedGreaterThanList = session.createQuery("From Item where itemPrice>1000").list();
|
||||||
final String expectedGreaterThanItems[] = new String[expectedGreaterThanList.size()];
|
final String expectedGreaterThanItems[] = new String[expectedGreaterThanList.size()];
|
||||||
for (int i = 0; i < expectedGreaterThanList.size(); i++) {
|
for (int i = 0; i < expectedGreaterThanList.size(); i++) {
|
||||||
expectedGreaterThanItems[i] = expectedGreaterThanList.get(i).getItemName();
|
expectedGreaterThanItems[i] = expectedGreaterThanList.get(i).getItemName();
|
||||||
}
|
}
|
||||||
session.close();
|
session.close();
|
||||||
assertArrayEquals(expectedGreaterThanItems, av.greaterThanCriteria());
|
assertArrayEquals(expectedGreaterThanItems, av.greaterThanCriteria());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testLessThanCriteriaQuery() {
|
public void testLessThanCriteriaQuery() {
|
||||||
final Session session = HibernateUtil.getHibernateSession();
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
final List<Item> expectedLessList = session.createQuery("From Item where itemPrice<1000").list();
|
final List<Item> expectedLessList = session.createQuery("From Item where itemPrice<1000").list();
|
||||||
final String expectedLessThanItems[] = new String[expectedLessList.size()];
|
final String expectedLessThanItems[] = new String[expectedLessList.size()];
|
||||||
for (int i = 0; i < expectedLessList.size(); i++) {
|
for (int i = 0; i < expectedLessList.size(); i++) {
|
||||||
expectedLessThanItems[i] = expectedLessList.get(i).getItemName();
|
expectedLessThanItems[i] = expectedLessList.get(i).getItemName();
|
||||||
}
|
}
|
||||||
session.close();
|
session.close();
|
||||||
assertArrayEquals(expectedLessThanItems, av.lessThanCriteria());
|
assertArrayEquals(expectedLessThanItems, av.lessThanCriteria());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void betweenCriteriaQuery() {
|
public void betweenCriteriaQuery() {
|
||||||
final Session session = HibernateUtil.getHibernateSession();
|
final Session session = HibernateUtil.getHibernateSession();
|
||||||
final List<Item> expectedBetweenList = session.createQuery("From Item where itemPrice between 100 and 200")
|
final List<Item> expectedBetweenList = session.createQuery("From Item where itemPrice between 100 and 200").list();
|
||||||
.list();
|
final String expectedPriceBetweenItems[] = new String[expectedBetweenList.size()];
|
||||||
final String expectedPriceBetweenItems[] = new String[expectedBetweenList.size()];
|
for (int i = 0; i < expectedBetweenList.size(); i++) {
|
||||||
for (int i = 0; i < expectedBetweenList.size(); i++) {
|
expectedPriceBetweenItems[i] = expectedBetweenList.get(i).getItemName();
|
||||||
expectedPriceBetweenItems[i] = expectedBetweenList.get(i).getItemName();
|
}
|
||||||
}
|
session.close();
|
||||||
session.close();
|
assertArrayEquals(expectedPriceBetweenItems, av.betweenCriteria());
|
||||||
assertArrayEquals(expectedPriceBetweenItems, av.betweenCriteria());
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -6,10 +6,10 @@ import org.junit.runner.notification.Failure;
|
||||||
|
|
||||||
public class HibernateCriteriaTestRunner {
|
public class HibernateCriteriaTestRunner {
|
||||||
|
|
||||||
public static void main(final String[] args) {
|
public static void main(final String[] args) {
|
||||||
Result result = JUnitCore.runClasses(HibernateCriteriaTestSuite.class);
|
Result result = JUnitCore.runClasses(HibernateCriteriaTestSuite.class);
|
||||||
for (Failure failure : result.getFailures()) {
|
for (Failure failure : result.getFailures()) {
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -13,31 +13,30 @@ import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
public class HibernateFetchingTest {
|
public class HibernateFetchingTest {
|
||||||
|
|
||||||
|
// this loads sample data in the database
|
||||||
|
@Before
|
||||||
|
public void addFecthingTestData() {
|
||||||
|
FetchingAppView fav = new FetchingAppView();
|
||||||
|
fav.createTestData();
|
||||||
|
}
|
||||||
|
|
||||||
//this loads sample data in the database
|
// testLazyFetching() tests the lazy loading
|
||||||
@Before
|
// Since it lazily loaded so orderDetalSetLazy won't
|
||||||
public void addFecthingTestData(){
|
// be initialized
|
||||||
FetchingAppView fav = new FetchingAppView();
|
@Test
|
||||||
fav.createTestData();
|
public void testLazyFetching() {
|
||||||
}
|
FetchingAppView fav = new FetchingAppView();
|
||||||
|
Set<OrderDetail> orderDetalSetLazy = fav.lazyLoaded();
|
||||||
|
assertFalse(Hibernate.isInitialized(orderDetalSetLazy));
|
||||||
|
}
|
||||||
|
|
||||||
//testLazyFetching() tests the lazy loading
|
// testEagerFetching() tests the eager loading
|
||||||
//Since it lazily loaded so orderDetalSetLazy won't
|
// Since it eagerly loaded so orderDetalSetLazy would
|
||||||
//be initialized
|
// be initialized
|
||||||
@Test
|
@Test
|
||||||
public void testLazyFetching() {
|
public void testEagerFetching() {
|
||||||
FetchingAppView fav = new FetchingAppView();
|
FetchingAppView fav = new FetchingAppView();
|
||||||
Set<OrderDetail> orderDetalSetLazy = fav.lazyLoaded();
|
Set<OrderDetail> orderDetalSetEager = fav.eagerLoaded();
|
||||||
assertFalse(Hibernate.isInitialized(orderDetalSetLazy));
|
assertTrue(Hibernate.isInitialized(orderDetalSetEager));
|
||||||
}
|
}
|
||||||
|
|
||||||
//testEagerFetching() tests the eager loading
|
|
||||||
//Since it eagerly loaded so orderDetalSetLazy would
|
|
||||||
//be initialized
|
|
||||||
@Test
|
|
||||||
public void testEagerFetching() {
|
|
||||||
FetchingAppView fav = new FetchingAppView();
|
|
||||||
Set<OrderDetail> orderDetalSetEager = fav.eagerLoaded();
|
|
||||||
assertTrue(Hibernate.isInitialized(orderDetalSetEager));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,6 +1,5 @@
|
||||||
package com.baeldung.persistence.save;
|
package com.baeldung.persistence.save;
|
||||||
|
|
||||||
|
|
||||||
import com.baeldung.persistence.model.Person;
|
import com.baeldung.persistence.model.Person;
|
||||||
import org.hibernate.HibernateException;
|
import org.hibernate.HibernateException;
|
||||||
import org.hibernate.Session;
|
import org.hibernate.Session;
|
||||||
|
@ -25,16 +24,9 @@ public class SaveMethodsTest {
|
||||||
|
|
||||||
@BeforeClass
|
@BeforeClass
|
||||||
public static void beforeTests() {
|
public static void beforeTests() {
|
||||||
Configuration configuration = new Configuration()
|
Configuration configuration = new Configuration().addAnnotatedClass(Person.class).setProperty("hibernate.dialect", HSQLDialect.class.getName()).setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName())
|
||||||
.addAnnotatedClass(Person.class)
|
.setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test").setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "").setProperty("hibernate.hbm2ddl.auto", "update");
|
||||||
.setProperty("hibernate.dialect", HSQLDialect.class.getName())
|
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
|
||||||
.setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName())
|
|
||||||
.setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test")
|
|
||||||
.setProperty("hibernate.connection.username", "sa")
|
|
||||||
.setProperty("hibernate.connection.password", "")
|
|
||||||
.setProperty("hibernate.hbm2ddl.auto", "update");
|
|
||||||
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
|
|
||||||
configuration.getProperties()).build();
|
|
||||||
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
|
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -44,7 +36,6 @@ public class SaveMethodsTest {
|
||||||
session.beginTransaction();
|
session.beginTransaction();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenPersistTransient_thenSavedToDatabaseOnCommit() {
|
public void whenPersistTransient_thenSavedToDatabaseOnCommit() {
|
||||||
|
|
||||||
|
@ -244,7 +235,6 @@ public class SaveMethodsTest {
|
||||||
|
|
||||||
assertNotNull(session.get(Person.class, person.getId()));
|
assertNotNull(session.get(Person.class, person.getId()));
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|
|
@ -25,7 +25,7 @@ import com.baeldung.persistence.model.Foo;
|
||||||
import com.baeldung.spring.PersistenceConfig;
|
import com.baeldung.spring.PersistenceConfig;
|
||||||
|
|
||||||
@RunWith(SpringJUnit4ClassRunner.class)
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
@ContextConfiguration(classes = {PersistenceConfig.class}, loader = AnnotationConfigContextLoader.class)
|
@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||||
public class FooStoredProceduresIntegrationTest {
|
public class FooStoredProceduresIntegrationTest {
|
||||||
|
|
||||||
private static final Logger LOGGER = LoggerFactory.getLogger(FooStoredProceduresIntegrationTest.class);
|
private static final Logger LOGGER = LoggerFactory.getLogger(FooStoredProceduresIntegrationTest.class);
|
||||||
|
@ -47,8 +47,7 @@ public class FooStoredProceduresIntegrationTest {
|
||||||
|
|
||||||
private boolean getFoosByNameExists() {
|
private boolean getFoosByNameExists() {
|
||||||
try {
|
try {
|
||||||
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()")
|
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class);
|
||||||
.addEntity(Foo.class);
|
|
||||||
sqlQuery.list();
|
sqlQuery.list();
|
||||||
return true;
|
return true;
|
||||||
} catch (SQLGrammarException e) {
|
} catch (SQLGrammarException e) {
|
||||||
|
@ -59,8 +58,7 @@ public class FooStoredProceduresIntegrationTest {
|
||||||
|
|
||||||
private boolean getAllFoosExists() {
|
private boolean getAllFoosExists() {
|
||||||
try {
|
try {
|
||||||
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()")
|
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class);
|
||||||
.addEntity(Foo.class);
|
|
||||||
sqlQuery.list();
|
sqlQuery.list();
|
||||||
return true;
|
return true;
|
||||||
} catch (SQLGrammarException e) {
|
} catch (SQLGrammarException e) {
|
||||||
|
@ -80,8 +78,7 @@ public class FooStoredProceduresIntegrationTest {
|
||||||
fooService.create(new Foo(randomAlphabetic(6)));
|
fooService.create(new Foo(randomAlphabetic(6)));
|
||||||
|
|
||||||
// Stored procedure getAllFoos using createSQLQuery
|
// Stored procedure getAllFoos using createSQLQuery
|
||||||
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(
|
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class);
|
||||||
Foo.class);
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
List<Foo> allFoos = sqlQuery.list();
|
List<Foo> allFoos = sqlQuery.list();
|
||||||
for (Foo foo : allFoos) {
|
for (Foo foo : allFoos) {
|
||||||
|
@ -105,8 +102,7 @@ public class FooStoredProceduresIntegrationTest {
|
||||||
fooService.create(new Foo("NewFooName"));
|
fooService.create(new Foo("NewFooName"));
|
||||||
|
|
||||||
// Stored procedure getFoosByName using createSQLQuery()
|
// Stored procedure getFoosByName using createSQLQuery()
|
||||||
Query sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)")
|
Query sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)").addEntity(Foo.class).setParameter("fooName", "NewFooName");
|
||||||
.addEntity(Foo.class).setParameter("fooName", "NewFooName");
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
List<Foo> allFoosByName = sqlQuery.list();
|
List<Foo> allFoosByName = sqlQuery.list();
|
||||||
for (Foo foo : allFoosByName) {
|
for (Foo foo : allFoosByName) {
|
||||||
|
@ -114,8 +110,7 @@ public class FooStoredProceduresIntegrationTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Stored procedure getFoosByName using getNamedQuery()
|
// Stored procedure getFoosByName using getNamedQuery()
|
||||||
Query namedQuery = session.getNamedQuery("callGetFoosByName")
|
Query namedQuery = session.getNamedQuery("callGetFoosByName").setParameter("fooName", "NewFooName");
|
||||||
.setParameter("fooName", "NewFooName");
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
List<Foo> allFoosByName2 = namedQuery.list();
|
List<Foo> allFoosByName2 = namedQuery.list();
|
||||||
for (Foo foo : allFoosByName2) {
|
for (Foo foo : allFoosByName2) {
|
||||||
|
|
|
@ -12,8 +12,7 @@ public class DefaultTextMessageSenderTest {
|
||||||
@SuppressWarnings("resource")
|
@SuppressWarnings("resource")
|
||||||
@BeforeClass
|
@BeforeClass
|
||||||
public static void setUp() {
|
public static void setUp() {
|
||||||
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
|
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml");
|
||||||
"classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml");
|
|
||||||
messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender");
|
messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -12,8 +12,7 @@ public class MapMessageConvertAndSendTest {
|
||||||
@SuppressWarnings("resource")
|
@SuppressWarnings("resource")
|
||||||
@BeforeClass
|
@BeforeClass
|
||||||
public static void setUp() {
|
public static void setUp() {
|
||||||
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
|
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml");
|
||||||
"classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml");
|
|
||||||
messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender");
|
messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -43,8 +43,7 @@ public class SecondLevelCacheIntegrationTest {
|
||||||
final Foo foo = new Foo(randomAlphabetic(6));
|
final Foo foo = new Foo(randomAlphabetic(6));
|
||||||
fooService.create(foo);
|
fooService.create(foo);
|
||||||
fooService.findOne(foo.getId());
|
fooService.findOne(foo.getId());
|
||||||
final int size = CacheManager.ALL_CACHE_MANAGERS.get(0)
|
final int size = CacheManager.ALL_CACHE_MANAGERS.get(0).getCache("org.baeldung.persistence.model.Foo").getSize();
|
||||||
.getCache("org.baeldung.persistence.model.Foo").getSize();
|
|
||||||
assertThat(size, greaterThan(0));
|
assertThat(size, greaterThan(0));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -64,21 +63,17 @@ public class SecondLevelCacheIntegrationTest {
|
||||||
return nativeQuery.executeUpdate();
|
return nativeQuery.executeUpdate();
|
||||||
});
|
});
|
||||||
|
|
||||||
final int size = CacheManager.ALL_CACHE_MANAGERS.get(0)
|
final int size = CacheManager.ALL_CACHE_MANAGERS.get(0).getCache("org.baeldung.persistence.model.Foo").getSize();
|
||||||
.getCache("org.baeldung.persistence.model.Foo").getSize();
|
|
||||||
assertThat(size, greaterThan(0));
|
assertThat(size, greaterThan(0));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenCacheableQueryIsExecuted_thenItIsCached() {
|
public final void givenCacheableQueryIsExecuted_thenItIsCached() {
|
||||||
new TransactionTemplate(platformTransactionManager).execute(status -> {
|
new TransactionTemplate(platformTransactionManager).execute(status -> {
|
||||||
return entityManager.createQuery("select f from Foo f")
|
return entityManager.createQuery("select f from Foo f").setHint("org.hibernate.cacheable", true).getResultList();
|
||||||
.setHint("org.hibernate.cacheable", true)
|
|
||||||
.getResultList();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
final int size = CacheManager.ALL_CACHE_MANAGERS.get(0)
|
final int size = CacheManager.ALL_CACHE_MANAGERS.get(0).getCache("org.hibernate.cache.internal.StandardQueryCache").getSize();
|
||||||
.getCache("org.hibernate.cache.internal.StandardQueryCache").getSize();
|
|
||||||
assertThat(size, greaterThan(0));
|
assertThat(size, greaterThan(0));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -30,7 +30,7 @@ public class User {
|
||||||
private String email;
|
private String email;
|
||||||
|
|
||||||
@ManyToMany(fetch = FetchType.EAGER)
|
@ManyToMany(fetch = FetchType.EAGER)
|
||||||
@JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") )
|
@JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"))
|
||||||
@JsonApiToMany
|
@JsonApiToMany
|
||||||
@JsonApiIncludeByDefault
|
@JsonApiIncludeByDefault
|
||||||
private Set<Role> roles;
|
private Set<Role> roles;
|
||||||
|
|
|
@ -5,7 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
public class MocksApplication {
|
public class MocksApplication {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
SpringApplication.run(MocksApplication.class, args);
|
SpringApplication.run(MocksApplication.class, args);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -17,13 +17,12 @@ public class MainController {
|
||||||
@Autowired
|
@Autowired
|
||||||
private ITutorialsService tutService;
|
private ITutorialsService tutService;
|
||||||
|
|
||||||
@RequestMapping(value ="/", method = RequestMethod.GET)
|
@RequestMapping(value = "/", method = RequestMethod.GET)
|
||||||
public String welcomePage() {
|
public String welcomePage() {
|
||||||
return "index";
|
return "index";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@RequestMapping(value = "/list", method = RequestMethod.GET)
|
||||||
@RequestMapping(value ="/list", method = RequestMethod.GET)
|
|
||||||
public String listTutorialsPage(Model model) {
|
public String listTutorialsPage(Model model) {
|
||||||
List<Tutorial> list = tutService.listTutorials();
|
List<Tutorial> list = tutService.listTutorials();
|
||||||
model.addAttribute("tutorials", list);
|
model.addAttribute("tutorials", list);
|
||||||
|
@ -38,5 +37,4 @@ public class MainController {
|
||||||
this.tutService = tutService;
|
this.tutService = tutService;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
|
@ -6,5 +6,5 @@ import java.util.List;
|
||||||
|
|
||||||
public interface ITutorialsService {
|
public interface ITutorialsService {
|
||||||
|
|
||||||
List<Tutorial> listTutorials();
|
List<Tutorial> listTutorials();
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,9 +10,6 @@ import java.util.List;
|
||||||
public class TutorialsService implements ITutorialsService {
|
public class TutorialsService implements ITutorialsService {
|
||||||
|
|
||||||
public List<Tutorial> listTutorials() {
|
public List<Tutorial> listTutorials() {
|
||||||
return Arrays.asList(
|
return Arrays.asList(new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"), new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor"));
|
||||||
new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"),
|
|
||||||
new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor")
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -13,7 +13,7 @@ import org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver;
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
@EnableWebMvc
|
@EnableWebMvc
|
||||||
@ComponentScan(basePackages = { "com.baeldung.mvc.velocity.controller", "com.baeldung.mvc.velocity.service"})
|
@ComponentScan(basePackages = { "com.baeldung.mvc.velocity.controller", "com.baeldung.mvc.velocity.service" })
|
||||||
public class WebConfig extends WebMvcConfigurerAdapter {
|
public class WebConfig extends WebMvcConfigurerAdapter {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|
|
@ -39,7 +39,6 @@ public class DataContentControllerTest {
|
||||||
@Before
|
@Before
|
||||||
public void setUp() {
|
public void setUp() {
|
||||||
|
|
||||||
|
|
||||||
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
|
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -55,7 +54,7 @@ public class DataContentControllerTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCallingIndex_thenViewOK() throws Exception{
|
public void whenCallingIndex_thenViewOK() throws Exception {
|
||||||
mockMvc.perform(get("/")).andExpect(status().isOk()).andExpect(view().name("index")).andExpect(model().size(0));
|
mockMvc.perform(get("/")).andExpect(status().isOk()).andExpect(view().name("index")).andExpect(model().size(0));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -9,7 +9,6 @@ import org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver;
|
||||||
@Configuration
|
@Configuration
|
||||||
public class TestConfig {
|
public class TestConfig {
|
||||||
|
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public ViewResolver viewResolver() {
|
public ViewResolver viewResolver() {
|
||||||
final VelocityLayoutViewResolver bean = new VelocityLayoutViewResolver();
|
final VelocityLayoutViewResolver bean = new VelocityLayoutViewResolver();
|
||||||
|
@ -27,6 +26,4 @@ public class TestConfig {
|
||||||
return velocityConfigurer;
|
return velocityConfigurer;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -8,10 +8,10 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
|
||||||
@Configuration
|
@Configuration
|
||||||
public class ClientWebConfig extends WebMvcConfigurerAdapter {
|
public class ClientWebConfig extends WebMvcConfigurerAdapter {
|
||||||
|
|
||||||
public ClientWebConfig() {
|
public ClientWebConfig() {
|
||||||
super();
|
super();
|
||||||
}
|
}
|
||||||
|
|
||||||
// API
|
// API
|
||||||
|
|
||||||
}
|
}
|
|
@ -17,40 +17,40 @@ import org.springframework.web.servlet.view.JstlView;
|
||||||
//@Configuration
|
//@Configuration
|
||||||
public class ClientWebConfigJava extends WebMvcConfigurerAdapter {
|
public class ClientWebConfigJava extends WebMvcConfigurerAdapter {
|
||||||
|
|
||||||
public ClientWebConfigJava() {
|
public ClientWebConfigJava() {
|
||||||
super();
|
super();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public MessageSource messageSource() {
|
public MessageSource messageSource() {
|
||||||
|
|
||||||
final ResourceBundleMessageSource ms = new ResourceBundleMessageSource();
|
final ResourceBundleMessageSource ms = new ResourceBundleMessageSource();
|
||||||
ms.setBasenames("messages");
|
ms.setBasenames("messages");
|
||||||
return ms;
|
return ms;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public ResourceBundle getBeanResourceBundle() {
|
public ResourceBundle getBeanResourceBundle() {
|
||||||
|
|
||||||
final Locale locale = Locale.getDefault();
|
final Locale locale = Locale.getDefault();
|
||||||
return new MessageSourceResourceBundle(messageSource(), locale);
|
return new MessageSourceResourceBundle(messageSource(), locale);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void addViewControllers(final ViewControllerRegistry registry) {
|
public void addViewControllers(final ViewControllerRegistry registry) {
|
||||||
super.addViewControllers(registry);
|
super.addViewControllers(registry);
|
||||||
|
|
||||||
registry.addViewController("/sample.html");
|
registry.addViewController("/sample.html");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public ViewResolver viewResolver() {
|
public ViewResolver viewResolver() {
|
||||||
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
|
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
|
||||||
|
|
||||||
bean.setViewClass(JstlView.class);
|
bean.setViewClass(JstlView.class);
|
||||||
bean.setPrefix("/WEB-INF/view/");
|
bean.setPrefix("/WEB-INF/view/");
|
||||||
bean.setSuffix(".jsp");
|
bean.setSuffix(".jsp");
|
||||||
|
|
||||||
return bean;
|
return bean;
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -18,28 +18,28 @@ import com.baeldung.spring.form.Employee;
|
||||||
@Controller
|
@Controller
|
||||||
public class EmployeeController {
|
public class EmployeeController {
|
||||||
|
|
||||||
Map<Long, Employee> employeeMap = new HashMap<>();
|
Map<Long, Employee> employeeMap = new HashMap<>();
|
||||||
|
|
||||||
@RequestMapping(value = "/employee", method = RequestMethod.GET)
|
@RequestMapping(value = "/employee", method = RequestMethod.GET)
|
||||||
public ModelAndView showForm() {
|
public ModelAndView showForm() {
|
||||||
return new ModelAndView("employeeHome", "employee", new Employee());
|
return new ModelAndView("employeeHome", "employee", new Employee());
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET)
|
@RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET)
|
||||||
public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) {
|
public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) {
|
||||||
return employeeMap.get(Id);
|
return employeeMap.get(Id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
|
@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
|
||||||
public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) {
|
public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) {
|
||||||
if (result.hasErrors()) {
|
if (result.hasErrors()) {
|
||||||
return "error";
|
return "error";
|
||||||
}
|
}
|
||||||
model.addAttribute("name", employee.getName());
|
model.addAttribute("name", employee.getName());
|
||||||
model.addAttribute("contactNumber", employee.getContactNumber());
|
model.addAttribute("contactNumber", employee.getContactNumber());
|
||||||
model.addAttribute("id", employee.getId());
|
model.addAttribute("id", employee.getId());
|
||||||
employeeMap.put(employee.getId(), employee);
|
employeeMap.put(employee.getId(), employee);
|
||||||
return "employeeView";
|
return "employeeView";
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -11,8 +11,7 @@ public class HelloController extends AbstractController {
|
||||||
@Override
|
@Override
|
||||||
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
|
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||||
ModelAndView model = new ModelAndView("helloworld");
|
ModelAndView model = new ModelAndView("helloworld");
|
||||||
model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.<br>This request was mapped" +
|
model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.<br>This request was mapped" + " using SimpleUrlHandlerMapping.");
|
||||||
" using SimpleUrlHandlerMapping.");
|
|
||||||
|
|
||||||
return model;
|
return model;
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,8 +10,7 @@ public class HelloGuestController extends AbstractController {
|
||||||
@Override
|
@Override
|
||||||
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
|
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||||
ModelAndView model = new ModelAndView("helloworld");
|
ModelAndView model = new ModelAndView("helloworld");
|
||||||
model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.<br>This request was mapped" +
|
model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.<br>This request was mapped" + " using ControllerClassNameHandlerMapping.");
|
||||||
" using ControllerClassNameHandlerMapping.");
|
|
||||||
|
|
||||||
return model;
|
return model;
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,8 +10,7 @@ public class HelloWorldController extends AbstractController {
|
||||||
@Override
|
@Override
|
||||||
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
|
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||||
ModelAndView model = new ModelAndView("helloworld");
|
ModelAndView model = new ModelAndView("helloworld");
|
||||||
model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.<br>This request was mapped" +
|
model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.<br>This request was mapped" + " using BeanNameUrlHandlerMapping.");
|
||||||
" using BeanNameUrlHandlerMapping.");
|
|
||||||
|
|
||||||
return model;
|
return model;
|
||||||
}
|
}
|
||||||
|
|
|
@ -22,63 +22,62 @@ import org.springframework.web.servlet.ModelAndView;
|
||||||
@Controller
|
@Controller
|
||||||
public class PersonController {
|
public class PersonController {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
PersonValidator validator;
|
PersonValidator validator;
|
||||||
|
|
||||||
@RequestMapping(value = "/person", method = RequestMethod.GET)
|
@RequestMapping(value = "/person", method = RequestMethod.GET)
|
||||||
public ModelAndView showForm(final Model model) {
|
public ModelAndView showForm(final Model model) {
|
||||||
|
|
||||||
initData(model);
|
initData(model);
|
||||||
return new ModelAndView("personForm", "person", new Person());
|
return new ModelAndView("personForm", "person", new Person());
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(value = "/addPerson", method = RequestMethod.POST)
|
@RequestMapping(value = "/addPerson", method = RequestMethod.POST)
|
||||||
public String submit(@Valid @ModelAttribute("person") final Person person, final BindingResult result,
|
public String submit(@Valid @ModelAttribute("person") final Person person, final BindingResult result, final ModelMap modelMap, final Model model) {
|
||||||
final ModelMap modelMap, final Model model) {
|
|
||||||
|
|
||||||
validator.validate(person, result);
|
validator.validate(person, result);
|
||||||
|
|
||||||
if (result.hasErrors()) {
|
if (result.hasErrors()) {
|
||||||
|
|
||||||
initData(model);
|
initData(model);
|
||||||
return "personForm";
|
return "personForm";
|
||||||
}
|
}
|
||||||
|
|
||||||
modelMap.addAttribute("person", person);
|
modelMap.addAttribute("person", person);
|
||||||
|
|
||||||
return "personView";
|
return "personView";
|
||||||
}
|
}
|
||||||
|
|
||||||
private void initData(final Model model) {
|
private void initData(final Model model) {
|
||||||
|
|
||||||
final List<String> favouriteLanguageItem = new ArrayList<String>();
|
final List<String> favouriteLanguageItem = new ArrayList<String>();
|
||||||
favouriteLanguageItem.add("Java");
|
favouriteLanguageItem.add("Java");
|
||||||
favouriteLanguageItem.add("C++");
|
favouriteLanguageItem.add("C++");
|
||||||
favouriteLanguageItem.add("Perl");
|
favouriteLanguageItem.add("Perl");
|
||||||
model.addAttribute("favouriteLanguageItem", favouriteLanguageItem);
|
model.addAttribute("favouriteLanguageItem", favouriteLanguageItem);
|
||||||
|
|
||||||
final List<String> jobItem = new ArrayList<String>();
|
final List<String> jobItem = new ArrayList<String>();
|
||||||
jobItem.add("Full time");
|
jobItem.add("Full time");
|
||||||
jobItem.add("Part time");
|
jobItem.add("Part time");
|
||||||
model.addAttribute("jobItem", jobItem);
|
model.addAttribute("jobItem", jobItem);
|
||||||
|
|
||||||
final Map<String, String> countryItems = new LinkedHashMap<String, String>();
|
final Map<String, String> countryItems = new LinkedHashMap<String, String>();
|
||||||
countryItems.put("US", "United Stated");
|
countryItems.put("US", "United Stated");
|
||||||
countryItems.put("IT", "Italy");
|
countryItems.put("IT", "Italy");
|
||||||
countryItems.put("UK", "United Kingdom");
|
countryItems.put("UK", "United Kingdom");
|
||||||
countryItems.put("FR", "Grance");
|
countryItems.put("FR", "Grance");
|
||||||
model.addAttribute("countryItems", countryItems);
|
model.addAttribute("countryItems", countryItems);
|
||||||
|
|
||||||
final List<String> fruit = new ArrayList<String>();
|
final List<String> fruit = new ArrayList<String>();
|
||||||
fruit.add("Banana");
|
fruit.add("Banana");
|
||||||
fruit.add("Mango");
|
fruit.add("Mango");
|
||||||
fruit.add("Apple");
|
fruit.add("Apple");
|
||||||
model.addAttribute("fruit", fruit);
|
model.addAttribute("fruit", fruit);
|
||||||
|
|
||||||
final List<String> books = new ArrayList<String>();
|
final List<String> books = new ArrayList<String>();
|
||||||
books.add("The Great Gatsby");
|
books.add("The Great Gatsby");
|
||||||
books.add("Nineteen Eighty-Four");
|
books.add("Nineteen Eighty-Four");
|
||||||
books.add("The Lord of the Rings");
|
books.add("The Lord of the Rings");
|
||||||
model.addAttribute("books", books);
|
model.addAttribute("books", books);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue