formatting work

This commit is contained in:
eugenp 2016-10-12 08:02:05 +03:00
parent eb7650eead
commit 856be0a08a
128 changed files with 2039 additions and 2275 deletions

View File

@ -29,5 +29,4 @@ public class SpringExtension extends AbstractExtensionId<SpringExtension.SpringE
}
}

View File

@ -27,9 +27,7 @@ public class SpringAkkaTest extends AbstractJUnit4SpringContextTests {
@Test
public void whenCallingGreetingActor_thenActorGreetsTheCaller() throws Exception {
ActorRef greeter = system.actorOf(
SPRING_EXTENSION_PROVIDER.get(system)
.props("greetingActor"), "greeter");
ActorRef greeter = system.actorOf(SPRING_EXTENSION_PROVIDER.get(system).props("greetingActor"), "greeter");
FiniteDuration duration = FiniteDuration.create(1, TimeUnit.SECONDS);
Timeout timeout = Timeout.durationToTimeout(duration);

View File

@ -12,20 +12,20 @@ import org.springframework.web.servlet.DispatcherServlet;
public class StudentControllerConfig implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext sc) throws ServletException {
AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
root.register(WebConfig.class);
@Override
public void onStartup(ServletContext sc) throws ServletException {
AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
root.register(WebConfig.class);
root.setServletContext(sc);
root.setServletContext(sc);
// Manages the lifecycle of the root application context
sc.addListener(new ContextLoaderListener(root));
// Manages the lifecycle of the root application context
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);
appServlet.setLoadOnStartup(1);
appServlet.addMapping("/test/*");
}
ServletRegistration.Dynamic appServlet = sc.addServlet("test-mvc", dv);
appServlet.setLoadOnStartup(1);
appServlet.addMapping("/test/*");
}
}

View File

@ -11,7 +11,7 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@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 {
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {

View File

@ -7,15 +7,15 @@ import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class RestController{
public class RestController {
@GetMapping(value="/student/{studentId}")
public @ResponseBody Student getTestData(@PathVariable Integer studentId) {
Student student = new Student();
student.setName("Peter");
student.setId(studentId);
@GetMapping(value = "/student/{studentId}")
public @ResponseBody Student getTestData(@PathVariable Integer studentId) {
Student student = new Student();
student.setName("Peter");
student.setId(studentId);
return student;
return student;
}
}
}

View File

@ -1,33 +1,33 @@
package org.baeldung.controller.student;
public class Student {
private String name;
private String name;
private int id;
private int id;
public String getName() {
return name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setId(int id) {
this.id = id;
}
@Override
public int hashCode(){
return this.id;
}
@Override
public int hashCode() {
return this.id;
}
@Override
public boolean equals(Object obj){
return this.name.equals(((Student)obj).getName());
}
@Override
public boolean equals(Object obj) {
return this.name.equals(((Student) obj).getName());
}
}

View File

@ -11,7 +11,6 @@ public class PropertiesWithPlaceHolderConfigurer {
super();
}
@Bean
public PropertyPlaceholderConfigurer propertyConfigurer() {
final PropertyPlaceholderConfigurer props = new PropertyPlaceholderConfigurer();

View File

@ -2,14 +2,14 @@ package org.baeldung.scopes;
public class HelloMessageGenerator {
private String message;
private String message;
public String getMessage() {
return message;
}
public String getMessage() {
return message;
}
public void setMessage(final String message) {
this.message = message;
}
public void setMessage(final String message) {
this.message = message;
}
}

View File

@ -1,27 +1,27 @@
package org.baeldung.scopes;
public class Person {
private String name;
private int age;
private String name;
private int age;
public Person() {
}
public Person() {
}
public Person(final String name, final int age) {
this.name = name;
}
public Person(final String name, final int age) {
this.name = name;
}
public String getName() {
return name;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public void setName(final String name) {
this.name = name;
}
@Override
public String toString() {
return "Person [name=" + name + "]";
}
@Override
public String toString() {
return "Person [name=" + name + "]";
}
}

View File

@ -9,23 +9,23 @@ import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ScopesController {
public static final Logger LOG = Logger.getLogger(ScopesController.class);
public static final Logger LOG = Logger.getLogger(ScopesController.class);
@Resource(name = "requestMessage")
HelloMessageGenerator requestMessage;
@Resource(name = "requestMessage")
HelloMessageGenerator requestMessage;
@Resource(name = "sessionMessage")
HelloMessageGenerator sessionMessage;
@Resource(name = "sessionMessage")
HelloMessageGenerator sessionMessage;
@RequestMapping("/scopes")
public String getScopes(final Model model) {
LOG.info("Request Message:" + requestMessage.getMessage());
LOG.info("Session Message" + sessionMessage.getMessage());
requestMessage.setMessage("Good morning!");
sessionMessage.setMessage("Good afternoon!");
model.addAttribute("requestMessage", requestMessage.getMessage());
model.addAttribute("sessionMessage", sessionMessage.getMessage());
return "scopesExample";
}
@RequestMapping("/scopes")
public String getScopes(final Model model) {
LOG.info("Request Message:" + requestMessage.getMessage());
LOG.info("Session Message" + sessionMessage.getMessage());
requestMessage.setMessage("Good morning!");
sessionMessage.setMessage("Good afternoon!");
model.addAttribute("requestMessage", requestMessage.getMessage());
model.addAttribute("sessionMessage", sessionMessage.getMessage());
return "scopesExample";
}
}

View File

@ -16,42 +16,42 @@ import org.springframework.web.servlet.view.UrlBasedViewResolver;
@ComponentScan("org.baeldung.scopes")
@EnableWebMvc
public class ScopesConfig {
@Bean
public UrlBasedViewResolver setupViewResolver() {
final UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
@Bean
public UrlBasedViewResolver setupViewResolver() {
final UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
@Bean
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public HelloMessageGenerator requestMessage() {
return new HelloMessageGenerator();
}
@Bean
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public HelloMessageGenerator requestMessage() {
return new HelloMessageGenerator();
}
@Bean
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public HelloMessageGenerator sessionMessage() {
return new HelloMessageGenerator();
}
@Bean
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public HelloMessageGenerator sessionMessage() {
return new HelloMessageGenerator();
}
@Bean
@Scope(value = WebApplicationContext.SCOPE_GLOBAL_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public HelloMessageGenerator globalSessionMessage() {
return new HelloMessageGenerator();
}
@Bean
@Scope(value = WebApplicationContext.SCOPE_GLOBAL_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public HelloMessageGenerator globalSessionMessage() {
return new HelloMessageGenerator();
}
@Bean
@Scope("prototype")
public Person personPrototype() {
return new Person();
}
@Bean
@Scope("prototype")
public Person personPrototype() {
return new Person();
}
@Bean
@Scope("singleton")
public Person personSingleton() {
return new Person();
}
@Bean
@Scope("singleton")
public Person personSingleton() {
return new Person();
}
}

View File

@ -11,7 +11,6 @@ public class Foo {
private static final AtomicInteger instanceCount = new AtomicInteger(0);
private final int instanceNum;
public Foo() {

View File

@ -18,13 +18,12 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.ModelAndView;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes={WebConfig.class}, loader=AnnotationConfigWebContextLoader.class )
@ContextConfiguration(classes = { WebConfig.class }, loader = AnnotationConfigWebContextLoader.class)
public class ControllerAnnotationTest {
private MockMvc mockMvc;
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
@ -43,9 +42,7 @@ public class ControllerAnnotationTest {
@Test
public void testTestController() throws Exception {
ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/"))
.andReturn()
.getModelAndView();
ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/")).andReturn().getModelAndView();
// validate modal data
Assert.assertSame(mv.getModelMap().get("data").toString(), "Welcome home man");
@ -57,9 +54,7 @@ public class ControllerAnnotationTest {
@Test
public void testRestController() throws Exception {
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1))
.andReturn().getResponse()
.getContentAsString();
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1)).andReturn().getResponse().getContentAsString();
ObjectMapper reader = new ObjectMapper();
@ -72,9 +67,7 @@ public class ControllerAnnotationTest {
@Test
public void testRestAnnotatedController() throws Exception {
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1))
.andReturn().getResponse()
.getContentAsString();
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1)).andReturn().getResponse().getContentAsString();
ObjectMapper reader = new ObjectMapper();

View File

@ -19,7 +19,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration({"classpath:test-mvc.xml"})
@ContextConfiguration({ "classpath:test-mvc.xml" })
public class ControllerTest {
private MockMvc mockMvc;
@ -41,9 +41,7 @@ public class ControllerTest {
@Test
public void testTestController() throws Exception {
ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/"))
.andReturn()
.getModelAndView();
ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/")).andReturn().getModelAndView();
// validate modal data
Assert.assertSame(mv.getModelMap().get("data").toString(), "Welcome home man");
@ -55,9 +53,7 @@ public class ControllerTest {
@Test
public void testRestController() throws Exception {
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1))
.andReturn().getResponse()
.getContentAsString();
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/{studentId}", 1)).andReturn().getResponse().getContentAsString();
ObjectMapper reader = new ObjectMapper();
@ -70,9 +66,7 @@ public class ControllerTest {
@Test
public void testRestAnnotatedController() throws Exception {
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1))
.andReturn().getResponse()
.getContentAsString();
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/annotated/student/{studentId}", 1)).andReturn().getResponse().getContentAsString();
ObjectMapper reader = new ObjectMapper();

View File

@ -8,36 +8,36 @@ import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ScopesTest {
private static final String NAME = "John Smith";
private static final String NAME_OTHER = "Anna Jones";
private static final String NAME = "John Smith";
private static final String NAME_OTHER = "Anna Jones";
@Test
public void testScopeSingleton() {
final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml");
@Test
public void testScopeSingleton() {
final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml");
final Person personSingletonA = (Person) applicationContext.getBean("personSingleton");
final Person personSingletonB = (Person) applicationContext.getBean("personSingleton");
final Person personSingletonA = (Person) applicationContext.getBean("personSingleton");
final Person personSingletonB = (Person) applicationContext.getBean("personSingleton");
personSingletonA.setName(NAME);
Assert.assertEquals(NAME, personSingletonB.getName());
personSingletonA.setName(NAME);
Assert.assertEquals(NAME, personSingletonB.getName());
((AbstractApplicationContext) applicationContext).close();
}
((AbstractApplicationContext) applicationContext).close();
}
@Test
public void testScopePrototype() {
final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml");
@Test
public void testScopePrototype() {
final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml");
final Person personPrototypeA = (Person) applicationContext.getBean("personPrototype");
final Person personPrototypeB = (Person) applicationContext.getBean("personPrototype");
final Person personPrototypeA = (Person) applicationContext.getBean("personPrototype");
final Person personPrototypeB = (Person) applicationContext.getBean("personPrototype");
personPrototypeA.setName(NAME);
personPrototypeB.setName(NAME_OTHER);
personPrototypeA.setName(NAME);
personPrototypeB.setName(NAME_OTHER);
Assert.assertEquals(NAME, personPrototypeA.getName());
Assert.assertEquals(NAME_OTHER, personPrototypeB.getName());
Assert.assertEquals(NAME, personPrototypeA.getName());
Assert.assertEquals(NAME_OTHER, personPrototypeB.getName());
((AbstractApplicationContext) applicationContext).close();
}
((AbstractApplicationContext) applicationContext).close();
}
}

View File

@ -26,18 +26,12 @@ public class AttributeAnnotationTest extends AbstractJUnit4SpringContextTests {
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac)
.build();
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void whenInterceptorAddsRequestAndSessionParams_thenParamsInjectedWithAttributesAnnotations() throws Exception {
String result = this.mockMvc.perform(get("/test")
.accept(MediaType.ALL))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString();
String result = this.mockMvc.perform(get("/test").accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
Assert.assertEquals("login = john, query = invoices", result);
}

View File

@ -29,15 +29,12 @@ public class ComposedMappingTest extends AbstractJUnit4SpringContextTests {
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac)
.build();
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void whenRequestingMethodWithGetMapping_thenReceiving200Answer() throws Exception {
this.mockMvc.perform(get("/appointments")
.accept(MediaType.ALL))
.andExpect(status().isOk());
this.mockMvc.perform(get("/appointments").accept(MediaType.ALL)).andExpect(status().isOk());
verify(appointmentService);
}

View File

@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import static org.junit.Assert.assertNotNull;
@ContextConfiguration(classes = {FooRepositoryConfiguration.class, FooServiceConfiguration.class})
@ContextConfiguration(classes = { FooRepositoryConfiguration.class, FooServiceConfiguration.class })
public class ConfigurationConstructorInjectionTest extends AbstractJUnit4SpringContextTests {
@Autowired

View File

@ -1,6 +1,5 @@
package org.baeldung.spring43.defaultmethods;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;

View File

@ -28,27 +28,16 @@ public class ScopeAnnotationsTest extends AbstractJUnit4SpringContextTests {
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac)
.build();
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void whenDifferentRequests_thenDifferentInstancesOfRequestScopedBeans() throws Exception {
MockHttpSession session = new MockHttpSession();
String requestScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/request")
.session(session)
.accept(MediaType.ALL)).andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString();
String requestScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/request").session(session).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
String requestScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/request")
.session(session)
.accept(MediaType.ALL)).andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString();
String requestScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/request").session(session).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
assertNotEquals(requestScopedServiceInstanceNumber1, requestScopedServiceInstanceNumber2);
}
@ -59,24 +48,9 @@ public class ScopeAnnotationsTest extends AbstractJUnit4SpringContextTests {
MockHttpSession session1 = new MockHttpSession();
MockHttpSession session2 = new MockHttpSession();
String sessionScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/session")
.session(session1)
.accept(MediaType.ALL)).andExpect(status().isOk())
.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();
String sessionScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/session").session(session1).accept(MediaType.ALL)).andExpect(status().isOk()).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);
@ -90,18 +64,8 @@ public class ScopeAnnotationsTest extends AbstractJUnit4SpringContextTests {
MockHttpSession session1 = new MockHttpSession();
MockHttpSession session2 = new MockHttpSession();
String applicationScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/application")
.session(session1)
.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();
String applicationScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/application").session(session1).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);

View File

@ -3,9 +3,9 @@ package com.baeldung.autowire.sample;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
FooService fooService = ctx.getBean(FooService.class);
fooService.doStuff();
}
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
FooService fooService = ctx.getBean(FooService.class);
fooService.doStuff();
}
}

View File

@ -10,7 +10,7 @@ public class FooService {
@FormatterType("Foo")
private Formatter formatter;
public String doStuff(){
public String doStuff() {
return formatter.format();
}

View File

@ -2,6 +2,6 @@ package com.baeldung.autowire.sample;
public interface Formatter {
String format();
String format();
}

View File

@ -8,7 +8,7 @@ import java.lang.annotation.Target;
import org.springframework.beans.factory.annotation.Qualifier;
@Qualifier
@Target({ElementType.FIELD, ElementType.METHOD,ElementType.TYPE, ElementType.PARAMETER})
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
public @interface FormatterType {

View File

@ -9,14 +9,14 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=AppConfig.class, loader=AnnotationConfigContextLoader.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
public class FooServiceTest {
@Autowired
FooService fooService;
@Test
public void whenFooFormatterType_thenReturnFoo(){
public void whenFooFormatterType_thenReturnFoo() {
Assert.assertEquals("foo", fooService.doStuff());
}
}

View File

@ -7,9 +7,9 @@ import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class TestController {
@RequestMapping(value="/")
public String welcome(Model model){
return "index";
}
@RequestMapping(value = "/")
public String welcome(Model model) {
return "index";
}
}

View File

@ -6,7 +6,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WebjarsdemoApplication {
public static void main(String[] args) {
SpringApplication.run(WebjarsdemoApplication.class, args);
}
public static void main(String[] args) {
SpringApplication.run(WebjarsdemoApplication.class, args);
}
}

View File

@ -6,7 +6,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
@SpringBootApplication(scanBasePackages = { "com.baeldung.git"})
@SpringBootApplication(scanBasePackages = { "com.baeldung.git" })
public class CommitIdApplication {
public static void main(String[] args) {
SpringApplication.run(CommitIdApplication.class, args);
@ -21,6 +21,3 @@ public class CommitIdApplication {
return c;
}
}

View File

@ -22,7 +22,7 @@ public class CommitInfoController {
@RequestMapping("/commitId")
public Map<String, String> getCommitId() {
Map<String, String> result = new HashMap<>();
result.put("Commit message",commitMessage);
result.put("Commit message", commitMessage);
result.put("Commit branch", branch);
result.put("Commit id", commitId);
return result;

View File

@ -11,8 +11,8 @@ import org.springframework.test.context.web.WebAppConfiguration;
@WebAppConfiguration
public class WebjarsdemoApplicationTests {
@Test
public void contextLoads() {
}
@Test
public void contextLoads() {
}
}

View File

@ -32,13 +32,10 @@ public class CommitIdTest {
LOG.info(commitMessage);
LOG.info(branch);
assertThat(commitMessage)
.isNotEqualTo("UNKNOWN");
assertThat(commitMessage).isNotEqualTo("UNKNOWN");
assertThat(branch)
.isNotEqualTo("UNKNOWN");
assertThat(branch).isNotEqualTo("UNKNOWN");
assertThat(commitId)
.isNotEqualTo("UNKNOWN");
assertThat(commitId).isNotEqualTo("UNKNOWN");
}
}

View File

@ -31,22 +31,15 @@ public class SpringBootApplicationTest {
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void setupMockMvc() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.build();
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void givenRequestHasBeenMade_whenMeetsAllOfGivenConditions_thenCorrect() throws Exception {
MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(),
Charset.forName("utf8"));
MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")).
andExpect(MockMvcResultMatchers.status().isOk()).
andExpect(MockMvcResultMatchers.content().contentType(contentType)).
andExpect(jsonPath("$", hasSize(4)));
mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)).andExpect(jsonPath("$", hasSize(4)));
}
}

View File

@ -69,7 +69,6 @@ public class SpringBootMailTest {
return wiserMessage.getMimeMessage().getSubject();
}
private SimpleMailMessage composeEmailMessage() {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setTo(userTo);

View File

@ -30,8 +30,7 @@ public class DetailsServiceClientTest {
@Before
public void setUp() throws Exception {
String detailsString = objectMapper.writeValueAsString(new Details("John Smith", "john"));
this.server.expect(requestTo("/john/details"))
.andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON));
this.server.expect(requestTo("/john/details")).andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON));
}
@Test

View File

@ -20,7 +20,7 @@ public class SpringDemoApplication extends SpringBootServletInitializer {
}
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}

View File

@ -23,18 +23,23 @@ public class Campus {
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Point getLocation() {
return location;
}
public void setLocation(Point location) {
this.location = location;
}
@ -42,13 +47,13 @@ public class Campus {
@Override
public int hashCode() {
int hash = 1;
if(id != null) {
if (id != null) {
hash = hash * 31 + id.hashCode();
}
if(name != null) {
if (name != null) {
hash = hash * 31 + name.hashCode();
}
if(location != null) {
if (location != null) {
hash = hash * 31 + location.hashCode();
}
return hash;
@ -56,14 +61,17 @@ public class Campus {
@Override
public boolean equals(Object obj) {
if((obj == null) || (obj.getClass() != this.getClass())) return false;
if(obj == this) return true;
if ((obj == null) || (obj.getClass() != this.getClass()))
return false;
if (obj == this)
return true;
Campus other = (Campus) obj;
return this.hashCode() == other.hashCode();
}
@SuppressWarnings("unused")
private Campus() {}
private Campus() {
}
public Campus(Builder b) {
this.id = b.id;

View File

@ -34,30 +34,39 @@ public class Person {
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public DateTime getCreated() {
return created;
}
public void setCreated(DateTime created) {
this.created = created;
}
public DateTime getUpdated() {
return updated;
}
public void setUpdated(DateTime updated) {
this.updated = updated;
}
@ -65,13 +74,13 @@ public class Person {
@Override
public int hashCode() {
int hash = 1;
if(id != null) {
if (id != null) {
hash = hash * 31 + id.hashCode();
}
if(firstName != null) {
if (firstName != null) {
hash = hash * 31 + firstName.hashCode();
}
if(lastName != null) {
if (lastName != null) {
hash = hash * 31 + lastName.hashCode();
}
return hash;
@ -79,8 +88,10 @@ public class Person {
@Override
public boolean equals(Object obj) {
if((obj == null) || (obj.getClass() != this.getClass())) return false;
if(obj == this) return true;
if ((obj == null) || (obj.getClass() != this.getClass()))
return false;
if (obj == this)
return true;
Person other = (Person) obj;
return this.hashCode() == other.hashCode();
}

View File

@ -20,13 +20,13 @@ public class Student {
private String id;
@Field
@NotNull
@Size(min=1, max=20)
@Pattern(regexp=NAME_REGEX)
@Size(min = 1, max = 20)
@Pattern(regexp = NAME_REGEX)
private String firstName;
@Field
@NotNull
@Size(min=1, max=20)
@Pattern(regexp=NAME_REGEX)
@Size(min = 1, max = 20)
@Pattern(regexp = NAME_REGEX)
private String lastName;
@Field
@Past
@ -39,7 +39,8 @@ public class Student {
@Version
private long version;
public Student() {}
public Student() {
}
public Student(String id, String firstName, String lastName, DateTime dateOfBirth) {
this.id = id;
@ -51,36 +52,47 @@ public class Student {
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public DateTime getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(DateTime dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public DateTime getCreated() {
return created;
}
public void setCreated(DateTime created) {
this.created = created;
}
public DateTime getUpdated() {
return updated;
}
public void setUpdated(DateTime updated) {
this.updated = updated;
}
@ -88,16 +100,16 @@ public class Student {
@Override
public int hashCode() {
int hash = 1;
if(id != null) {
if (id != null) {
hash = hash * 31 + id.hashCode();
}
if(firstName != null) {
if (firstName != null) {
hash = hash * 31 + firstName.hashCode();
}
if(lastName != null) {
if (lastName != null) {
hash = hash * 31 + lastName.hashCode();
}
if(dateOfBirth != null) {
if (dateOfBirth != null) {
hash = hash * 31 + dateOfBirth.hashCode();
}
return hash;
@ -105,8 +117,10 @@ public class Student {
@Override
public boolean equals(Object obj) {
if((obj == null) || (obj.getClass() != this.getClass())) return false;
if(obj == this) return true;
if ((obj == null) || (obj.getClass() != this.getClass()))
return false;
if (obj == this)
return true;
Student other = (Student) obj;
return this.hashCode() == other.hashCode();
}

View File

@ -17,9 +17,6 @@ public class CustomStudentRepositoryImpl implements CustomStudentRepository {
private CouchbaseTemplate template;
public List<Student> findByFirstNameStartsWith(String s) {
return template.findByView(ViewQuery.from(DESIGN_DOC, "byFirstName")
.startKey(s)
.stale(Stale.FALSE),
Student.class);
return template.findByView(ViewQuery.from(DESIGN_DOC, "byFirstName").startKey(s).stale(Stale.FALSE), Student.class);
}
}

View File

@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository;
public interface PersonRepository extends CrudRepository<Person, String> {
List<Person> findByFirstName(String firstName);
List<Person> findByLastName(String lastName);
}

View File

@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository;
public interface StudentRepository extends CrudRepository<Student, String>, CustomStudentRepository {
List<Student> findByFirstName(String firstName);
List<Student> findByLastName(String lastName);
}

View File

@ -16,6 +16,7 @@ import org.springframework.stereotype.Service;
public class PersonRepositoryService implements PersonService {
private PersonRepository repo;
@Autowired
public void setPersonRepository(PersonRepository repo) {
this.repo = repo;
@ -28,7 +29,7 @@ public class PersonRepositoryService implements PersonService {
public List<Person> findAll() {
List<Person> people = new ArrayList<Person>();
Iterator<Person> it = repo.findAll().iterator();
while(it.hasNext()) {
while (it.hasNext()) {
people.add(it.next());
}
return people;

View File

@ -18,13 +18,14 @@ public class PersonTemplateService implements PersonService {
private static final String DESIGN_DOC = "person";
private CouchbaseTemplate template;
@Autowired
public void setCouchbaseTemplate(CouchbaseTemplate template) {
this.template = template;
}
public Person findOne(String id) {
return template.findById(id, Person.class);
public Person findOne(String id) {
return template.findById(id, Person.class);
}
public List<Person> findAll() {

View File

@ -16,6 +16,7 @@ import org.springframework.stereotype.Service;
public class StudentRepositoryService implements StudentService {
private StudentRepository repo;
@Autowired
public void setStudentRepository(StudentRepository repo) {
this.repo = repo;
@ -28,7 +29,7 @@ public class StudentRepositoryService implements StudentService {
public List<Student> findAll() {
List<Student> people = new ArrayList<Student>();
Iterator<Student> it = repo.findAll().iterator();
while(it.hasNext()) {
while (it.hasNext()) {
people.add(it.next());
}
return people;

View File

@ -18,13 +18,14 @@ public class StudentTemplateService implements StudentService {
private static final String DESIGN_DOC = "student";
private CouchbaseTemplate template;
@Autowired
public void setCouchbaseTemplate(CouchbaseTemplate template) {
this.template = template;
}
public Student findOne(String id) {
return template.findById(id, Student.class);
public Student findOne(String id) {
return template.findById(id, Student.class);
}
public List<Student> findAll() {

View File

@ -11,9 +11,9 @@ import org.springframework.data.repository.CrudRepository;
public interface CampusRepository extends CrudRepository<Campus, String> {
@View(designDocument="campus", viewName="byName")
@View(designDocument = "campus", viewName = "byName")
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);
}

View File

@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository;
public interface PersonRepository extends CrudRepository<Person, String> {
List<Person> findByFirstName(String firstName);
List<Person> findByLastName(String lastName);
}

View File

@ -7,5 +7,6 @@ import org.springframework.data.repository.CrudRepository;
public interface StudentRepository extends CrudRepository<Student, String> {
List<Student> findByFirstName(String firstName);
List<Student> findByLastName(String lastName);
}

View File

@ -15,6 +15,7 @@ import org.springframework.stereotype.Service;
public class CampusServiceImpl implements CampusService {
private CampusRepository repo;
@Autowired
public void setCampusRepository(CampusRepository repo) {
this.repo = repo;
@ -39,7 +40,7 @@ public class CampusServiceImpl implements CampusService {
public Set<Campus> findAll() {
Set<Campus> campuses = new HashSet<>();
Iterator<Campus> it = repo.findAll().iterator();
while(it.hasNext()) {
while (it.hasNext()) {
campuses.add(it.next());
}
return campuses;

View File

@ -14,6 +14,7 @@ import org.springframework.stereotype.Service;
public class PersonServiceImpl implements PersonService {
private PersonRepository repo;
@Autowired
public void setPersonRepository(PersonRepository repo) {
this.repo = repo;
@ -26,7 +27,7 @@ public class PersonServiceImpl implements PersonService {
public List<Person> findAll() {
List<Person> people = new ArrayList<Person>();
Iterator<Person> it = repo.findAll().iterator();
while(it.hasNext()) {
while (it.hasNext()) {
people.add(it.next());
}
return people;

View File

@ -14,6 +14,7 @@ import org.springframework.stereotype.Service;
public class StudentServiceImpl implements StudentService {
private StudentRepository repo;
@Autowired
public void setStudentRepository(StudentRepository repo) {
this.repo = repo;
@ -26,7 +27,7 @@ public class StudentServiceImpl implements StudentService {
public List<Student> findAll() {
List<Student> people = new ArrayList<Student>();
Iterator<Student> it = repo.findAll().iterator();
while(it.hasNext()) {
while (it.hasNext()) {
people.add(it.next());
}
return people;

View File

@ -12,7 +12,7 @@ import org.springframework.data.couchbase.repository.config.EnableCouchbaseRepos
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
@Configuration
@EnableCouchbaseRepositories(basePackages={"org.baeldung.spring.data.couchbase"})
@EnableCouchbaseRepositories(basePackages = { "org.baeldung.spring.data.couchbase" })
public class MyCouchbaseConfig extends AbstractCouchbaseConfiguration {
public static final List<String> NODE_LIST = Arrays.asList("localhost");

View File

@ -30,24 +30,14 @@ public abstract class StudentServiceTest extends IntegrationTest {
static final String joeCollegeId = "student:" + joe + ":" + college;
static final DateTime joeCollegeDob = DateTime.now().minusYears(21);
static final Student joeCollege = new Student(joeCollegeId, joe, college, joeCollegeDob);
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);
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);
static final String judy = "Judy";
static final String jetson = "Jetson";
static final String judyJetsonId = "student:" + judy + ":" + jetson;
static final DateTime judyJetsonDob = DateTime.now().minusYears(19).minusMonths(5).minusDays(3);
static final Student judyJetson = new Student(judyJetsonId, judy, jetson, judyJetsonDob);
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);
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);
StudentService studentService;
@ -75,7 +65,7 @@ public abstract class StudentServiceTest extends IntegrationTest {
assertEquals(expectedStudent.getId(), actualStudent.getId());
}
@Test(expected=ConstraintViolationException.class)
@Test(expected = ConstraintViolationException.class)
public void whenCreatingStudentWithInvalidFirstName_thenConstraintViolationException() {
String firstName = "Er+ic";
String lastName = "Stratton";
@ -85,7 +75,7 @@ public abstract class StudentServiceTest extends IntegrationTest {
studentService.create(student);
}
@Test(expected=ConstraintViolationException.class)
@Test(expected = ConstraintViolationException.class)
public void whenCreatingStudentWithFutureDob_thenConstraintViolationException() {
String firstName = "Jane";
String lastName = "Doe";
@ -133,8 +123,8 @@ public abstract class StudentServiceTest extends IntegrationTest {
private boolean resultContains(List<Student> resultList, Student student) {
boolean found = false;
for(Student p : resultList) {
if(p.getId().equals(student.getId())) {
for (Student p : resultList) {
if (p.getId().equals(student.getId())) {
found = true;
break;
}
@ -144,8 +134,8 @@ public abstract class StudentServiceTest extends IntegrationTest {
private boolean allResultsContainExpectedFirstName(List<Student> resultList, String firstName) {
boolean found = false;
for(Student p : resultList) {
if(p.getFirstName().equals(firstName)) {
for (Student p : resultList) {
if (p.getFirstName().equals(firstName)) {
found = true;
break;
}
@ -155,8 +145,8 @@ public abstract class StudentServiceTest extends IntegrationTest {
private boolean allResultsContainExpectedLastName(List<Student> resultList, String lastName) {
boolean found = false;
for(Student p : resultList) {
if(p.getLastName().equals(lastName)) {
for (Student p : resultList) {
if (p.getLastName().equals(lastName)) {
found = true;
break;
}

View File

@ -46,11 +46,7 @@ public class MultiBucketCouchbaseConfig extends AbstractCouchbaseConfiguration {
@Bean(name = "campusTemplate")
public CouchbaseTemplate campusTemplate() throws Exception {
CouchbaseTemplate template = new CouchbaseTemplate(
couchbaseClusterInfo(),
campusBucket(),
mappingCouchbaseConverter(),
translationService());
CouchbaseTemplate template = new CouchbaseTemplate(couchbaseClusterInfo(), campusBucket(), mappingCouchbaseConverter(), translationService());
template.setDefaultConsistency(getDefaultConsistency());
return template;
}
@ -60,7 +56,7 @@ public class MultiBucketCouchbaseConfig extends AbstractCouchbaseConfiguration {
try {
baseMapping.mapEntity(Campus.class, campusTemplate());
} catch (Exception e) {
//custom Exception handling
// custom Exception handling
}
}

View File

@ -26,53 +26,21 @@ public class CampusServiceImplTest extends MultiBucketIntegationTest {
@Autowired
private CampusRepository campusRepo;
private final Campus Brown = Campus.Builder.newInstance()
.id("campus:Brown")
.name("Brown")
.location(new Point(71.4025, 51.8268))
.build();
private final Campus Brown = Campus.Builder.newInstance().id("campus:Brown").name("Brown").location(new Point(71.4025, 51.8268)).build();
private final Campus Cornell = Campus.Builder.newInstance()
.id("campus:Cornell")
.name("Cornell")
.location(new Point(76.4833, 42.4459))
.build();
private final Campus Cornell = Campus.Builder.newInstance().id("campus:Cornell").name("Cornell").location(new Point(76.4833, 42.4459)).build();
private final Campus Columbia = Campus.Builder.newInstance()
.id("campus:Columbia")
.name("Columbia")
.location(new Point(73.9626, 40.8075))
.build();
private final Campus Columbia = Campus.Builder.newInstance().id("campus:Columbia").name("Columbia").location(new Point(73.9626, 40.8075)).build();
private final Campus Dartmouth = Campus.Builder.newInstance()
.id("campus:Dartmouth")
.name("Dartmouth")
.location(new Point(72.2887, 43.7044))
.build();
private final Campus Dartmouth = Campus.Builder.newInstance().id("campus:Dartmouth").name("Dartmouth").location(new Point(72.2887, 43.7044)).build();
private final Campus Harvard = Campus.Builder.newInstance()
.id("campus:Harvard")
.name("Harvard")
.location(new Point(71.1167, 42.3770))
.build();
private final Campus Harvard = Campus.Builder.newInstance().id("campus:Harvard").name("Harvard").location(new Point(71.1167, 42.3770)).build();
private final Campus Penn = Campus.Builder.newInstance()
.id("campus:Penn")
.name("Penn")
.location(new Point(75.1932, 39.9522))
.build();
private final Campus Penn = Campus.Builder.newInstance().id("campus:Penn").name("Penn").location(new Point(75.1932, 39.9522)).build();
private final Campus Princeton = Campus.Builder.newInstance()
.id("campus:Princeton")
.name("Princeton")
.location(new Point(74.6514, 40.3340))
.build();
private final Campus Princeton = Campus.Builder.newInstance().id("campus:Princeton").name("Princeton").location(new Point(74.6514, 40.3340)).build();
private final Campus Yale = Campus.Builder.newInstance()
.id("campus:Yale")
.name("Yale")
.location(new Point(72.9223, 41.3163))
.build();
private final Campus Yale = Campus.Builder.newInstance().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 NewYorkCity = new Point(74.0059, 40.7128);

View File

@ -31,24 +31,14 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest {
static final String joeCollegeId = "student:" + joe + ":" + college;
static final DateTime joeCollegeDob = DateTime.now().minusYears(21);
static final Student joeCollege = new Student(joeCollegeId, joe, college, joeCollegeDob);
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);
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);
static final String judy = "Judy";
static final String jetson = "Jetson";
static final String judyJetsonId = "student:" + judy + ":" + jetson;
static final DateTime judyJetsonDob = DateTime.now().minusYears(19).minusMonths(5).minusDays(3);
static final Student judyJetson = new Student(judyJetsonId, judy, jetson, judyJetsonDob);
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);
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);
@Autowired
StudentServiceImpl studentService;
@ -77,7 +67,7 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest {
assertEquals(expectedStudent.getId(), actualStudent.getId());
}
@Test(expected=ConstraintViolationException.class)
@Test(expected = ConstraintViolationException.class)
public void whenCreatingStudentWithInvalidFirstName_thenConstraintViolationException() {
String firstName = "Er+ic";
String lastName = "Stratton";
@ -87,7 +77,7 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest {
studentService.create(student);
}
@Test(expected=ConstraintViolationException.class)
@Test(expected = ConstraintViolationException.class)
public void whenCreatingStudentWithFutureDob_thenConstraintViolationException() {
String firstName = "Jane";
String lastName = "Doe";
@ -135,8 +125,8 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest {
private boolean resultContains(List<Student> resultList, Student student) {
boolean found = false;
for(Student p : resultList) {
if(p.getId().equals(student.getId())) {
for (Student p : resultList) {
if (p.getId().equals(student.getId())) {
found = true;
break;
}
@ -146,8 +136,8 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest {
private boolean allResultsContainExpectedFirstName(List<Student> resultList, String firstName) {
boolean found = false;
for(Student p : resultList) {
if(p.getFirstName().equals(firstName)) {
for (Student p : resultList) {
if (p.getFirstName().equals(firstName)) {
found = true;
break;
}
@ -157,8 +147,8 @@ public class StudentServiceImplTest extends MultiBucketIntegationTest {
private boolean allResultsContainExpectedLastName(List<Student> resultList, String lastName) {
boolean found = false;
for(Student p : resultList) {
if(p.getLastName().equals(lastName)) {
for (Student p : resultList) {
if (p.getLastName().equals(lastName)) {
found = true;
break;
}

View File

@ -43,8 +43,7 @@ public class ElasticSearchUnitTests {
@Test
public void givenJsonString_whenJavaObject_thenIndexDocument() {
String jsonObject = "{\"age\":20,\"dateOfBirth\":1471466076564,\"fullName\":\"John Doe\"}";
IndexResponse response = client.prepareIndex("people", "Doe")
.setSource(jsonObject).get();
IndexResponse response = client.prepareIndex("people", "Doe").setSource(jsonObject).get();
String index = response.getIndex();
String type = response.getType();
assertTrue(response.isCreated());
@ -55,8 +54,7 @@ public class ElasticSearchUnitTests {
@Test
public void givenDocumentId_whenJavaObject_thenDeleteDocument() {
String jsonObject = "{\"age\":10,\"dateOfBirth\":1471455886564,\"fullName\":\"Johan Doe\"}";
IndexResponse response = client.prepareIndex("people", "Doe")
.setSource(jsonObject).get();
IndexResponse response = client.prepareIndex("people", "Doe").setSource(jsonObject).get();
String id = response.getId();
DeleteResponse deleteResponse = client.prepareDelete("people", "Doe", id).get();
assertTrue(deleteResponse.isFound());
@ -77,29 +75,11 @@ public class ElasticSearchUnitTests {
@Test
public void givenSearchParamters_thenReturnResults() {
boolean isExecutedSuccessfully = true;
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();
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();
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();
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();
SearchResponse response3 = client.prepareSearch()
.setTypes()
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setPostFilter(QueryBuilders.matchQuery("John", "Name*"))
.setFrom(0).setSize(60).setExplain(true)
.execute()
.actionGet();
SearchResponse response3 = client.prepareSearch().setTypes().setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setPostFilter(QueryBuilders.matchQuery("John", "Name*")).setFrom(0).setSize(60).setExplain(true).execute().actionGet();
try {
response2.getHits();
response3.getHits();
@ -114,14 +94,8 @@ public class ElasticSearchUnitTests {
@Test
public void givenContentBuilder_whenHelpers_thanIndexJson() throws IOException {
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
.field("fullName", "Test")
.field("salary", "11500")
.field("age", "10")
.endObject();
IndexResponse response = client.prepareIndex("people", "Doe")
.setSource(builder).get();
XContentBuilder builder = XContentFactory.jsonBuilder().startObject().field("fullName", "Test").field("salary", "11500").field("age", "10").endObject();
IndexResponse response = client.prepareIndex("people", "Doe").setSource(builder).get();
assertTrue(response.isCreated());
}
}

View File

@ -9,8 +9,7 @@ import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@ComponentScan(basePackages = {"com.baeldung.spring.data.neo4j.services"})
@ComponentScan(basePackages = { "com.baeldung.spring.data.neo4j.services" })
@Configuration
@EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repostory")
public class MovieDatabaseNeo4jConfiguration extends Neo4jConfiguration {
@ -20,10 +19,7 @@ public class MovieDatabaseNeo4jConfiguration extends Neo4jConfiguration {
@Bean
public org.neo4j.ogm.config.Configuration getConfiguration() {
org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration();
config
.driverConfiguration()
.setDriverClassName("org.neo4j.ogm.drivers.http.driver.HttpDriver")
.setURI(URL);
config.driverConfiguration().setDriverClassName("org.neo4j.ogm.drivers.http.driver.HttpDriver").setURI(URL);
return config;
}

View File

@ -10,20 +10,17 @@ import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
import org.springframework.data.neo4j.server.Neo4jServer;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement
@ComponentScan(basePackages = {"com.baeldung.spring.data.neo4j.services"})
@ComponentScan(basePackages = { "com.baeldung.spring.data.neo4j.services" })
@Configuration
@EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repostory")
@Profile({"embedded", "test"})
@Profile({ "embedded", "test" })
public class MovieDatabaseNeo4jTestConfiguration extends Neo4jConfiguration {
@Bean
public org.neo4j.ogm.config.Configuration getConfiguration() {
org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration();
config
.driverConfiguration()
.setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver");
config.driverConfiguration().setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver");
return config;
}

View File

@ -9,7 +9,7 @@ import org.neo4j.ogm.annotation.Relationship;
import java.util.Collection;
import java.util.List;
@JsonIdentityInfo(generator=JSOGGenerator.class)
@JsonIdentityInfo(generator = JSOGGenerator.class)
@NodeEntity
public class Movie {
@ -21,9 +21,11 @@ public class Movie {
private int released;
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() {
return title;
@ -57,5 +59,4 @@ public class Movie {
this.roles = roles;
}
}

View File

@ -1,6 +1,5 @@
package com.baeldung.spring.data.neo4j.domain;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.voodoodyne.jackson.jsog.JSOGGenerator;
import org.neo4j.ogm.annotation.GraphId;
@ -9,7 +8,7 @@ import org.neo4j.ogm.annotation.Relationship;
import java.util.List;
@JsonIdentityInfo(generator=JSOGGenerator.class)
@JsonIdentityInfo(generator = JSOGGenerator.class)
@NodeEntity
public class Person {
@GraphId
@ -21,7 +20,8 @@ public class Person {
@Relationship(type = "ACTED_IN")
private List<Movie> movies;
public Person() { }
public Person() {
}
public String getName() {
return name;

View File

@ -1,6 +1,5 @@
package com.baeldung.spring.data.neo4j.domain;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.voodoodyne.jackson.jsog.JSOGGenerator;
import org.neo4j.ogm.annotation.EndNode;
@ -10,7 +9,7 @@ import org.neo4j.ogm.annotation.StartNode;
import java.util.Collection;
@JsonIdentityInfo(generator=JSOGGenerator.class)
@JsonIdentityInfo(generator = JSOGGenerator.class)
@RelationshipEntity(type = "ACTED_IN")
public class Role {
@GraphId

View File

@ -18,7 +18,5 @@ public interface MovieRepository extends GraphRepository<Movie> {
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}")
List<Map<String,Object>> graph(@Param("limit") int limit);
List<Map<String, Object>> graph(@Param("limit") int limit);
}

View File

@ -4,7 +4,6 @@ import com.baeldung.spring.data.neo4j.domain.Person;
import org.springframework.data.neo4j.repository.GraphRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PersonRepository extends GraphRepository<Person> {

View File

@ -15,31 +15,31 @@ public class MovieService {
MovieRepository movieRepository;
private Map<String, Object> toD3Format(Iterator<Map<String, Object>> result) {
List<Map<String,Object>> nodes = new ArrayList<Map<String,Object>>();
List<Map<String,Object>> rels= new ArrayList<Map<String,Object>>();
int i=0;
List<Map<String, Object>> nodes = new ArrayList<Map<String, Object>>();
List<Map<String, Object>> rels = new ArrayList<Map<String, Object>>();
int i = 0;
while (result.hasNext()) {
Map<String, Object> row = result.next();
nodes.add(map("title",row.get("movie"),"label","movie"));
int target=i;
nodes.add(map("title", row.get("movie"), "label", "movie"));
int target = i;
i++;
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);
if (source == -1) {
nodes.add(actor);
source = i++;
}
rels.add(map("source",source,"target",target));
rels.add(map("source", source, "target", target));
}
}
return map("nodes", nodes, "links", rels);
}
private Map<String, Object> map(String key1, Object value1, String key2, Object value2) {
Map<String, Object> result = new HashMap<String,Object>(2);
result.put(key1,value1);
result.put(key2,value2);
Map<String, Object> result = new HashMap<String, Object>(2);
result.put(key1, value1);
result.put(key2, value2);
return result;
}

View File

@ -82,8 +82,7 @@ public class MovieRepositoryTest {
@DirtiesContext
public void testFindAll() {
System.out.println("findAll");
Collection<Movie> result =
(Collection<Movie>) movieRepository.findAll();
Collection<Movie> result = (Collection<Movie>) movieRepository.findAll();
assertNotNull(result);
assertEquals(1, result.size());
}
@ -93,8 +92,7 @@ public class MovieRepositoryTest {
public void testFindByTitleContaining() {
System.out.println("findByTitleContaining");
String title = "Italian";
Collection<Movie> result =
movieRepository.findByTitleContaining(title);
Collection<Movie> result = movieRepository.findByTitleContaining(title);
assertNotNull(result);
assertEquals(1, result.size());
}
@ -126,8 +124,7 @@ public class MovieRepositoryTest {
public void testDeleteAll() {
System.out.println("deleteAll");
movieRepository.deleteAll();
Collection<Movie> result =
(Collection<Movie>) movieRepository.findAll();
Collection<Movie> result = (Collection<Movie>) movieRepository.findAll();
assertEquals(0, result.size());
}
}

View File

@ -1,6 +1,5 @@
package com.baeldung.spring.data.redis.queue;
public interface MessagePublisher {
void publish(final String message);

View File

@ -16,8 +16,7 @@ public class RedisMessagePublisher implements MessagePublisher {
public RedisMessagePublisher() {
}
public RedisMessagePublisher(final RedisTemplate<String, Object> redisTemplate,
final ChannelTopic topic) {
public RedisMessagePublisher(final RedisTemplate<String, Object> redisTemplate, final ChannelTopic topic) {
this.redisTemplate = redisTemplate;
this.topic = topic;
}

View File

@ -18,16 +18,16 @@ import javax.sql.DataSource;
@ContextConfiguration(classes = { Cause1NonTransientConfig.class }, loader = AnnotationConfigContextLoader.class)
public class InvalidResourceUsageExceptionTest {
@Autowired
private IFooService fooService;
@Autowired
private IFooService fooService;
@Autowired
private DataSource restDataSource;
@Autowired
private DataSource restDataSource;
@Test(expected = InvalidDataAccessResourceUsageException.class)
public void whenRetrievingDataUserNoSelectRights_thenInvalidResourceUsageException() {
final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource);
jdbcTemplate.execute("revoke select from tutorialuser");
@Test(expected = InvalidDataAccessResourceUsageException.class)
public void whenRetrievingDataUserNoSelectRights_thenInvalidResourceUsageException() {
final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource);
jdbcTemplate.execute("revoke select from tutorialuser");
try {
fooService.findAll();
@ -36,11 +36,11 @@ public class InvalidResourceUsageExceptionTest {
}
}
@Test(expected = BadSqlGrammarException.class)
public void whenIncorrectSql_thenBadSqlGrammarException() {
final JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource);
@Test(expected = BadSqlGrammarException.class)
public void whenIncorrectSql_thenBadSqlGrammarException() {
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);
}
}

View File

@ -4,78 +4,78 @@ import java.io.Serializable;
public class Item implements Serializable {
private static final long serialVersionUID = 1L;
private Integer itemId;
private String itemName;
private String itemDescription;
private Integer itemPrice;
private static final long serialVersionUID = 1L;
private Integer itemId;
private String itemName;
private String itemDescription;
private Integer itemPrice;
// constructors
public Item() {
// constructors
public Item() {
}
}
public Item(final Integer itemId, final String itemName, final String itemDescription) {
super();
this.itemId = itemId;
this.itemName = itemName;
this.itemDescription = itemDescription;
}
public Item(final Integer itemId, final String itemName, final String itemDescription) {
super();
this.itemId = itemId;
this.itemName = itemName;
this.itemDescription = itemDescription;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((itemId == null) ? 0 : itemId.hashCode());
return result;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((itemId == null) ? 0 : itemId.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Item other = (Item) obj;
if (itemId == null) {
if (other.itemId != null)
return false;
} else if (!itemId.equals(other.itemId))
return false;
return true;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Item other = (Item) obj;
if (itemId == null) {
if (other.itemId != null)
return false;
} else if (!itemId.equals(other.itemId))
return false;
return true;
}
public Integer getItemId() {
return itemId;
}
public Integer getItemId() {
return itemId;
}
public void setItemId(final Integer itemId) {
this.itemId = itemId;
}
public void setItemId(final Integer itemId) {
this.itemId = itemId;
}
public String getItemName() {
return itemName;
}
public String getItemName() {
return itemName;
}
public void setItemName(final String itemName) {
this.itemName = itemName;
}
public void setItemName(final String itemName) {
this.itemName = itemName;
}
public String getItemDescription() {
return itemDescription;
}
public String getItemDescription() {
return itemDescription;
}
public Integer getItemPrice() {
return itemPrice;
}
public Integer getItemPrice() {
return itemPrice;
}
public void setItemPrice(final Integer itemPrice) {
this.itemPrice = itemPrice;
}
public void setItemPrice(final Integer itemPrice) {
this.itemPrice = itemPrice;
}
public void setItemDescription(final String itemDescription) {
this.itemDescription = itemDescription;
}
public void setItemDescription(final String itemDescription) {
this.itemDescription = itemDescription;
}
}

View File

@ -9,12 +9,11 @@ public class HibernateUtil {
@SuppressWarnings("deprecation")
public static Session getHibernateSession() {
final SessionFactory sf = new Configuration()
.configure("criteria.cfg.xml").buildSessionFactory();
final SessionFactory sf = new Configuration().configure("criteria.cfg.xml").buildSessionFactory();
// factory = new Configuration().configure().buildSessionFactory();
final Session session = sf.openSession();
return session;
// factory = new Configuration().configure().buildSessionFactory();
final Session session = sf.openSession();
return session;
}
}

View File

@ -26,228 +26,226 @@ import com.baeldung.hibernate.criteria.util.HibernateUtil;
public class ApplicationView {
// default Constructor
public ApplicationView() {
// default Constructor
public ApplicationView() {
}
}
public boolean checkIfCriteriaTimeLower() {
final Session session = HibernateUtil.getHibernateSession();
final Criteria cr = session.createCriteria(Item.class);
Transaction tx = null;
public boolean checkIfCriteriaTimeLower() {
final Session session = HibernateUtil.getHibernateSession();
final Criteria cr = session.createCriteria(Item.class);
Transaction tx = null;
// calculate the time taken by criteria
final long startTimeCriteria = System.nanoTime();
cr.add(Restrictions.like("itemName", "%item One%"));
final List results = cr.list();
final long endTimeCriteria = System.nanoTime();
final long durationCriteria = (endTimeCriteria - startTimeCriteria) / 1000;
// calculate the time taken by criteria
final long startTimeCriteria = System.nanoTime();
cr.add(Restrictions.like("itemName", "%item One%"));
final List results = cr.list();
final long endTimeCriteria = System.nanoTime();
final long durationCriteria = (endTimeCriteria - startTimeCriteria) / 1000;
// calculate the time taken by HQL
final long startTimeHQL = System.nanoTime();
tx = session.beginTransaction();
final List items = session.createQuery("FROM Item where itemName like '%item One%'").list();
final long endTimeHQL = System.nanoTime();
final long durationHQL = (endTimeHQL - startTimeHQL) / 1000;
// calculate the time taken by HQL
final long startTimeHQL = System.nanoTime();
tx = session.beginTransaction();
final List items = session.createQuery("FROM Item where itemName like '%item One%'").list();
final long endTimeHQL = System.nanoTime();
final long durationHQL = (endTimeHQL - startTimeHQL) / 1000;
if (durationCriteria > durationHQL) {
return false;
} else {
return true;
}
}
if (durationCriteria > durationHQL) {
return false;
} else {
return true;
}
}
// To get items having price more than 1000
public String[] greaterThanCriteria() {
final Session session = HibernateUtil.getHibernateSession();
final Criteria cr = session.createCriteria(Item.class);
cr.add(Restrictions.gt("itemPrice", 1000));
final List<Item> greaterThanItemsList = cr.list();
final String greaterThanItems[] = new String[greaterThanItemsList.size()];
for (int i = 0; i < greaterThanItemsList.size(); i++) {
greaterThanItems[i] = greaterThanItemsList.get(i).getItemName();
}
session.close();
return greaterThanItems;
}
// To get items having price more than 1000
public String[] greaterThanCriteria() {
final Session session = HibernateUtil.getHibernateSession();
final Criteria cr = session.createCriteria(Item.class);
cr.add(Restrictions.gt("itemPrice", 1000));
final List<Item> greaterThanItemsList = cr.list();
final String greaterThanItems[] = new String[greaterThanItemsList.size()];
for (int i = 0; i < greaterThanItemsList.size(); i++) {
greaterThanItems[i] = greaterThanItemsList.get(i).getItemName();
}
session.close();
return greaterThanItems;
}
// To get items having price less than 1000
public String[] lessThanCriteria() {
final Session session = HibernateUtil.getHibernateSession();
final Criteria cr = session.createCriteria(Item.class);
cr.add(Restrictions.lt("itemPrice", 1000));
final List<Item> lessThanItemsList = cr.list();
final String lessThanItems[] = new String[lessThanItemsList.size()];
for (int i = 0; i < lessThanItemsList.size(); i++) {
lessThanItems[i] = lessThanItemsList.get(i).getItemName();
}
session.close();
return lessThanItems;
}
// To get items having price less than 1000
public String[] lessThanCriteria() {
final Session session = HibernateUtil.getHibernateSession();
final Criteria cr = session.createCriteria(Item.class);
cr.add(Restrictions.lt("itemPrice", 1000));
final List<Item> lessThanItemsList = cr.list();
final String lessThanItems[] = new String[lessThanItemsList.size()];
for (int i = 0; i < lessThanItemsList.size(); i++) {
lessThanItems[i] = lessThanItemsList.get(i).getItemName();
}
session.close();
return lessThanItems;
}
// To get items whose Name start with Chair
public String[] likeCriteria() {
final Session session = HibernateUtil.getHibernateSession();
// To get items whose Name start with Chair
public String[] likeCriteria() {
final Session session = HibernateUtil.getHibernateSession();
final Criteria cr = session.createCriteria(Item.class);
cr.add(Restrictions.like("itemName", "%chair%"));
final List<Item> likeItemsList = cr.list();
final String likeItems[] = new String[likeItemsList.size()];
for (int i = 0; i < likeItemsList.size(); i++) {
likeItems[i] = likeItemsList.get(i).getItemName();
}
session.close();
return likeItems;
}
final Criteria cr = session.createCriteria(Item.class);
cr.add(Restrictions.like("itemName", "%chair%"));
final List<Item> likeItemsList = cr.list();
final String likeItems[] = new String[likeItemsList.size()];
for (int i = 0; i < likeItemsList.size(); i++) {
likeItems[i] = likeItemsList.get(i).getItemName();
}
session.close();
return likeItems;
}
// Case sensitive search
public String[] likeCaseCriteria() {
final Session session = HibernateUtil.getHibernateSession();
final Criteria cr = session.createCriteria(Item.class);
cr.add(Restrictions.ilike("itemName", "%Chair%"));
final List<Item> ilikeItemsList = cr.list();
final String ilikeItems[] = new String[ilikeItemsList.size()];
for (int i = 0; i < ilikeItemsList.size(); i++) {
ilikeItems[i] = ilikeItemsList.get(i).getItemName();
}
session.close();
return ilikeItems;
}
// Case sensitive search
public String[] likeCaseCriteria() {
final Session session = HibernateUtil.getHibernateSession();
final Criteria cr = session.createCriteria(Item.class);
cr.add(Restrictions.ilike("itemName", "%Chair%"));
final List<Item> ilikeItemsList = cr.list();
final String ilikeItems[] = new String[ilikeItemsList.size()];
for (int i = 0; i < ilikeItemsList.size(); i++) {
ilikeItems[i] = ilikeItemsList.get(i).getItemName();
}
session.close();
return ilikeItems;
}
// To get records having itemPrice in between 100 and 200
public String[] betweenCriteria() {
final Session session = HibernateUtil.getHibernateSession();
final Criteria cr = session.createCriteria(Item.class);
// To get items having price more than 1000
cr.add(Restrictions.between("itemPrice", 100, 200));
final List<Item> betweenItemsList = cr.list();
final String betweenItems[] = new String[betweenItemsList.size()];
for (int i = 0; i < betweenItemsList.size(); i++) {
betweenItems[i] = betweenItemsList.get(i).getItemName();
}
session.close();
return betweenItems;
}
// To get records having itemPrice in between 100 and 200
public String[] betweenCriteria() {
final Session session = HibernateUtil.getHibernateSession();
final Criteria cr = session.createCriteria(Item.class);
// To get items having price more than 1000
cr.add(Restrictions.between("itemPrice", 100, 200));
final List<Item> betweenItemsList = cr.list();
final String betweenItems[] = new String[betweenItemsList.size()];
for (int i = 0; i < betweenItemsList.size(); i++) {
betweenItems[i] = betweenItemsList.get(i).getItemName();
}
session.close();
return betweenItems;
}
// To check if the given property is null
public String[] nullCriteria() {
final Session session = HibernateUtil.getHibernateSession();
final Criteria cr = session.createCriteria(Item.class);
cr.add(Restrictions.isNull("itemDescription"));
final List<Item> nullItemsList = cr.list();
final String nullDescItems[] = new String[nullItemsList.size()];
for (int i = 0; i < nullItemsList.size(); i++) {
nullDescItems[i] = nullItemsList.get(i).getItemName();
}
session.close();
return nullDescItems;
}
// To check if the given property is null
public String[] nullCriteria() {
final Session session = HibernateUtil.getHibernateSession();
final Criteria cr = session.createCriteria(Item.class);
cr.add(Restrictions.isNull("itemDescription"));
final List<Item> nullItemsList = cr.list();
final String nullDescItems[] = new String[nullItemsList.size()];
for (int i = 0; i < nullItemsList.size(); i++) {
nullDescItems[i] = nullItemsList.get(i).getItemName();
}
session.close();
return nullDescItems;
}
// To check if the given property is not null
public String[] notNullCriteria() {
final Session session = HibernateUtil.getHibernateSession();
final Criteria cr = session.createCriteria(Item.class);
cr.add(Restrictions.isNotNull("itemDescription"));
final List<Item> notNullItemsList = cr.list();
final String notNullDescItems[] = new String[notNullItemsList.size()];
for (int i = 0; i < notNullItemsList.size(); i++) {
notNullDescItems[i] = notNullItemsList.get(i).getItemName();
}
session.close();
return notNullDescItems;
}
// To check if the given property is not null
public String[] notNullCriteria() {
final Session session = HibernateUtil.getHibernateSession();
final Criteria cr = session.createCriteria(Item.class);
cr.add(Restrictions.isNotNull("itemDescription"));
final List<Item> notNullItemsList = cr.list();
final String notNullDescItems[] = new String[notNullItemsList.size()];
for (int i = 0; i < notNullItemsList.size(); i++) {
notNullDescItems[i] = notNullItemsList.get(i).getItemName();
}
session.close();
return notNullDescItems;
}
// Adding more than one expression in one cr
public String[] twoCriteria() {
final Session session = HibernateUtil.getHibernateSession();
final Criteria cr = session.createCriteria(Item.class);
cr.add(Restrictions.isNull("itemDescription"));
cr.add(Restrictions.like("itemName", "chair%"));
final List<Item> notNullItemsList = cr.list();
final String notNullDescItems[] = new String[notNullItemsList.size()];
for (int i = 0; i < notNullItemsList.size(); i++) {
notNullDescItems[i] = notNullItemsList.get(i).getItemName();
}
session.close();
return notNullDescItems;
}
// Adding more than one expression in one cr
public String[] twoCriteria() {
final Session session = HibernateUtil.getHibernateSession();
final Criteria cr = session.createCriteria(Item.class);
cr.add(Restrictions.isNull("itemDescription"));
cr.add(Restrictions.like("itemName", "chair%"));
final List<Item> notNullItemsList = cr.list();
final String notNullDescItems[] = new String[notNullItemsList.size()];
for (int i = 0; i < notNullItemsList.size(); i++) {
notNullDescItems[i] = notNullItemsList.get(i).getItemName();
}
session.close();
return notNullDescItems;
}
// To get items matching with the above defined conditions joined
// with Logical AND
public String[] andLogicalCriteria() {
final Session session = HibernateUtil.getHibernateSession();
final Criteria cr = session.createCriteria(Item.class);
final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000);
final Criterion chairItems = Restrictions.like("itemName", "Chair%");
final LogicalExpression andExample = Restrictions.and(greaterThanPrice, chairItems);
cr.add(andExample);
final List<Item> andItemsList = cr.list();
final String andItems[] = new String[andItemsList.size()];
for (int i = 0; i < andItemsList.size(); i++) {
andItems[i] = andItemsList.get(i).getItemName();
}
session.close();
return andItems;
}
// To get items matching with the above defined conditions joined
// with Logical AND
public String[] andLogicalCriteria() {
final Session session = HibernateUtil.getHibernateSession();
final Criteria cr = session.createCriteria(Item.class);
final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000);
final Criterion chairItems = Restrictions.like("itemName", "Chair%");
final LogicalExpression andExample = Restrictions.and(greaterThanPrice, chairItems);
cr.add(andExample);
final List<Item> andItemsList = cr.list();
final String andItems[] = new String[andItemsList.size()];
for (int i = 0; i < andItemsList.size(); i++) {
andItems[i] = andItemsList.get(i).getItemName();
}
session.close();
return andItems;
}
// To get items matching with the above defined conditions joined
// with Logical OR
public String[] orLogicalCriteria() {
final Session session = HibernateUtil.getHibernateSession();
final Criteria cr = session.createCriteria(Item.class);
final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000);
final Criterion chairItems = Restrictions.like("itemName", "Chair%");
final LogicalExpression orExample = Restrictions.or(greaterThanPrice, chairItems);
cr.add(orExample);
final List<Item> orItemsList = cr.list();
final String orItems[] = new String[orItemsList.size()];
for (int i = 0; i < orItemsList.size(); i++) {
orItems[i] = orItemsList.get(i).getItemName();
}
session.close();
return orItems;
}
// To get items matching with the above defined conditions joined
// with Logical OR
public String[] orLogicalCriteria() {
final Session session = HibernateUtil.getHibernateSession();
final Criteria cr = session.createCriteria(Item.class);
final Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000);
final Criterion chairItems = Restrictions.like("itemName", "Chair%");
final LogicalExpression orExample = Restrictions.or(greaterThanPrice, chairItems);
cr.add(orExample);
final List<Item> orItemsList = cr.list();
final String orItems[] = new String[orItemsList.size()];
for (int i = 0; i < orItemsList.size(); i++) {
orItems[i] = orItemsList.get(i).getItemName();
}
session.close();
return orItems;
}
// Sorting example
public String[] sortingCriteria() {
final Session session = HibernateUtil.getHibernateSession();
final Criteria cr = session.createCriteria(Item.class);
cr.addOrder(Order.asc("itemName"));
cr.addOrder(Order.desc("itemPrice")).list();
final List<Item> sortedItemsList = cr.list();
final String sortedItems[] = new String[sortedItemsList.size()];
for (int i = 0; i < sortedItemsList.size(); i++) {
sortedItems[i] = sortedItemsList.get(i).getItemName();
}
session.close();
return sortedItems;
}
// Sorting example
public String[] sortingCriteria() {
final Session session = HibernateUtil.getHibernateSession();
final Criteria cr = session.createCriteria(Item.class);
cr.addOrder(Order.asc("itemName"));
cr.addOrder(Order.desc("itemPrice")).list();
final List<Item> sortedItemsList = cr.list();
final String sortedItems[] = new String[sortedItemsList.size()];
for (int i = 0; i < sortedItemsList.size(); i++) {
sortedItems[i] = sortedItemsList.get(i).getItemName();
}
session.close();
return sortedItems;
}
// Set projections Row Count
public Long[] projectionRowCount() {
final Session session = HibernateUtil.getHibernateSession();
final List<Long> itemProjected = session.createCriteria(Item.class).setProjection(Projections.rowCount())
.list();
final Long projectedRowCount[] = new Long[itemProjected.size()];
for (int i = 0; i < itemProjected.size(); i++) {
projectedRowCount[i] = itemProjected.get(i);
}
session.close();
return projectedRowCount;
}
// Set projections Row Count
public Long[] projectionRowCount() {
final Session session = HibernateUtil.getHibernateSession();
final List<Long> itemProjected = session.createCriteria(Item.class).setProjection(Projections.rowCount()).list();
final Long projectedRowCount[] = new Long[itemProjected.size()];
for (int i = 0; i < itemProjected.size(); i++) {
projectedRowCount[i] = itemProjected.get(i);
}
session.close();
return projectedRowCount;
}
// Set projections average of itemPrice
public Double[] projectionAverage() {
final Session session = HibernateUtil.getHibernateSession();
final List avgItemPriceList = session.createCriteria(Item.class)
.setProjection(Projections.projectionList().add(Projections.avg("itemPrice"))).list();
// Set projections average of itemPrice
public Double[] projectionAverage() {
final Session session = HibernateUtil.getHibernateSession();
final List avgItemPriceList = session.createCriteria(Item.class).setProjection(Projections.projectionList().add(Projections.avg("itemPrice"))).list();
final Double avgItemPrice[] = new Double[avgItemPriceList.size()];
for (int i = 0; i < avgItemPriceList.size(); i++) {
avgItemPrice[i] = (Double) avgItemPriceList.get(i);
}
session.close();
return avgItemPrice;
}
final Double avgItemPrice[] = new Double[avgItemPriceList.size()];
for (int i = 0; i < avgItemPriceList.size(); i++) {
avgItemPrice[i] = (Double) avgItemPriceList.get(i);
}
session.close();
return avgItemPrice;
}
}

View File

@ -5,54 +5,54 @@ import java.io.Serializable;
import java.sql.Date;
@Entity
@Table (name = "USER_ORDER")
public class OrderDetail implements Serializable{
@Table(name = "USER_ORDER")
public class OrderDetail implements Serializable {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
@Column(name="ORDER_ID")
private Long orderId;
@Id
@GeneratedValue
@Column(name = "ORDER_ID")
private Long orderId;
public OrderDetail(){
}
public OrderDetail() {
}
public OrderDetail(Date orderDate, String orderDesc) {
super();
}
public OrderDetail(Date orderDate, String orderDesc) {
super();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((orderId == null) ? 0 : orderId.hashCode());
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;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((orderId == null) ? 0 : orderId.hashCode());
return result;
}
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 orderId;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
return true;
}
public Long getOrderId() {
return orderId;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
}

View File

@ -6,66 +6,66 @@ import java.util.HashSet;
import java.util.Set;
@Entity
@Table (name = "USER")
@Table(name = "USER")
public class UserEager implements Serializable {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
@Column(name="USER_ID")
private Long userId;
@Id
@GeneratedValue
@Column(name = "USER_ID")
private Long userId;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "user")
private Set<OrderDetail> orderDetail = new HashSet();
@OneToMany(fetch = FetchType.EAGER, mappedBy = "user")
private Set<OrderDetail> orderDetail = new HashSet();
public UserEager() {
}
public UserEager() {
}
public UserEager(final Long userId) {
super();
this.userId = userId;
}
public UserEager(final Long userId) {
super();
this.userId = userId;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((userId == null) ? 0 : userId.hashCode());
return result;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((userId == null) ? 0 : userId.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final UserEager other = (UserEager) obj;
if (userId == null) {
if (other.userId != null)
return false;
} else if (!userId.equals(other.userId))
return false;
return true;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final UserEager other = (UserEager) obj;
if (userId == null) {
if (other.userId != null)
return false;
} else if (!userId.equals(other.userId))
return false;
return true;
}
public Long getUserId() {
return userId;
}
public Long getUserId() {
return userId;
}
public void setUserId(final Long userId) {
this.userId = userId;
}
public void setUserId(final Long userId) {
this.userId = userId;
}
public Set<OrderDetail> getOrderDetail() {
return orderDetail;
}
public Set<OrderDetail> getOrderDetail() {
return orderDetail;
}
public void setOrderDetail(Set<OrderDetail> orderDetail) {
this.orderDetail = orderDetail;
}
public void setOrderDetail(Set<OrderDetail> orderDetail) {
this.orderDetail = orderDetail;
}
}

View File

@ -6,67 +6,66 @@ import java.util.HashSet;
import java.util.Set;
@Entity
@Table (name = "USER")
@Table(name = "USER")
public class UserLazy implements Serializable {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
@Column(name="USER_ID")
private Long userId;
@Id
@GeneratedValue
@Column(name = "USER_ID")
private Long userId;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
private Set<OrderDetail> orderDetail = new HashSet();
@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
private Set<OrderDetail> orderDetail = new HashSet();
public UserLazy() {
}
public UserLazy() {
}
public UserLazy(final Long userId) {
super();
this.userId = userId;
}
public UserLazy(final Long userId) {
super();
this.userId = userId;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((userId == null) ? 0 : userId.hashCode());
return result;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((userId == null) ? 0 : userId.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final UserLazy other = (UserLazy) obj;
if (userId == null) {
if (other.userId != null)
return false;
} else if (!userId.equals(other.userId))
return false;
return true;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final UserLazy other = (UserLazy) obj;
if (userId == null) {
if (other.userId != null)
return false;
} else if (!userId.equals(other.userId))
return false;
return true;
}
public Long getUserId() {
return userId;
}
public Long getUserId() {
return userId;
}
public void setUserId(final Long userId) {
this.userId = userId;
}
public void setUserId(final Long userId) {
this.userId = userId;
}
public Set<OrderDetail> getOrderDetail() {
return orderDetail;
}
public Set<OrderDetail> getOrderDetail() {
return orderDetail;
}
public void setOrderDetail(Set<OrderDetail> orderDetail) {
this.orderDetail = orderDetail;
}
public void setOrderDetail(Set<OrderDetail> orderDetail) {
this.orderDetail = orderDetail;
}
}

View File

@ -6,27 +6,24 @@ import org.hibernate.cfg.Configuration;
public class HibernateUtil {
@SuppressWarnings("deprecation")
public static Session getHibernateSession(String fetchMethod) {
//two config files are there
//one with lazy loading enabled
//another lazy = false
SessionFactory sf;
if ("lazy".equals(fetchMethod)) {
sf = new Configuration().configure("fetchingLazy.cfg.xml").buildSessionFactory();
} else {
sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory();
}
@SuppressWarnings("deprecation")
public static Session getHibernateSession(String fetchMethod) {
// two config files are there
// one with lazy loading enabled
// another lazy = false
SessionFactory sf;
if ("lazy".equals(fetchMethod)) {
sf = new Configuration().configure("fetchingLazy.cfg.xml").buildSessionFactory();
} else {
sf = new Configuration().configure("fetching.cfg.xml").buildSessionFactory();
}
// fetching.cfg.xml is used for this example
return sf.openSession();
}
// fetching.cfg.xml is used for this example
return sf.openSession();
}
public static Session getHibernateSession() {
return new Configuration()
.configure("fetching.cfg.xml")
.buildSessionFactory()
.openSession();
return new Configuration().configure("fetching.cfg.xml").buildSessionFactory().openSession();
}
}

View File

@ -16,92 +16,90 @@ import javax.persistence.NamedNativeQuery;
import org.hibernate.envers.Audited;
@NamedNativeQueries({
@NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class),
@NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class) })
@NamedNativeQueries({ @NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class), @NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class) })
@Entity
@Audited
// @Proxy(lazy = false)
public class Foo implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private long id;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private long id;
@Column(name = "name")
private String name;
@Column(name = "name")
private String name;
@ManyToOne(targetEntity = Bar.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "BAR_ID")
private Bar bar = new Bar();
@ManyToOne(targetEntity = Bar.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "BAR_ID")
private Bar bar = new Bar();
public Foo() {
super();
}
public Foo() {
super();
}
public Foo(final String name) {
super();
this.name = name;
}
public Foo(final String name) {
super();
this.name = name;
}
//
//
public Bar getBar() {
return bar;
}
public Bar getBar() {
return bar;
}
public void setBar(final Bar bar) {
this.bar = bar;
}
public void setBar(final Bar bar) {
this.bar = bar;
}
public long getId() {
return id;
}
public long getId() {
return id;
}
public void setId(final long id) {
this.id = id;
}
public void setId(final long id) {
this.id = id;
}
public String getName() {
return name;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public void setName(final String name) {
this.name = name;
}
//
//
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Foo other = (Foo) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Foo other = (Foo) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Foo [name=").append(name).append("]");
return builder.toString();
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Foo [name=").append(name).append("]");
return builder.toString();
}
}

View File

@ -14,178 +14,170 @@ import com.baeldung.hibernate.criteria.view.ApplicationView;
public class HibernateCriteriaTest {
final private ApplicationView av = new ApplicationView();
final private ApplicationView av = new ApplicationView();
@Test
public void testPerformanceOfCriteria() {
assertTrue(av.checkIfCriteriaTimeLower());
}
@Test
public void testPerformanceOfCriteria() {
assertTrue(av.checkIfCriteriaTimeLower());
}
@Test
public void testLikeCriteriaQuery() {
final Session session = HibernateUtil.getHibernateSession();
final List<Item> expectedLikeList = session.createQuery("From Item where itemName like '%chair%'").list();
final String expectedLikeItems[] = new String[expectedLikeList.size()];
for (int i = 0; i < expectedLikeList.size(); i++) {
expectedLikeItems[i] = expectedLikeList.get(i).getItemName();
}
session.close();
assertArrayEquals(expectedLikeItems, av.likeCriteria());
}
@Test
public void testLikeCriteriaQuery() {
final Session session = HibernateUtil.getHibernateSession();
final List<Item> expectedLikeList = session.createQuery("From Item where itemName like '%chair%'").list();
final String expectedLikeItems[] = new String[expectedLikeList.size()];
for (int i = 0; i < expectedLikeList.size(); i++) {
expectedLikeItems[i] = expectedLikeList.get(i).getItemName();
}
session.close();
assertArrayEquals(expectedLikeItems, av.likeCriteria());
}
@Test
public void testILikeCriteriaQuery() {
final Session session = HibernateUtil.getHibernateSession();
final List<Item> expectedChairCaseList = session.createQuery("From Item where itemName like '%Chair%'").list();
final String expectedChairCaseItems[] = new String[expectedChairCaseList.size()];
for (int i = 0; i < expectedChairCaseList.size(); i++) {
expectedChairCaseItems[i] = expectedChairCaseList.get(i).getItemName();
}
session.close();
assertArrayEquals(expectedChairCaseItems, av.likeCaseCriteria());
@Test
public void testILikeCriteriaQuery() {
final Session session = HibernateUtil.getHibernateSession();
final List<Item> expectedChairCaseList = session.createQuery("From Item where itemName like '%Chair%'").list();
final String expectedChairCaseItems[] = new String[expectedChairCaseList.size()];
for (int i = 0; i < expectedChairCaseList.size(); i++) {
expectedChairCaseItems[i] = expectedChairCaseList.get(i).getItemName();
}
session.close();
assertArrayEquals(expectedChairCaseItems, av.likeCaseCriteria());
}
}
@Test
public void testNullCriteriaQuery() {
final Session session = HibernateUtil.getHibernateSession();
final List<Item> expectedIsNullDescItemsList = session.createQuery("From Item where itemDescription is null")
.list();
final String expectedIsNullDescItems[] = new String[expectedIsNullDescItemsList.size()];
for (int i = 0; i < expectedIsNullDescItemsList.size(); i++) {
expectedIsNullDescItems[i] = expectedIsNullDescItemsList.get(i).getItemName();
}
session.close();
assertArrayEquals(expectedIsNullDescItems, av.nullCriteria());
}
@Test
public void testNullCriteriaQuery() {
final Session session = HibernateUtil.getHibernateSession();
final List<Item> expectedIsNullDescItemsList = session.createQuery("From Item where itemDescription is null").list();
final String expectedIsNullDescItems[] = new String[expectedIsNullDescItemsList.size()];
for (int i = 0; i < expectedIsNullDescItemsList.size(); i++) {
expectedIsNullDescItems[i] = expectedIsNullDescItemsList.get(i).getItemName();
}
session.close();
assertArrayEquals(expectedIsNullDescItems, av.nullCriteria());
}
@Test
public void testIsNotNullCriteriaQuery() {
final Session session = HibernateUtil.getHibernateSession();
final List<Item> expectedIsNotNullDescItemsList = session
.createQuery("From Item where itemDescription is not null").list();
final String expectedIsNotNullDescItems[] = new String[expectedIsNotNullDescItemsList.size()];
for (int i = 0; i < expectedIsNotNullDescItemsList.size(); i++) {
expectedIsNotNullDescItems[i] = expectedIsNotNullDescItemsList.get(i).getItemName();
}
session.close();
assertArrayEquals(expectedIsNotNullDescItems, av.notNullCriteria());
@Test
public void testIsNotNullCriteriaQuery() {
final Session session = HibernateUtil.getHibernateSession();
final List<Item> expectedIsNotNullDescItemsList = session.createQuery("From Item where itemDescription is not null").list();
final String expectedIsNotNullDescItems[] = new String[expectedIsNotNullDescItemsList.size()];
for (int i = 0; i < expectedIsNotNullDescItemsList.size(); i++) {
expectedIsNotNullDescItems[i] = expectedIsNotNullDescItemsList.get(i).getItemName();
}
session.close();
assertArrayEquals(expectedIsNotNullDescItems, av.notNullCriteria());
}
}
@Test
public void testAverageProjection() {
final Session session = HibernateUtil.getHibernateSession();
final List<Double> expectedAvgProjItemsList = session.createQuery("Select avg(itemPrice) from Item item")
.list();
@Test
public void testAverageProjection() {
final Session session = HibernateUtil.getHibernateSession();
final List<Double> expectedAvgProjItemsList = session.createQuery("Select avg(itemPrice) from Item item").list();
final Double expectedAvgProjItems[] = new Double[expectedAvgProjItemsList.size()];
for (int i = 0; i < expectedAvgProjItemsList.size(); i++) {
expectedAvgProjItems[i] = expectedAvgProjItemsList.get(i);
}
session.close();
assertArrayEquals(expectedAvgProjItems, av.projectionAverage());
final Double expectedAvgProjItems[] = new Double[expectedAvgProjItemsList.size()];
for (int i = 0; i < expectedAvgProjItemsList.size(); i++) {
expectedAvgProjItems[i] = expectedAvgProjItemsList.get(i);
}
session.close();
assertArrayEquals(expectedAvgProjItems, av.projectionAverage());
}
}
@Test
public void testRowCountProjection() {
final Session session = HibernateUtil.getHibernateSession();
final List<Long> expectedCountProjItemsList = session.createQuery("Select count(*) from Item").list();
final Long expectedCountProjItems[] = new Long[expectedCountProjItemsList.size()];
for (int i = 0; i < expectedCountProjItemsList.size(); i++) {
expectedCountProjItems[i] = expectedCountProjItemsList.get(i);
}
session.close();
assertArrayEquals(expectedCountProjItems, av.projectionRowCount());
}
@Test
public void testRowCountProjection() {
final Session session = HibernateUtil.getHibernateSession();
final List<Long> expectedCountProjItemsList = session.createQuery("Select count(*) from Item").list();
final Long expectedCountProjItems[] = new Long[expectedCountProjItemsList.size()];
for (int i = 0; i < expectedCountProjItemsList.size(); i++) {
expectedCountProjItems[i] = expectedCountProjItemsList.get(i);
}
session.close();
assertArrayEquals(expectedCountProjItems, av.projectionRowCount());
}
@Test
public void testOrCriteriaQuery() {
final Session session = HibernateUtil.getHibernateSession();
final List<Item> expectedOrCritItemsList = session
.createQuery("From Item where itemPrice>1000 or itemName like 'Chair%'").list();
final String expectedOrCritItems[] = new String[expectedOrCritItemsList.size()];
for (int i = 0; i < expectedOrCritItemsList.size(); i++) {
expectedOrCritItems[i] = expectedOrCritItemsList.get(i).getItemName();
}
session.close();
assertArrayEquals(expectedOrCritItems, av.orLogicalCriteria());
}
@Test
public void testOrCriteriaQuery() {
final Session session = HibernateUtil.getHibernateSession();
final List<Item> expectedOrCritItemsList = session.createQuery("From Item where itemPrice>1000 or itemName like 'Chair%'").list();
final String expectedOrCritItems[] = new String[expectedOrCritItemsList.size()];
for (int i = 0; i < expectedOrCritItemsList.size(); i++) {
expectedOrCritItems[i] = expectedOrCritItemsList.get(i).getItemName();
}
session.close();
assertArrayEquals(expectedOrCritItems, av.orLogicalCriteria());
}
@Test
public void testAndCriteriaQuery() {
final Session session = HibernateUtil.getHibernateSession();
final List<Item> expectedAndCritItemsList = session
.createQuery("From Item where itemPrice>1000 and itemName like 'Chair%'").list();
final String expectedAndCritItems[] = new String[expectedAndCritItemsList.size()];
for (int i = 0; i < expectedAndCritItemsList.size(); i++) {
expectedAndCritItems[i] = expectedAndCritItemsList.get(i).getItemName();
}
session.close();
assertArrayEquals(expectedAndCritItems, av.andLogicalCriteria());
}
@Test
public void testAndCriteriaQuery() {
final Session session = HibernateUtil.getHibernateSession();
final List<Item> expectedAndCritItemsList = session.createQuery("From Item where itemPrice>1000 and itemName like 'Chair%'").list();
final String expectedAndCritItems[] = new String[expectedAndCritItemsList.size()];
for (int i = 0; i < expectedAndCritItemsList.size(); i++) {
expectedAndCritItems[i] = expectedAndCritItemsList.get(i).getItemName();
}
session.close();
assertArrayEquals(expectedAndCritItems, av.andLogicalCriteria());
}
@Test
public void testMultiCriteriaQuery() {
final Session session = HibernateUtil.getHibernateSession();
final List<Item> expectedMultiCritItemsList = session
.createQuery("From Item where itemDescription is null and itemName like'chair%'").list();
final String expectedMultiCritItems[] = new String[expectedMultiCritItemsList.size()];
for (int i = 0; i < expectedMultiCritItemsList.size(); i++) {
expectedMultiCritItems[i] = expectedMultiCritItemsList.get(i).getItemName();
}
session.close();
assertArrayEquals(expectedMultiCritItems, av.twoCriteria());
}
@Test
public void testMultiCriteriaQuery() {
final Session session = HibernateUtil.getHibernateSession();
final List<Item> expectedMultiCritItemsList = session.createQuery("From Item where itemDescription is null and itemName like'chair%'").list();
final String expectedMultiCritItems[] = new String[expectedMultiCritItemsList.size()];
for (int i = 0; i < expectedMultiCritItemsList.size(); i++) {
expectedMultiCritItems[i] = expectedMultiCritItemsList.get(i).getItemName();
}
session.close();
assertArrayEquals(expectedMultiCritItems, av.twoCriteria());
}
@Test
public void testSortCriteriaQuery() {
final Session session = HibernateUtil.getHibernateSession();
final List<Item> expectedSortCritItemsList = session
.createQuery("From Item order by itemName asc, itemPrice desc").list();
final String expectedSortCritItems[] = new String[expectedSortCritItemsList.size()];
for (int i = 0; i < expectedSortCritItemsList.size(); i++) {
expectedSortCritItems[i] = expectedSortCritItemsList.get(i).getItemName();
}
session.close();
assertArrayEquals(expectedSortCritItems, av.sortingCriteria());
}
@Test
public void testSortCriteriaQuery() {
final Session session = HibernateUtil.getHibernateSession();
final List<Item> expectedSortCritItemsList = session.createQuery("From Item order by itemName asc, itemPrice desc").list();
final String expectedSortCritItems[] = new String[expectedSortCritItemsList.size()];
for (int i = 0; i < expectedSortCritItemsList.size(); i++) {
expectedSortCritItems[i] = expectedSortCritItemsList.get(i).getItemName();
}
session.close();
assertArrayEquals(expectedSortCritItems, av.sortingCriteria());
}
@Test
public void testGreaterThanCriteriaQuery() {
final Session session = HibernateUtil.getHibernateSession();
final List<Item> expectedGreaterThanList = session.createQuery("From Item where itemPrice>1000").list();
final String expectedGreaterThanItems[] = new String[expectedGreaterThanList.size()];
for (int i = 0; i < expectedGreaterThanList.size(); i++) {
expectedGreaterThanItems[i] = expectedGreaterThanList.get(i).getItemName();
}
session.close();
assertArrayEquals(expectedGreaterThanItems, av.greaterThanCriteria());
}
@Test
public void testGreaterThanCriteriaQuery() {
final Session session = HibernateUtil.getHibernateSession();
final List<Item> expectedGreaterThanList = session.createQuery("From Item where itemPrice>1000").list();
final String expectedGreaterThanItems[] = new String[expectedGreaterThanList.size()];
for (int i = 0; i < expectedGreaterThanList.size(); i++) {
expectedGreaterThanItems[i] = expectedGreaterThanList.get(i).getItemName();
}
session.close();
assertArrayEquals(expectedGreaterThanItems, av.greaterThanCriteria());
}
@Test
public void testLessThanCriteriaQuery() {
final Session session = HibernateUtil.getHibernateSession();
final List<Item> expectedLessList = session.createQuery("From Item where itemPrice<1000").list();
final String expectedLessThanItems[] = new String[expectedLessList.size()];
for (int i = 0; i < expectedLessList.size(); i++) {
expectedLessThanItems[i] = expectedLessList.get(i).getItemName();
}
session.close();
assertArrayEquals(expectedLessThanItems, av.lessThanCriteria());
}
@Test
public void testLessThanCriteriaQuery() {
final Session session = HibernateUtil.getHibernateSession();
final List<Item> expectedLessList = session.createQuery("From Item where itemPrice<1000").list();
final String expectedLessThanItems[] = new String[expectedLessList.size()];
for (int i = 0; i < expectedLessList.size(); i++) {
expectedLessThanItems[i] = expectedLessList.get(i).getItemName();
}
session.close();
assertArrayEquals(expectedLessThanItems, av.lessThanCriteria());
}
@Test
public void betweenCriteriaQuery() {
final Session session = HibernateUtil.getHibernateSession();
final List<Item> expectedBetweenList = session.createQuery("From Item where itemPrice between 100 and 200")
.list();
final String expectedPriceBetweenItems[] = new String[expectedBetweenList.size()];
for (int i = 0; i < expectedBetweenList.size(); i++) {
expectedPriceBetweenItems[i] = expectedBetweenList.get(i).getItemName();
}
session.close();
assertArrayEquals(expectedPriceBetweenItems, av.betweenCriteria());
}
@Test
public void betweenCriteriaQuery() {
final Session session = HibernateUtil.getHibernateSession();
final List<Item> expectedBetweenList = session.createQuery("From Item where itemPrice between 100 and 200").list();
final String expectedPriceBetweenItems[] = new String[expectedBetweenList.size()];
for (int i = 0; i < expectedBetweenList.size(); i++) {
expectedPriceBetweenItems[i] = expectedBetweenList.get(i).getItemName();
}
session.close();
assertArrayEquals(expectedPriceBetweenItems, av.betweenCriteria());
}
}

View File

@ -6,10 +6,10 @@ import org.junit.runner.notification.Failure;
public class HibernateCriteriaTestRunner {
public static void main(final String[] args) {
Result result = JUnitCore.runClasses(HibernateCriteriaTestSuite.class);
for (Failure failure : result.getFailures()) {
public static void main(final String[] args) {
Result result = JUnitCore.runClasses(HibernateCriteriaTestSuite.class);
for (Failure failure : result.getFailures()) {
}
}
}
}
}

View File

@ -13,31 +13,30 @@ import static org.junit.Assert.assertTrue;
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
@Before
public void addFecthingTestData(){
FetchingAppView fav = new FetchingAppView();
fav.createTestData();
}
// testLazyFetching() tests the lazy loading
// Since it lazily loaded so orderDetalSetLazy won't
// be initialized
@Test
public void testLazyFetching() {
FetchingAppView fav = new FetchingAppView();
Set<OrderDetail> orderDetalSetLazy = fav.lazyLoaded();
assertFalse(Hibernate.isInitialized(orderDetalSetLazy));
}
//testLazyFetching() tests the lazy loading
//Since it lazily loaded so orderDetalSetLazy won't
//be initialized
@Test
public void testLazyFetching() {
FetchingAppView fav = new FetchingAppView();
Set<OrderDetail> orderDetalSetLazy = fav.lazyLoaded();
assertFalse(Hibernate.isInitialized(orderDetalSetLazy));
}
//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));
}
// 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));
}
}

View File

@ -1,6 +1,5 @@
package com.baeldung.persistence.save;
import com.baeldung.persistence.model.Person;
import org.hibernate.HibernateException;
import org.hibernate.Session;
@ -25,16 +24,9 @@ public class SaveMethodsTest {
@BeforeClass
public static void beforeTests() {
Configuration configuration = new Configuration()
.addAnnotatedClass(Person.class)
.setProperty("hibernate.dialect", HSQLDialect.class.getName())
.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();
Configuration configuration = new Configuration().addAnnotatedClass(Person.class).setProperty("hibernate.dialect", HSQLDialect.class.getName()).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);
}
@ -44,7 +36,6 @@ public class SaveMethodsTest {
session.beginTransaction();
}
@Test
public void whenPersistTransient_thenSavedToDatabaseOnCommit() {
@ -244,7 +235,6 @@ public class SaveMethodsTest {
assertNotNull(session.get(Person.class, person.getId()));
}
@Test

View File

@ -25,7 +25,7 @@ import com.baeldung.persistence.model.Foo;
import com.baeldung.spring.PersistenceConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {PersistenceConfig.class}, loader = AnnotationConfigContextLoader.class)
@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
public class FooStoredProceduresIntegrationTest {
private static final Logger LOGGER = LoggerFactory.getLogger(FooStoredProceduresIntegrationTest.class);
@ -47,8 +47,7 @@ public class FooStoredProceduresIntegrationTest {
private boolean getFoosByNameExists() {
try {
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()")
.addEntity(Foo.class);
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class);
sqlQuery.list();
return true;
} catch (SQLGrammarException e) {
@ -59,8 +58,7 @@ public class FooStoredProceduresIntegrationTest {
private boolean getAllFoosExists() {
try {
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()")
.addEntity(Foo.class);
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class);
sqlQuery.list();
return true;
} catch (SQLGrammarException e) {
@ -80,8 +78,7 @@ public class FooStoredProceduresIntegrationTest {
fooService.create(new Foo(randomAlphabetic(6)));
// Stored procedure getAllFoos using createSQLQuery
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(
Foo.class);
Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class);
@SuppressWarnings("unchecked")
List<Foo> allFoos = sqlQuery.list();
for (Foo foo : allFoos) {
@ -105,8 +102,7 @@ public class FooStoredProceduresIntegrationTest {
fooService.create(new Foo("NewFooName"));
// Stored procedure getFoosByName using createSQLQuery()
Query sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)")
.addEntity(Foo.class).setParameter("fooName", "NewFooName");
Query sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)").addEntity(Foo.class).setParameter("fooName", "NewFooName");
@SuppressWarnings("unchecked")
List<Foo> allFoosByName = sqlQuery.list();
for (Foo foo : allFoosByName) {
@ -114,8 +110,7 @@ public class FooStoredProceduresIntegrationTest {
}
// Stored procedure getFoosByName using getNamedQuery()
Query namedQuery = session.getNamedQuery("callGetFoosByName")
.setParameter("fooName", "NewFooName");
Query namedQuery = session.getNamedQuery("callGetFoosByName").setParameter("fooName", "NewFooName");
@SuppressWarnings("unchecked")
List<Foo> allFoosByName2 = namedQuery.list();
for (Foo foo : allFoosByName2) {

View File

@ -12,8 +12,7 @@ public class DefaultTextMessageSenderTest {
@SuppressWarnings("resource")
@BeforeClass
public static void setUp() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml");
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml");
messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender");
}

View File

@ -12,8 +12,7 @@ public class MapMessageConvertAndSendTest {
@SuppressWarnings("resource")
@BeforeClass
public static void setUp() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml");
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:EmbeddedActiveMQ.xml", "classpath:applicationContext.xml");
messageProducer = (SampleJmsMessageSender) applicationContext.getBean("SampleJmsMessageSender");
}

View File

@ -43,8 +43,7 @@ public class SecondLevelCacheIntegrationTest {
final Foo foo = new Foo(randomAlphabetic(6));
fooService.create(foo);
fooService.findOne(foo.getId());
final int size = CacheManager.ALL_CACHE_MANAGERS.get(0)
.getCache("org.baeldung.persistence.model.Foo").getSize();
final int size = CacheManager.ALL_CACHE_MANAGERS.get(0).getCache("org.baeldung.persistence.model.Foo").getSize();
assertThat(size, greaterThan(0));
}
@ -64,21 +63,17 @@ public class SecondLevelCacheIntegrationTest {
return nativeQuery.executeUpdate();
});
final int size = CacheManager.ALL_CACHE_MANAGERS.get(0)
.getCache("org.baeldung.persistence.model.Foo").getSize();
final int size = CacheManager.ALL_CACHE_MANAGERS.get(0).getCache("org.baeldung.persistence.model.Foo").getSize();
assertThat(size, greaterThan(0));
}
@Test
public final void givenCacheableQueryIsExecuted_thenItIsCached() {
new TransactionTemplate(platformTransactionManager).execute(status -> {
return entityManager.createQuery("select f from Foo f")
.setHint("org.hibernate.cacheable", true)
.getResultList();
return entityManager.createQuery("select f from Foo f").setHint("org.hibernate.cacheable", true).getResultList();
});
final int size = CacheManager.ALL_CACHE_MANAGERS.get(0)
.getCache("org.hibernate.cache.internal.StandardQueryCache").getSize();
final int size = CacheManager.ALL_CACHE_MANAGERS.get(0).getCache("org.hibernate.cache.internal.StandardQueryCache").getSize();
assertThat(size, greaterThan(0));
}
}

View File

@ -30,7 +30,7 @@ public class User {
private String email;
@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
@JsonApiIncludeByDefault
private Set<Role> roles;

View File

@ -5,7 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MocksApplication {
public static void main(String[] args) {
SpringApplication.run(MocksApplication.class, args);
}
public static void main(String[] args) {
SpringApplication.run(MocksApplication.class, args);
}
}

View File

@ -17,13 +17,12 @@ public class MainController {
@Autowired
private ITutorialsService tutService;
@RequestMapping(value ="/", method = RequestMethod.GET)
@RequestMapping(value = "/", method = RequestMethod.GET)
public String welcomePage() {
return "index";
return "index";
}
@RequestMapping(value ="/list", method = RequestMethod.GET)
@RequestMapping(value = "/list", method = RequestMethod.GET)
public String listTutorialsPage(Model model) {
List<Tutorial> list = tutService.listTutorials();
model.addAttribute("tutorials", list);
@ -38,5 +37,4 @@ public class MainController {
this.tutService = tutService;
}
}

View File

@ -6,5 +6,5 @@ import java.util.List;
public interface ITutorialsService {
List<Tutorial> listTutorials();
List<Tutorial> listTutorials();
}

View File

@ -10,9 +10,6 @@ import java.util.List;
public class TutorialsService implements ITutorialsService {
public List<Tutorial> listTutorials() {
return Arrays.asList(
new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"),
new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor")
);
return Arrays.asList(new Tutorial(1, "Guava", "Introduction to Guava", "GuavaAuthor"), new Tutorial(2, "Android", "Introduction to Android", "AndroidAuthor"));
}
}

View File

@ -13,7 +13,7 @@ import org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver;
@Configuration
@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 {
@Override

View File

@ -39,7 +39,6 @@ public class DataContentControllerTest {
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@ -55,7 +54,7 @@ public class DataContentControllerTest {
}
@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));
}
}

View File

@ -9,7 +9,6 @@ import org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver;
@Configuration
public class TestConfig {
@Bean
public ViewResolver viewResolver() {
final VelocityLayoutViewResolver bean = new VelocityLayoutViewResolver();
@ -27,6 +26,4 @@ public class TestConfig {
return velocityConfigurer;
}
}

View File

@ -8,10 +8,10 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
@Configuration
public class ClientWebConfig extends WebMvcConfigurerAdapter {
public ClientWebConfig() {
super();
}
public ClientWebConfig() {
super();
}
// API
// API
}

View File

@ -17,40 +17,40 @@ import org.springframework.web.servlet.view.JstlView;
//@Configuration
public class ClientWebConfigJava extends WebMvcConfigurerAdapter {
public ClientWebConfigJava() {
super();
}
public ClientWebConfigJava() {
super();
}
@Bean
public MessageSource messageSource() {
@Bean
public MessageSource messageSource() {
final ResourceBundleMessageSource ms = new ResourceBundleMessageSource();
ms.setBasenames("messages");
return ms;
}
final ResourceBundleMessageSource ms = new ResourceBundleMessageSource();
ms.setBasenames("messages");
return ms;
}
@Bean
public ResourceBundle getBeanResourceBundle() {
@Bean
public ResourceBundle getBeanResourceBundle() {
final Locale locale = Locale.getDefault();
return new MessageSourceResourceBundle(messageSource(), locale);
}
final Locale locale = Locale.getDefault();
return new MessageSourceResourceBundle(messageSource(), locale);
}
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
super.addViewControllers(registry);
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
super.addViewControllers(registry);
registry.addViewController("/sample.html");
}
registry.addViewController("/sample.html");
}
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
return bean;
}
return bean;
}
}

View File

@ -18,28 +18,28 @@ import com.baeldung.spring.form.Employee;
@Controller
public class EmployeeController {
Map<Long, Employee> employeeMap = new HashMap<>();
Map<Long, Employee> employeeMap = new HashMap<>();
@RequestMapping(value = "/employee", method = RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView("employeeHome", "employee", new Employee());
}
@RequestMapping(value = "/employee", method = RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView("employeeHome", "employee", new Employee());
}
@RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET)
public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) {
return employeeMap.get(Id);
}
@RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET)
public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) {
return employeeMap.get(Id);
}
@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) {
if (result.hasErrors()) {
return "error";
}
model.addAttribute("name", employee.getName());
model.addAttribute("contactNumber", employee.getContactNumber());
model.addAttribute("id", employee.getId());
employeeMap.put(employee.getId(), employee);
return "employeeView";
}
@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) {
if (result.hasErrors()) {
return "error";
}
model.addAttribute("name", employee.getName());
model.addAttribute("contactNumber", employee.getContactNumber());
model.addAttribute("id", employee.getId());
employeeMap.put(employee.getId(), employee);
return "employeeView";
}
}

View File

@ -11,8 +11,7 @@ public class HelloController extends AbstractController {
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("helloworld");
model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.<br>This request was mapped" +
" using SimpleUrlHandlerMapping.");
model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.<br>This request was mapped" + " using SimpleUrlHandlerMapping.");
return model;
}

View File

@ -10,8 +10,7 @@ public class HelloGuestController extends AbstractController {
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("helloworld");
model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.<br>This request was mapped" +
" using ControllerClassNameHandlerMapping.");
model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.<br>This request was mapped" + " using ControllerClassNameHandlerMapping.");
return model;
}

View File

@ -10,8 +10,7 @@ public class HelloWorldController extends AbstractController {
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("helloworld");
model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.<br>This request was mapped" +
" using BeanNameUrlHandlerMapping.");
model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.<br>This request was mapped" + " using BeanNameUrlHandlerMapping.");
return model;
}

View File

@ -22,63 +22,62 @@ import org.springframework.web.servlet.ModelAndView;
@Controller
public class PersonController {
@Autowired
PersonValidator validator;
@Autowired
PersonValidator validator;
@RequestMapping(value = "/person", method = RequestMethod.GET)
public ModelAndView showForm(final Model model) {
@RequestMapping(value = "/person", method = RequestMethod.GET)
public ModelAndView showForm(final Model model) {
initData(model);
return new ModelAndView("personForm", "person", new Person());
}
initData(model);
return new ModelAndView("personForm", "person", new Person());
}
@RequestMapping(value = "/addPerson", method = RequestMethod.POST)
public String submit(@Valid @ModelAttribute("person") final Person person, final BindingResult result,
final ModelMap modelMap, final Model model) {
@RequestMapping(value = "/addPerson", method = RequestMethod.POST)
public String submit(@Valid @ModelAttribute("person") final Person person, final BindingResult result, final ModelMap modelMap, final Model model) {
validator.validate(person, result);
validator.validate(person, result);
if (result.hasErrors()) {
if (result.hasErrors()) {
initData(model);
return "personForm";
}
initData(model);
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>();
favouriteLanguageItem.add("Java");
favouriteLanguageItem.add("C++");
favouriteLanguageItem.add("Perl");
model.addAttribute("favouriteLanguageItem", favouriteLanguageItem);
final List<String> favouriteLanguageItem = new ArrayList<String>();
favouriteLanguageItem.add("Java");
favouriteLanguageItem.add("C++");
favouriteLanguageItem.add("Perl");
model.addAttribute("favouriteLanguageItem", favouriteLanguageItem);
final List<String> jobItem = new ArrayList<String>();
jobItem.add("Full time");
jobItem.add("Part time");
model.addAttribute("jobItem", jobItem);
final List<String> jobItem = new ArrayList<String>();
jobItem.add("Full time");
jobItem.add("Part time");
model.addAttribute("jobItem", jobItem);
final Map<String, String> countryItems = new LinkedHashMap<String, String>();
countryItems.put("US", "United Stated");
countryItems.put("IT", "Italy");
countryItems.put("UK", "United Kingdom");
countryItems.put("FR", "Grance");
model.addAttribute("countryItems", countryItems);
final Map<String, String> countryItems = new LinkedHashMap<String, String>();
countryItems.put("US", "United Stated");
countryItems.put("IT", "Italy");
countryItems.put("UK", "United Kingdom");
countryItems.put("FR", "Grance");
model.addAttribute("countryItems", countryItems);
final List<String> fruit = new ArrayList<String>();
fruit.add("Banana");
fruit.add("Mango");
fruit.add("Apple");
model.addAttribute("fruit", fruit);
final List<String> fruit = new ArrayList<String>();
fruit.add("Banana");
fruit.add("Mango");
fruit.add("Apple");
model.addAttribute("fruit", fruit);
final List<String> books = new ArrayList<String>();
books.add("The Great Gatsby");
books.add("Nineteen Eighty-Four");
books.add("The Lord of the Rings");
model.addAttribute("books", books);
}
final List<String> books = new ArrayList<String>();
books.add("The Great Gatsby");
books.add("Nineteen Eighty-Four");
books.add("The Lord of the Rings");
model.addAttribute("books", books);
}
}

Some files were not shown because too many files have changed in this diff Show More