From 5a177f3664895d010b38dacbb0e1d2ff30848acd Mon Sep 17 00:00:00 2001 From: Code WellnWill Date: Sat, 5 Jan 2019 11:24:00 +0530 Subject: [PATCH 01/19] Scopes --- .../jm3007/learn/spring/scope/noxml/Bike.java | 14 ++++++++++ .../jm3007/learn/spring/scope/noxml/Car.java | 13 +++++++++ .../learn/spring/scope/noxml/Client.java | 26 ++++++++++++++++++ .../spring/scope/noxml/MyConfiguration.java | 10 +++++++ .../jm3007/learn/spring/scope/xml/Bike.java | 9 +++++++ .../jm3007/learn/spring/scope/xml/Car.java | 8 ++++++ .../jm3007/learn/spring/scope/xml/Client.java | 27 +++++++++++++++++++ .../learn/spring/scope/xml/spring-cfg.xml | 22 +++++++++++++++ 8 files changed, 129 insertions(+) create mode 100644 src/com/jm3007/learn/spring/scope/noxml/Bike.java create mode 100644 src/com/jm3007/learn/spring/scope/noxml/Car.java create mode 100644 src/com/jm3007/learn/spring/scope/noxml/Client.java create mode 100644 src/com/jm3007/learn/spring/scope/noxml/MyConfiguration.java create mode 100644 src/com/jm3007/learn/spring/scope/xml/Bike.java create mode 100644 src/com/jm3007/learn/spring/scope/xml/Car.java create mode 100644 src/com/jm3007/learn/spring/scope/xml/Client.java create mode 100644 src/com/jm3007/learn/spring/scope/xml/spring-cfg.xml diff --git a/src/com/jm3007/learn/spring/scope/noxml/Bike.java b/src/com/jm3007/learn/spring/scope/noxml/Bike.java new file mode 100644 index 0000000..6517774 --- /dev/null +++ b/src/com/jm3007/learn/spring/scope/noxml/Bike.java @@ -0,0 +1,14 @@ +package com.jm3007.learn.spring.scope.noxml; + +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Component +@Scope("prototype") +public class Bike { + + public Bike() { + System.out.println("Bike is being created."); + } + +} diff --git a/src/com/jm3007/learn/spring/scope/noxml/Car.java b/src/com/jm3007/learn/spring/scope/noxml/Car.java new file mode 100644 index 0000000..8d09556 --- /dev/null +++ b/src/com/jm3007/learn/spring/scope/noxml/Car.java @@ -0,0 +1,13 @@ +package com.jm3007.learn.spring.scope.noxml; + +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Component +@Scope("singleton") +public class Car { + + public Car() { + System.out.println("Car is being constructed."); + } +} diff --git a/src/com/jm3007/learn/spring/scope/noxml/Client.java b/src/com/jm3007/learn/spring/scope/noxml/Client.java new file mode 100644 index 0000000..521b77c --- /dev/null +++ b/src/com/jm3007/learn/spring/scope/noxml/Client.java @@ -0,0 +1,26 @@ +package com.jm3007.learn.spring.scope.noxml; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +public class Client { + + public static void main(String[] args) { + ApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class); + Car car1 = (Car) context.getBean("car"); + System.out.println(car1.hashCode()); + + Car car2 = (Car) context.getBean("car"); + System.out.println(car2.hashCode()); + +// Car car3 = new Car(); +// System.out.println(car3.hashCode()); + System.out.println("-------------------------"); + Bike bike1 = (Bike)context.getBean("bike"); + System.out.println(bike1.hashCode()); + + Bike bike2 = (Bike)context.getBean("bike"); + System.out.println(bike2.hashCode()); + } + +} diff --git a/src/com/jm3007/learn/spring/scope/noxml/MyConfiguration.java b/src/com/jm3007/learn/spring/scope/noxml/MyConfiguration.java new file mode 100644 index 0000000..2d9d4b9 --- /dev/null +++ b/src/com/jm3007/learn/spring/scope/noxml/MyConfiguration.java @@ -0,0 +1,10 @@ +package com.jm3007.learn.spring.scope.noxml; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan(basePackages = "com.jm3007.learn.spring.scope.noxml") +public class MyConfiguration { + +} diff --git a/src/com/jm3007/learn/spring/scope/xml/Bike.java b/src/com/jm3007/learn/spring/scope/xml/Bike.java new file mode 100644 index 0000000..02e2e1d --- /dev/null +++ b/src/com/jm3007/learn/spring/scope/xml/Bike.java @@ -0,0 +1,9 @@ +package com.jm3007.learn.spring.scope.xml; + +public class Bike { + + public Bike() { + System.out.println("Bike is being created."); + } + +} diff --git a/src/com/jm3007/learn/spring/scope/xml/Car.java b/src/com/jm3007/learn/spring/scope/xml/Car.java new file mode 100644 index 0000000..ce70e39 --- /dev/null +++ b/src/com/jm3007/learn/spring/scope/xml/Car.java @@ -0,0 +1,8 @@ +package com.jm3007.learn.spring.scope.xml; + +public class Car { + + public Car() { + System.out.println("Car is being constructed."); + } +} diff --git a/src/com/jm3007/learn/spring/scope/xml/Client.java b/src/com/jm3007/learn/spring/scope/xml/Client.java new file mode 100644 index 0000000..9e9f036 --- /dev/null +++ b/src/com/jm3007/learn/spring/scope/xml/Client.java @@ -0,0 +1,27 @@ +package com.jm3007.learn.spring.scope.xml; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class Client { + + public static void main(String[] args) { + ApplicationContext context = new ClassPathXmlApplicationContext( + "com//jm3007//learn//spring//scope//xml//spring-cfg.xml"); + Car car1 = (Car) context.getBean("car"); + System.out.println(car1.hashCode()); + + Car car2 = (Car) context.getBean("car"); + System.out.println(car2.hashCode()); + +// Car car3 = new Car(); +// System.out.println(car3.hashCode()); + System.out.println("-------------------------"); + Bike bike1 = (Bike)context.getBean("bike"); + System.out.println(bike1.hashCode()); + + Bike bike2 = (Bike)context.getBean("bike"); + System.out.println(bike2.hashCode()); + } + +} diff --git a/src/com/jm3007/learn/spring/scope/xml/spring-cfg.xml b/src/com/jm3007/learn/spring/scope/xml/spring-cfg.xml new file mode 100644 index 0000000..41b00e2 --- /dev/null +++ b/src/com/jm3007/learn/spring/scope/xml/spring-cfg.xml @@ -0,0 +1,22 @@ + + + + + + + \ No newline at end of file From ca0369c33b0f66dd9f9d81363f0d30f99af7c92b Mon Sep 17 00:00:00 2001 From: Code WellnWill Date: Sun, 6 Jan 2019 11:27:18 +0530 Subject: [PATCH 02/19] Bean Life cycle --- src/com/jm3007/learn/spring/scope/noxml/Car.java | 13 +++++++++++++ src/com/jm3007/learn/spring/scope/noxml/Client.java | 6 +++++- src/com/jm3007/learn/spring/scope/xml/Client.java | 2 ++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/com/jm3007/learn/spring/scope/noxml/Car.java b/src/com/jm3007/learn/spring/scope/noxml/Car.java index 8d09556..4b74dfd 100644 --- a/src/com/jm3007/learn/spring/scope/noxml/Car.java +++ b/src/com/jm3007/learn/spring/scope/noxml/Car.java @@ -1,5 +1,8 @@ package com.jm3007.learn.spring.scope.noxml; +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; + import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @@ -10,4 +13,14 @@ public class Car { public Car() { System.out.println("Car is being constructed."); } + + @PostConstruct + public void doSomethingAfterBeanIsConstructed() { + System.out.println("Car is constructed successfully."); + } + + @PreDestroy + public void doSomethingBeforeBeanIsDestroyed() { + System.out.println("Car is going to be destroyed."); + } } diff --git a/src/com/jm3007/learn/spring/scope/noxml/Client.java b/src/com/jm3007/learn/spring/scope/noxml/Client.java index 521b77c..dd70128 100644 --- a/src/com/jm3007/learn/spring/scope/noxml/Client.java +++ b/src/com/jm3007/learn/spring/scope/noxml/Client.java @@ -6,7 +6,8 @@ public class Client { public static void main(String[] args) { - ApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class); + Car car1 = (Car) context.getBean("car"); System.out.println(car1.hashCode()); @@ -15,12 +16,15 @@ public static void main(String[] args) { // Car car3 = new Car(); // System.out.println(car3.hashCode()); + System.out.println("-------------------------"); Bike bike1 = (Bike)context.getBean("bike"); System.out.println(bike1.hashCode()); Bike bike2 = (Bike)context.getBean("bike"); System.out.println(bike2.hashCode()); + + context.close(); } } diff --git a/src/com/jm3007/learn/spring/scope/xml/Client.java b/src/com/jm3007/learn/spring/scope/xml/Client.java index 9e9f036..2e409e7 100644 --- a/src/com/jm3007/learn/spring/scope/xml/Client.java +++ b/src/com/jm3007/learn/spring/scope/xml/Client.java @@ -8,6 +8,7 @@ public class Client { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext( "com//jm3007//learn//spring//scope//xml//spring-cfg.xml"); + Car car1 = (Car) context.getBean("car"); System.out.println(car1.hashCode()); @@ -16,6 +17,7 @@ public static void main(String[] args) { // Car car3 = new Car(); // System.out.println(car3.hashCode()); + System.out.println("-------------------------"); Bike bike1 = (Bike)context.getBean("bike"); System.out.println(bike1.hashCode()); From 5112e7c4bd78d6aab6328c0ed29e84e41769f14f Mon Sep 17 00:00:00 2001 From: Code WellnWill Date: Sat, 12 Jan 2019 11:18:47 +0530 Subject: [PATCH 03/19] Misc concepts --- src/com/jm3007/learn/spring/di/xml/Car.java | 2 ++ .../jm3007/learn/spring/di/xml/CarApp.java | 18 ++++++++++- .../jm3007/learn/spring/di/xml/spring-cfg.xml | 32 ++++++++++--------- .../jm3007/learn/spring/scope/xml/Car.java | 8 +++++ .../jm3007/learn/spring/scope/xml/Client.java | 5 ++- .../learn/spring/scope/xml/spring-cfg.xml | 2 +- src/experiment/HashCodeEqualsContract.java | 20 ++++++++++++ 7 files changed, 69 insertions(+), 18 deletions(-) create mode 100644 src/experiment/HashCodeEqualsContract.java diff --git a/src/com/jm3007/learn/spring/di/xml/Car.java b/src/com/jm3007/learn/spring/di/xml/Car.java index 73f910d..ab501ec 100644 --- a/src/com/jm3007/learn/spring/di/xml/Car.java +++ b/src/com/jm3007/learn/spring/di/xml/Car.java @@ -21,4 +21,6 @@ public void setEngine(Engine engine) { System.out.println("Putting engine in car."); this.engine = engine; } + + } diff --git a/src/com/jm3007/learn/spring/di/xml/CarApp.java b/src/com/jm3007/learn/spring/di/xml/CarApp.java index b87dafc..9ffbeee 100644 --- a/src/com/jm3007/learn/spring/di/xml/CarApp.java +++ b/src/com/jm3007/learn/spring/di/xml/CarApp.java @@ -9,10 +9,26 @@ public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext( "com/jm3007/learn/spring/di/xml/spring-cfg.xml"); + System.out.println("---------------"); + Engine engine = (Engine) context.getBean("engine"); + System.out.println(engine.hashCode()); Car car = (Car) context.getBean("car"); - car.driveTheCar(); +// car.driveTheCar(); + System.out.println("-------------"); + System.out.println(car.hashCode()); + System.out.println(car.getEngine().hashCode()); + + Car car2 = (Car) context.getBean("car"); + System.out.println("-------------"); + System.out.println(car2.hashCode()); + System.out.println(car2.getEngine().hashCode()); + + System.out.println("---------------"); + Engine engine2 = (Engine) context.getBean("engine"); + System.out.println(engine2.hashCode()); + } } diff --git a/src/com/jm3007/learn/spring/di/xml/spring-cfg.xml b/src/com/jm3007/learn/spring/di/xml/spring-cfg.xml index 95aa9c2..24fc206 100644 --- a/src/com/jm3007/learn/spring/di/xml/spring-cfg.xml +++ b/src/com/jm3007/learn/spring/di/xml/spring-cfg.xml @@ -16,22 +16,24 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> - + - + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/com/jm3007/learn/spring/scope/xml/Car.java b/src/com/jm3007/learn/spring/scope/xml/Car.java index ce70e39..b44e510 100644 --- a/src/com/jm3007/learn/spring/scope/xml/Car.java +++ b/src/com/jm3007/learn/spring/scope/xml/Car.java @@ -5,4 +5,12 @@ public class Car { public Car() { System.out.println("Car is being constructed."); } + + public void mysdnkksn() { + System.out.println("I'm ruuning after post construct..."); + } + + public void cleanUp() { + System.out.println("Clean up"); + } } diff --git a/src/com/jm3007/learn/spring/scope/xml/Client.java b/src/com/jm3007/learn/spring/scope/xml/Client.java index 2e409e7..c58d8cd 100644 --- a/src/com/jm3007/learn/spring/scope/xml/Client.java +++ b/src/com/jm3007/learn/spring/scope/xml/Client.java @@ -1,12 +1,13 @@ package com.jm3007.learn.spring.scope.xml; import org.springframework.context.ApplicationContext; +import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Client { public static void main(String[] args) { - ApplicationContext context = new ClassPathXmlApplicationContext( + ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( "com//jm3007//learn//spring//scope//xml//spring-cfg.xml"); Car car1 = (Car) context.getBean("car"); @@ -24,6 +25,8 @@ public static void main(String[] args) { Bike bike2 = (Bike)context.getBean("bike"); System.out.println(bike2.hashCode()); + + context.close(); } } diff --git a/src/com/jm3007/learn/spring/scope/xml/spring-cfg.xml b/src/com/jm3007/learn/spring/scope/xml/spring-cfg.xml index 41b00e2..1edd6ab 100644 --- a/src/com/jm3007/learn/spring/scope/xml/spring-cfg.xml +++ b/src/com/jm3007/learn/spring/scope/xml/spring-cfg.xml @@ -16,7 +16,7 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> - + \ No newline at end of file diff --git a/src/experiment/HashCodeEqualsContract.java b/src/experiment/HashCodeEqualsContract.java new file mode 100644 index 0000000..886956e --- /dev/null +++ b/src/experiment/HashCodeEqualsContract.java @@ -0,0 +1,20 @@ +package experiment; + +public class HashCodeEqualsContract { + public static void main(String[] args) { + HashCodeEqualsContract obj1 = new HashCodeEqualsContract(); + System.out.println(obj1); + System.out.println(obj1.hashCode()); + + System.out.println("------------"); + HashCodeEqualsContract obj2 = new HashCodeEqualsContract(); + System.out.println(obj2); + System.out.println(obj2.hashCode()); + + System.out.println("------------"); + System.out.println(obj1 == obj2); + + System.out.println("------------"); + System.out.println(obj1.equals(obj2)); + } +} From d4994113b3aff46d09691d1f58bf3efbb3de1b50 Mon Sep 17 00:00:00 2001 From: Code WellnWill Date: Sat, 12 Jan 2019 11:34:55 +0530 Subject: [PATCH 04/19] converted to Dynamic Web project --- WebContent/META-INF/MANIFEST.MF | 3 +++ WebContent/WEB-INF/web.xml | 12 ++++++++++++ WebContent/index.html | 10 ++++++++++ pom.xml | 8 ++++++++ 4 files changed, 33 insertions(+) create mode 100644 WebContent/META-INF/MANIFEST.MF create mode 100644 WebContent/WEB-INF/web.xml create mode 100644 WebContent/index.html diff --git a/WebContent/META-INF/MANIFEST.MF b/WebContent/META-INF/MANIFEST.MF new file mode 100644 index 0000000..5e94951 --- /dev/null +++ b/WebContent/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/WebContent/WEB-INF/web.xml b/WebContent/WEB-INF/web.xml new file mode 100644 index 0000000..2a6b7d1 --- /dev/null +++ b/WebContent/WEB-INF/web.xml @@ -0,0 +1,12 @@ + + + JM3007 + + index.html + index.htm + index.jsp + default.html + default.htm + default.jsp + + \ No newline at end of file diff --git a/WebContent/index.html b/WebContent/index.html new file mode 100644 index 0000000..3b926a8 --- /dev/null +++ b/WebContent/index.html @@ -0,0 +1,10 @@ + + + + +Welcome!! + + +

Welcome.....

+ + \ No newline at end of file diff --git a/pom.xml b/pom.xml index 6cc341c..b8218ff 100644 --- a/pom.xml +++ b/pom.xml @@ -6,6 +6,7 @@ learn 0.0.1-SNAPSHOT JM3007 + war Learning Java Frameworks @@ -29,6 +30,13 @@ 1.8 + + maven-war-plugin + 3.2.1 + + WebContent + + \ No newline at end of file From e984645ad4e433ec080c4a58a8c683d5d68b3528 Mon Sep 17 00:00:00 2001 From: Code WellnWill Date: Sun, 13 Jan 2019 19:56:50 +0530 Subject: [PATCH 05/19] First Controller --- WebContent/WEB-INF/spring-config.xml | 28 +++++++++++++++++++ WebContent/WEB-INF/view/home.jsp | 12 ++++++++ WebContent/WEB-INF/web.xml | 14 ++++++++++ WebContent/index.html | 10 ------- pom.xml | 4 +-- .../learn/spring/web/HomeController.java | 20 +++++++++++++ 6 files changed, 76 insertions(+), 12 deletions(-) create mode 100644 WebContent/WEB-INF/spring-config.xml create mode 100644 WebContent/WEB-INF/view/home.jsp delete mode 100644 WebContent/index.html create mode 100644 src/com/jm3007/learn/spring/web/HomeController.java diff --git a/WebContent/WEB-INF/spring-config.xml b/WebContent/WEB-INF/spring-config.xml new file mode 100644 index 0000000..823bc77 --- /dev/null +++ b/WebContent/WEB-INF/spring-config.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/WebContent/WEB-INF/view/home.jsp b/WebContent/WEB-INF/view/home.jsp new file mode 100644 index 0000000..5e50e2b --- /dev/null +++ b/WebContent/WEB-INF/view/home.jsp @@ -0,0 +1,12 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Welcome!!! + + +

I'm here............. Ok

+ + \ No newline at end of file diff --git a/WebContent/WEB-INF/web.xml b/WebContent/WEB-INF/web.xml index 2a6b7d1..22ee770 100644 --- a/WebContent/WEB-INF/web.xml +++ b/WebContent/WEB-INF/web.xml @@ -9,4 +9,18 @@ default.htm default.jsp + + + dispatcher + org.springframework.web.servlet.DispatcherServlet + + contextConfigLocation + /WEB-INF/spring-config.xml + + + + + dispatcher + / + \ No newline at end of file diff --git a/WebContent/index.html b/WebContent/index.html deleted file mode 100644 index 3b926a8..0000000 --- a/WebContent/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - -Welcome!! - - -

Welcome.....

- - \ No newline at end of file diff --git a/pom.xml b/pom.xml index b8218ff..2733012 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.jm3007 - learn + JM3007 0.0.1-SNAPSHOT JM3007 war @@ -12,7 +12,7 @@ org.springframework - spring-context + spring-webmvc 5.1.3.RELEASE diff --git a/src/com/jm3007/learn/spring/web/HomeController.java b/src/com/jm3007/learn/spring/web/HomeController.java new file mode 100644 index 0000000..2eae058 --- /dev/null +++ b/src/com/jm3007/learn/spring/web/HomeController.java @@ -0,0 +1,20 @@ +package com.jm3007.learn.spring.web; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@Controller +public class HomeController { + + @RequestMapping(value = "/", method = RequestMethod.GET) + public String showHomePage() { + return "home"; + } + + @RequestMapping(value = "/login", method = RequestMethod.GET) + public String ffklmnalkf() { + System.out.println("Isdmlkdsmfl"); + return "home"; + } +} From 1f8dc8866ddb3efc26c910e4d4f9205b9771f1c3 Mon Sep 17 00:00:00 2001 From: Code WellnWill Date: Tue, 15 Jan 2019 11:48:19 +0530 Subject: [PATCH 06/19] Revision --- .../spring/revision/annotationway/AirBag.java | 15 ++++++++ .../spring/revision/annotationway/Car.java | 36 +++++++++++++++++++ .../spring/revision/annotationway/Client.java | 13 +++++++ .../spring/revision/annotationway/Engine.java | 15 ++++++++ .../revision/annotationway/MusicSystem.java | 15 ++++++++ .../revision/annotationway/SrpingConfig.java | 8 +++++ 6 files changed, 102 insertions(+) create mode 100644 src/com/jm3007/learn/spring/revision/annotationway/AirBag.java create mode 100644 src/com/jm3007/learn/spring/revision/annotationway/Car.java create mode 100644 src/com/jm3007/learn/spring/revision/annotationway/Client.java create mode 100644 src/com/jm3007/learn/spring/revision/annotationway/Engine.java create mode 100644 src/com/jm3007/learn/spring/revision/annotationway/MusicSystem.java create mode 100644 src/com/jm3007/learn/spring/revision/annotationway/SrpingConfig.java diff --git a/src/com/jm3007/learn/spring/revision/annotationway/AirBag.java b/src/com/jm3007/learn/spring/revision/annotationway/AirBag.java new file mode 100644 index 0000000..b0cf913 --- /dev/null +++ b/src/com/jm3007/learn/spring/revision/annotationway/AirBag.java @@ -0,0 +1,15 @@ +package com.jm3007.learn.spring.revision.annotationway; + +import org.springframework.stereotype.Component; + +@Component +public class AirBag { + + public AirBag() { + System.out.println("AirBag is bieng constructed..."); + } + + public void acivate() { + System.out.println("AirBag has been activated."); + } +} diff --git a/src/com/jm3007/learn/spring/revision/annotationway/Car.java b/src/com/jm3007/learn/spring/revision/annotationway/Car.java new file mode 100644 index 0000000..ec89f5b --- /dev/null +++ b/src/com/jm3007/learn/spring/revision/annotationway/Car.java @@ -0,0 +1,36 @@ +package com.jm3007.learn.spring.revision.annotationway; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component("myCar") +public class Car { + + private Engine engine; + + // dependency injection - thru field + @Autowired + private MusicSystem musicSystem; + + private AirBag airBag; + + // dependency injection - thru constructor + @Autowired + public Car(Engine engine) { + this.engine = engine; + System.out.println("Car is being constructed..."); + } + + public void driveTheCar() { + engine.start(); + airBag.acivate(); + System.out.println("Driving the car."); + musicSystem.playMusic(); + } + + // dependency injection - thru setter + @Autowired + public void setAirBag(AirBag airBag) { + this.airBag = airBag; + } +} diff --git a/src/com/jm3007/learn/spring/revision/annotationway/Client.java b/src/com/jm3007/learn/spring/revision/annotationway/Client.java new file mode 100644 index 0000000..52b6cee --- /dev/null +++ b/src/com/jm3007/learn/spring/revision/annotationway/Client.java @@ -0,0 +1,13 @@ +package com.jm3007.learn.spring.revision.annotationway; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +public class Client { + public static void main(String[] args) { +// Car car = new Car(); + ApplicationContext context = new AnnotationConfigApplicationContext(SrpingConfig.class); + Car car = (Car) context.getBean("myCar"); + car.driveTheCar(); + } +} diff --git a/src/com/jm3007/learn/spring/revision/annotationway/Engine.java b/src/com/jm3007/learn/spring/revision/annotationway/Engine.java new file mode 100644 index 0000000..6dd53ce --- /dev/null +++ b/src/com/jm3007/learn/spring/revision/annotationway/Engine.java @@ -0,0 +1,15 @@ +package com.jm3007.learn.spring.revision.annotationway; + +import org.springframework.stereotype.Component; + +@Component +public class Engine { + + public Engine() { + System.out.println("Engine is being constructed..."); + } + + public void start() { + System.out.println("Engine started."); + } +} diff --git a/src/com/jm3007/learn/spring/revision/annotationway/MusicSystem.java b/src/com/jm3007/learn/spring/revision/annotationway/MusicSystem.java new file mode 100644 index 0000000..b62d9ff --- /dev/null +++ b/src/com/jm3007/learn/spring/revision/annotationway/MusicSystem.java @@ -0,0 +1,15 @@ +package com.jm3007.learn.spring.revision.annotationway; + +import org.springframework.stereotype.Component; + +@Component +public class MusicSystem { + + public MusicSystem() { + System.out.println("MusicSystem is being constructed..."); + } + + public void playMusic() { + System.out.println("Playing music."); + } +} diff --git a/src/com/jm3007/learn/spring/revision/annotationway/SrpingConfig.java b/src/com/jm3007/learn/spring/revision/annotationway/SrpingConfig.java new file mode 100644 index 0000000..02433ba --- /dev/null +++ b/src/com/jm3007/learn/spring/revision/annotationway/SrpingConfig.java @@ -0,0 +1,8 @@ +package com.jm3007.learn.spring.revision.annotationway; + +import org.springframework.context.annotation.ComponentScan; + +@ComponentScan(basePackages = "com.jm3007.learn.spring.revision.annotationway") +public class SrpingConfig { + +} From 982664ccb771ad12caec70e89492eaf201b569c6 Mon Sep 17 00:00:00 2001 From: Code WellnWill Date: Tue, 15 Jan 2019 12:03:44 +0530 Subject: [PATCH 07/19] DIP --- .../learn/spring/revision/annotationway/Car.java | 2 ++ .../revision/annotationway/MusicSystem.java | 14 ++------------ .../annotationway/PhilipsMusicSystem.java | 16 ++++++++++++++++ .../revision/annotationway/SonyMusicSystem.java | 16 ++++++++++++++++ 4 files changed, 36 insertions(+), 12 deletions(-) create mode 100644 src/com/jm3007/learn/spring/revision/annotationway/PhilipsMusicSystem.java create mode 100644 src/com/jm3007/learn/spring/revision/annotationway/SonyMusicSystem.java diff --git a/src/com/jm3007/learn/spring/revision/annotationway/Car.java b/src/com/jm3007/learn/spring/revision/annotationway/Car.java index ec89f5b..d51bd4f 100644 --- a/src/com/jm3007/learn/spring/revision/annotationway/Car.java +++ b/src/com/jm3007/learn/spring/revision/annotationway/Car.java @@ -1,6 +1,7 @@ package com.jm3007.learn.spring.revision.annotationway; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; @Component("myCar") @@ -9,6 +10,7 @@ public class Car { private Engine engine; // dependency injection - thru field + @Qualifier("sony") @Autowired private MusicSystem musicSystem; diff --git a/src/com/jm3007/learn/spring/revision/annotationway/MusicSystem.java b/src/com/jm3007/learn/spring/revision/annotationway/MusicSystem.java index b62d9ff..56ab24a 100644 --- a/src/com/jm3007/learn/spring/revision/annotationway/MusicSystem.java +++ b/src/com/jm3007/learn/spring/revision/annotationway/MusicSystem.java @@ -1,15 +1,5 @@ package com.jm3007.learn.spring.revision.annotationway; -import org.springframework.stereotype.Component; - -@Component -public class MusicSystem { - - public MusicSystem() { - System.out.println("MusicSystem is being constructed..."); - } - - public void playMusic() { - System.out.println("Playing music."); - } +public interface MusicSystem { + public void playMusic(); } diff --git a/src/com/jm3007/learn/spring/revision/annotationway/PhilipsMusicSystem.java b/src/com/jm3007/learn/spring/revision/annotationway/PhilipsMusicSystem.java new file mode 100644 index 0000000..9e635f8 --- /dev/null +++ b/src/com/jm3007/learn/spring/revision/annotationway/PhilipsMusicSystem.java @@ -0,0 +1,16 @@ +package com.jm3007.learn.spring.revision.annotationway; + +import org.springframework.stereotype.Component; + +@Component("philips") +public class PhilipsMusicSystem implements MusicSystem { + + public PhilipsMusicSystem() { + System.out.println(this.getClass().getSimpleName() + " is being constructued."); + } + + public void playMusic() { + System.out.println("Playing music on " + this.getClass().getSimpleName()); + } + +} diff --git a/src/com/jm3007/learn/spring/revision/annotationway/SonyMusicSystem.java b/src/com/jm3007/learn/spring/revision/annotationway/SonyMusicSystem.java new file mode 100644 index 0000000..a958fc0 --- /dev/null +++ b/src/com/jm3007/learn/spring/revision/annotationway/SonyMusicSystem.java @@ -0,0 +1,16 @@ +package com.jm3007.learn.spring.revision.annotationway; + +import org.springframework.stereotype.Component; + +@Component("sony") +public class SonyMusicSystem implements MusicSystem { + + public SonyMusicSystem() { + System.out.println(this.getClass().getSimpleName() + " is being constructued."); + } + + public void playMusic() { + System.out.println("Playing music on " + this.getClass().getSimpleName()); + } + +} From a3f9099345b5b62dd21a1872abe1be254bbcb119 Mon Sep 17 00:00:00 2001 From: Code WellnWill Date: Tue, 15 Jan 2019 12:10:15 +0530 Subject: [PATCH 08/19] Beans Scope --- .../learn/spring/revision/annotationway/Car.java | 3 +++ .../spring/revision/annotationway/Client.java | 14 ++++++++++++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/com/jm3007/learn/spring/revision/annotationway/Car.java b/src/com/jm3007/learn/spring/revision/annotationway/Car.java index d51bd4f..665b50c 100644 --- a/src/com/jm3007/learn/spring/revision/annotationway/Car.java +++ b/src/com/jm3007/learn/spring/revision/annotationway/Car.java @@ -2,9 +2,12 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Component("myCar") +//@Scope("singleton") +@Scope("prototype") public class Car { private Engine engine; diff --git a/src/com/jm3007/learn/spring/revision/annotationway/Client.java b/src/com/jm3007/learn/spring/revision/annotationway/Client.java index 52b6cee..8797a91 100644 --- a/src/com/jm3007/learn/spring/revision/annotationway/Client.java +++ b/src/com/jm3007/learn/spring/revision/annotationway/Client.java @@ -7,7 +7,17 @@ public class Client { public static void main(String[] args) { // Car car = new Car(); ApplicationContext context = new AnnotationConfigApplicationContext(SrpingConfig.class); - Car car = (Car) context.getBean("myCar"); - car.driveTheCar(); + Car car1 = (Car) context.getBean("myCar"); + car1.driveTheCar(); + + + Car car2 = (Car) context.getBean("myCar"); + + + System.out.println("--------------"); + System.out.println(car1.hashCode()); + System.out.println(car2.hashCode()); + + } } From 4b5f9a8433fa03bbd70eacf0b3d47e65ff043dd2 Mon Sep 17 00:00:00 2001 From: Code WellnWill Date: Tue, 15 Jan 2019 12:32:46 +0530 Subject: [PATCH 09/19] XML way --- .../learn/spring/revision/xmlway/AirBag.java | 12 ++++++ .../learn/spring/revision/xmlway/Car.java | 30 +++++++++++++ .../learn/spring/revision/xmlway/Client.java | 21 ++++++++++ .../learn/spring/revision/xmlway/Engine.java | 12 ++++++ .../spring/revision/xmlway/MusicSystem.java | 5 +++ .../revision/xmlway/PhilipsMusicSystem.java | 13 ++++++ .../revision/xmlway/SonyMusicSystem.java | 13 ++++++ .../spring/revision/xmlway/spring-cfg.xml | 42 +++++++++++++++++++ 8 files changed, 148 insertions(+) create mode 100644 src/com/jm3007/learn/spring/revision/xmlway/AirBag.java create mode 100644 src/com/jm3007/learn/spring/revision/xmlway/Car.java create mode 100644 src/com/jm3007/learn/spring/revision/xmlway/Client.java create mode 100644 src/com/jm3007/learn/spring/revision/xmlway/Engine.java create mode 100644 src/com/jm3007/learn/spring/revision/xmlway/MusicSystem.java create mode 100644 src/com/jm3007/learn/spring/revision/xmlway/PhilipsMusicSystem.java create mode 100644 src/com/jm3007/learn/spring/revision/xmlway/SonyMusicSystem.java create mode 100644 src/com/jm3007/learn/spring/revision/xmlway/spring-cfg.xml diff --git a/src/com/jm3007/learn/spring/revision/xmlway/AirBag.java b/src/com/jm3007/learn/spring/revision/xmlway/AirBag.java new file mode 100644 index 0000000..b41adc6 --- /dev/null +++ b/src/com/jm3007/learn/spring/revision/xmlway/AirBag.java @@ -0,0 +1,12 @@ +package com.jm3007.learn.spring.revision.xmlway; + +public class AirBag { + + public AirBag() { + System.out.println("AirBag is bieng constructed..."); + } + + public void acivate() { + System.out.println("AirBag has been activated."); + } +} diff --git a/src/com/jm3007/learn/spring/revision/xmlway/Car.java b/src/com/jm3007/learn/spring/revision/xmlway/Car.java new file mode 100644 index 0000000..5bd05c1 --- /dev/null +++ b/src/com/jm3007/learn/spring/revision/xmlway/Car.java @@ -0,0 +1,30 @@ +package com.jm3007.learn.spring.revision.xmlway; + +public class Car { + + private Engine engine; + + private AirBag airBag; + + private MusicSystem musicSystem; + + public void setMusicSystem(MusicSystem musicSystem) { + this.musicSystem = musicSystem; + } + + public Car(Engine engine) { + this.engine = engine; + System.out.println("Car is being constructed..."); + } + + public void driveTheCar() { + engine.start(); + airBag.acivate(); + System.out.println("Driving the car."); + musicSystem.playMusic(); + } + + public void setAirBag(AirBag airBag) { + this.airBag = airBag; + } +} diff --git a/src/com/jm3007/learn/spring/revision/xmlway/Client.java b/src/com/jm3007/learn/spring/revision/xmlway/Client.java new file mode 100644 index 0000000..ccc7cc6 --- /dev/null +++ b/src/com/jm3007/learn/spring/revision/xmlway/Client.java @@ -0,0 +1,21 @@ +package com.jm3007.learn.spring.revision.xmlway; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class Client { + public static void main(String[] args) { + ApplicationContext context = new ClassPathXmlApplicationContext( + "com/jm3007/learn/spring/revision/xmlway/spring-cfg.xml"); + + Car car1 = (Car) context.getBean("car"); + car1.driveTheCar(); + + Car car2 = (Car) context.getBean("car"); + + System.out.println("----------------"); + System.out.println(car1.hashCode()); + System.out.println(car2.hashCode()); + + } +} diff --git a/src/com/jm3007/learn/spring/revision/xmlway/Engine.java b/src/com/jm3007/learn/spring/revision/xmlway/Engine.java new file mode 100644 index 0000000..b7a4eb9 --- /dev/null +++ b/src/com/jm3007/learn/spring/revision/xmlway/Engine.java @@ -0,0 +1,12 @@ +package com.jm3007.learn.spring.revision.xmlway; + +public class Engine { + + public Engine() { + System.out.println("Engine is being constructed..."); + } + + public void start() { + System.out.println("Engine started."); + } +} diff --git a/src/com/jm3007/learn/spring/revision/xmlway/MusicSystem.java b/src/com/jm3007/learn/spring/revision/xmlway/MusicSystem.java new file mode 100644 index 0000000..83110fc --- /dev/null +++ b/src/com/jm3007/learn/spring/revision/xmlway/MusicSystem.java @@ -0,0 +1,5 @@ +package com.jm3007.learn.spring.revision.xmlway; + +public interface MusicSystem { + public void playMusic(); +} diff --git a/src/com/jm3007/learn/spring/revision/xmlway/PhilipsMusicSystem.java b/src/com/jm3007/learn/spring/revision/xmlway/PhilipsMusicSystem.java new file mode 100644 index 0000000..a505110 --- /dev/null +++ b/src/com/jm3007/learn/spring/revision/xmlway/PhilipsMusicSystem.java @@ -0,0 +1,13 @@ +package com.jm3007.learn.spring.revision.xmlway; + +public class PhilipsMusicSystem implements MusicSystem { + + public PhilipsMusicSystem() { + System.out.println(this.getClass().getSimpleName() + " is being constructued."); + } + + public void playMusic() { + System.out.println("Playing music on " + this.getClass().getSimpleName()); + } + +} diff --git a/src/com/jm3007/learn/spring/revision/xmlway/SonyMusicSystem.java b/src/com/jm3007/learn/spring/revision/xmlway/SonyMusicSystem.java new file mode 100644 index 0000000..e20c714 --- /dev/null +++ b/src/com/jm3007/learn/spring/revision/xmlway/SonyMusicSystem.java @@ -0,0 +1,13 @@ +package com.jm3007.learn.spring.revision.xmlway; + +public class SonyMusicSystem implements MusicSystem { + + public SonyMusicSystem() { + System.out.println(this.getClass().getSimpleName() + " is being constructued."); + } + + public void playMusic() { + System.out.println("Playing music on " + this.getClass().getSimpleName()); + } + +} diff --git a/src/com/jm3007/learn/spring/revision/xmlway/spring-cfg.xml b/src/com/jm3007/learn/spring/revision/xmlway/spring-cfg.xml new file mode 100644 index 0000000..7b8259b --- /dev/null +++ b/src/com/jm3007/learn/spring/revision/xmlway/spring-cfg.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file From c811364c05199fe763f35b92cdbe1be5648ef679 Mon Sep 17 00:00:00 2001 From: Code WellnWill Date: Tue, 15 Jan 2019 12:47:29 +0530 Subject: [PATCH 10/19] SpEL --- src/car.properties | 2 +- .../spring/revision/annotationway/Car.java | 9 ++++++++- .../revision/annotationway/SrpingConfig.java | 2 ++ .../learn/spring/revision/xmlway/Car.java | 18 +++++++++++++++--- .../spring/revision/xmlway/spring-cfg.xml | 13 +++++++++---- 5 files changed, 35 insertions(+), 9 deletions(-) diff --git a/src/car.properties b/src/car.properties index 01d7180..6369f6f 100644 --- a/src/car.properties +++ b/src/car.properties @@ -1,2 +1,2 @@ color=Green -speed=200 \ No newline at end of file +speed=100 \ No newline at end of file diff --git a/src/com/jm3007/learn/spring/revision/annotationway/Car.java b/src/com/jm3007/learn/spring/revision/annotationway/Car.java index 665b50c..3959db9 100644 --- a/src/com/jm3007/learn/spring/revision/annotationway/Car.java +++ b/src/com/jm3007/learn/spring/revision/annotationway/Car.java @@ -2,6 +2,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @@ -10,6 +11,12 @@ @Scope("prototype") public class Car { + @Value("${color}") + private String color; + + @Value("${speed}") + private double speed; + private Engine engine; // dependency injection - thru field @@ -29,7 +36,7 @@ public Car(Engine engine) { public void driveTheCar() { engine.start(); airBag.acivate(); - System.out.println("Driving the car."); + System.out.println("Driving the " + color + " car at speed of " + speed + " KM/H."); musicSystem.playMusic(); } diff --git a/src/com/jm3007/learn/spring/revision/annotationway/SrpingConfig.java b/src/com/jm3007/learn/spring/revision/annotationway/SrpingConfig.java index 02433ba..ef6bf7e 100644 --- a/src/com/jm3007/learn/spring/revision/annotationway/SrpingConfig.java +++ b/src/com/jm3007/learn/spring/revision/annotationway/SrpingConfig.java @@ -1,8 +1,10 @@ package com.jm3007.learn.spring.revision.annotationway; import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.PropertySource; @ComponentScan(basePackages = "com.jm3007.learn.spring.revision.annotationway") +@PropertySource(value = "classpath:car.properties") public class SrpingConfig { } diff --git a/src/com/jm3007/learn/spring/revision/xmlway/Car.java b/src/com/jm3007/learn/spring/revision/xmlway/Car.java index 5bd05c1..80aea42 100644 --- a/src/com/jm3007/learn/spring/revision/xmlway/Car.java +++ b/src/com/jm3007/learn/spring/revision/xmlway/Car.java @@ -2,10 +2,18 @@ public class Car { + private String color; + + private double speed; + + public void setSpeed(double speed) { + this.speed = speed; + } + private Engine engine; - + private AirBag airBag; - + private MusicSystem musicSystem; public void setMusicSystem(MusicSystem musicSystem) { @@ -20,10 +28,14 @@ public Car(Engine engine) { public void driveTheCar() { engine.start(); airBag.acivate(); - System.out.println("Driving the car."); + System.out.println("Driving the " + color + " car at speed of " + speed + " KM/H."); musicSystem.playMusic(); } + public void setColor(String color) { + this.color = color; + } + public void setAirBag(AirBag airBag) { this.airBag = airBag; } diff --git a/src/com/jm3007/learn/spring/revision/xmlway/spring-cfg.xml b/src/com/jm3007/learn/spring/revision/xmlway/spring-cfg.xml index 7b8259b..cbf171e 100644 --- a/src/com/jm3007/learn/spring/revision/xmlway/spring-cfg.xml +++ b/src/com/jm3007/learn/spring/revision/xmlway/spring-cfg.xml @@ -16,11 +16,16 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> + + + + - - - - \ No newline at end of file From ae407c0eb9126bdd660717281c681a43c2d96f3f Mon Sep 17 00:00:00 2001 From: Code WellnWill Date: Sat, 19 Jan 2019 12:26:41 +0530 Subject: [PATCH 11/19] Spring MVC --- WebContent/WEB-INF/view/home.jsp | 4 + WebContent/WEB-INF/view/login.jsp | 16 ++++ WebContent/WEB-INF/view/user-profile.jsp | 18 +++++ WebContent/WEB-INF/view/user-registration.jsp | 57 +++++++++++++++ .../learn/spring/web/HomeController.java | 6 -- .../learn/spring/web/ItemController.java | 29 ++++++++ .../learn/spring/web/LoginController.java | 47 ++++++++++++ src/com/jm3007/learn/spring/web/User.java | 73 +++++++++++++++++++ .../learn/spring/web/UserController.java | 24 ++++++ 9 files changed, 268 insertions(+), 6 deletions(-) create mode 100644 WebContent/WEB-INF/view/login.jsp create mode 100644 WebContent/WEB-INF/view/user-profile.jsp create mode 100644 WebContent/WEB-INF/view/user-registration.jsp create mode 100644 src/com/jm3007/learn/spring/web/ItemController.java create mode 100644 src/com/jm3007/learn/spring/web/LoginController.java create mode 100644 src/com/jm3007/learn/spring/web/User.java create mode 100644 src/com/jm3007/learn/spring/web/UserController.java diff --git a/WebContent/WEB-INF/view/home.jsp b/WebContent/WEB-INF/view/home.jsp index 5e50e2b..704cb09 100644 --- a/WebContent/WEB-INF/view/home.jsp +++ b/WebContent/WEB-INF/view/home.jsp @@ -8,5 +8,9 @@

I'm here............. Ok

+Login + +

Users

+Register \ No newline at end of file diff --git a/WebContent/WEB-INF/view/login.jsp b/WebContent/WEB-INF/view/login.jsp new file mode 100644 index 0000000..960616d --- /dev/null +++ b/WebContent/WEB-INF/view/login.jsp @@ -0,0 +1,16 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Login page + + +
+ +
+ + \ No newline at end of file diff --git a/WebContent/WEB-INF/view/user-profile.jsp b/WebContent/WEB-INF/view/user-profile.jsp new file mode 100644 index 0000000..c80cfa1 --- /dev/null +++ b/WebContent/WEB-INF/view/user-profile.jsp @@ -0,0 +1,18 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +User Profile + + + ${user.name} +
${user.age} +
${user.gender} +
${user.country} +
${user.courses} +
${user.graduated} +
${user.feedback} + + \ No newline at end of file diff --git a/WebContent/WEB-INF/view/user-registration.jsp b/WebContent/WEB-INF/view/user-registration.jsp new file mode 100644 index 0000000..e1415d6 --- /dev/null +++ b/WebContent/WEB-INF/view/user-registration.jsp @@ -0,0 +1,57 @@ +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> + + + + +User Registration Form + + +

${msg}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Name
Age
Gender Male   + Female
Country + + + +
Courses + Core Java   + Advance Java   + Java Frameworks   +
Are you graduate?
Feedback
+ +
+ + \ No newline at end of file diff --git a/src/com/jm3007/learn/spring/web/HomeController.java b/src/com/jm3007/learn/spring/web/HomeController.java index 2eae058..da020c5 100644 --- a/src/com/jm3007/learn/spring/web/HomeController.java +++ b/src/com/jm3007/learn/spring/web/HomeController.java @@ -11,10 +11,4 @@ public class HomeController { public String showHomePage() { return "home"; } - - @RequestMapping(value = "/login", method = RequestMethod.GET) - public String ffklmnalkf() { - System.out.println("Isdmlkdsmfl"); - return "home"; - } } diff --git a/src/com/jm3007/learn/spring/web/ItemController.java b/src/com/jm3007/learn/spring/web/ItemController.java new file mode 100644 index 0000000..a393f08 --- /dev/null +++ b/src/com/jm3007/learn/spring/web/ItemController.java @@ -0,0 +1,29 @@ +package com.jm3007.learn.spring.web; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +@RequestMapping("/items") +public class ItemController { + + private Map items = new HashMap<>(); + + public ItemController() { + items.put("1001", "Item One"); + items.put("1002", "Item Two"); + items.put("1003", "Item Three"); + items.put("1004", "Item Four"); + } + + @RequestMapping(value = "/name/{id}/fun", method = RequestMethod.GET) + public @ResponseBody String getItemNameById(@PathVariable("id") String myId) { + return items.get(myId); + } +} diff --git a/src/com/jm3007/learn/spring/web/LoginController.java b/src/com/jm3007/learn/spring/web/LoginController.java new file mode 100644 index 0000000..43884a3 --- /dev/null +++ b/src/com/jm3007/learn/spring/web/LoginController.java @@ -0,0 +1,47 @@ +package com.jm3007.learn.spring.web; + +import javax.servlet.http.HttpServletRequest; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +public class LoginController { + + @RequestMapping(value = "/login", method = RequestMethod.GET) + public String showLoginPage() { + return "login"; + } + + @RequestMapping(value = "/login", method = RequestMethod.POST) + public @ResponseBody String processLogin(HttpServletRequest request) { + String un = request.getParameter("username"); + String pass = request.getParameter("password"); + if (un.equalsIgnoreCase(pass)) { + return "Welcome, " + un; + } + return "Login failed."; + } + + @RequestMapping(value = "/loginSpringWay", method = RequestMethod.POST) + public @ResponseBody String processLoginSpringWay(@RequestParam("username") String un, + @RequestParam("password") String pass) { + if (un.equalsIgnoreCase(pass)) { + return "Welcome, " + un; + } + return "Login failed."; + } + + @RequestMapping(value = "/loginSpringWay", method = RequestMethod.GET) + public @ResponseBody String processLoginSpringWayGET(@RequestParam("username") String un, + @RequestParam("password") String pass) { + if (un.equalsIgnoreCase(pass)) { + return "Welcome, " + un; + } + return "Login failed."; + } + +} diff --git a/src/com/jm3007/learn/spring/web/User.java b/src/com/jm3007/learn/spring/web/User.java new file mode 100644 index 0000000..12b62ff --- /dev/null +++ b/src/com/jm3007/learn/spring/web/User.java @@ -0,0 +1,73 @@ +package com.jm3007.learn.spring.web; + +public class User { + private String name; + + private int age; + + private String gender; + + private String country; + + private String[] courses; + + private boolean graduated; + + private String feedback; + + public String[] getCourses() { + return courses; + } + + public void setCourses(String[] courses) { + this.courses = courses; + } + + public boolean isGraduated() { + return graduated; + } + + public void setGraduated(boolean graduated) { + this.graduated = graduated; + } + + public String getFeedback() { + return feedback; + } + + public void setFeedback(String feedback) { + this.feedback = feedback; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + public String getGender() { + return gender; + } + + public void setGender(String gender) { + this.gender = gender; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/src/com/jm3007/learn/spring/web/UserController.java b/src/com/jm3007/learn/spring/web/UserController.java new file mode 100644 index 0000000..0de247f --- /dev/null +++ b/src/com/jm3007/learn/spring/web/UserController.java @@ -0,0 +1,24 @@ +package com.jm3007.learn.spring.web; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@Controller +@RequestMapping("/users") +public class UserController { + + @RequestMapping(value = "/show-form", method = RequestMethod.GET) + public String showUserRegistrationForm(Model model) { + model.addAttribute("user", new User()); + model.addAttribute("msg", "Hello How are you"); + return "user-registration"; + } + + @RequestMapping(value = "/process-user-registration", method = RequestMethod.POST) + public String processUserRegistration(@ModelAttribute("user") User u) { + return "user-profile"; + } +} From 056157e8266e681018c396320a84862a3cdb0f9f Mon Sep 17 00:00:00 2001 From: Code WellnWill Date: Sun, 20 Jan 2019 12:42:43 +0530 Subject: [PATCH 12/19] Spring MVC validation --- WebContent/WEB-INF/view/user-registration.jsp | 54 ++++++++++++----- pom.xml | 6 ++ .../jm3007/learn/spring/ioc/noxml/Car.java | 1 - .../jm3007/learn/spring/web/BatchCode.java | 23 +++++++ .../web/BatchCodeContraintValidator.java | 22 +++++++ src/com/jm3007/learn/spring/web/User.java | 60 ++++++++++++++++++- .../learn/spring/web/UserController.java | 18 +++++- 7 files changed, 163 insertions(+), 21 deletions(-) create mode 100644 src/com/jm3007/learn/spring/web/BatchCode.java create mode 100644 src/com/jm3007/learn/spring/web/BatchCodeContraintValidator.java diff --git a/WebContent/WEB-INF/view/user-registration.jsp b/WebContent/WEB-INF/view/user-registration.jsp index e1415d6..94f1256 100644 --- a/WebContent/WEB-INF/view/user-registration.jsp +++ b/WebContent/WEB-INF/view/user-registration.jsp @@ -2,27 +2,50 @@ + User Registration Form -

${msg}

- +

${msg}

+ - + - + + + + + + + + + + + + + - + - + - + - + - + - - + +
Name
Age
Batch Code
Date of Birth
Last class Date
Gender Male   - Female Male   + Female
Country @@ -32,23 +55,22 @@
Courses - Core Java   - Advance Java   - Java Frameworks   - Core Java +   Advance Java +   Java Frameworks +  
Are you graduate?
Feedback
diff --git a/pom.xml b/pom.xml index 2733012..938c2d0 100644 --- a/pom.xml +++ b/pom.xml @@ -15,6 +15,12 @@ spring-webmvc 5.1.3.RELEASE + + org.hibernate.validator + hibernate-validator + 6.0.13.Final + +
diff --git a/src/com/jm3007/learn/spring/ioc/noxml/Car.java b/src/com/jm3007/learn/spring/ioc/noxml/Car.java index c64b138..b004b54 100644 --- a/src/com/jm3007/learn/spring/ioc/noxml/Car.java +++ b/src/com/jm3007/learn/spring/ioc/noxml/Car.java @@ -4,7 +4,6 @@ @Component public class Car { - public void driveTheCar() { System.out.println("Driving the Car..."); } diff --git a/src/com/jm3007/learn/spring/web/BatchCode.java b/src/com/jm3007/learn/spring/web/BatchCode.java new file mode 100644 index 0000000..60bfa9b --- /dev/null +++ b/src/com/jm3007/learn/spring/web/BatchCode.java @@ -0,0 +1,23 @@ +package com.jm3007.learn.spring.web; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import javax.validation.Constraint; +import javax.validation.Payload; + +@Constraint(validatedBy = BatchCodeContraintValidator.class) +@Retention(RUNTIME) +@Target(FIELD) +public @interface BatchCode { + public String value() default "JM3"; + + public String message() default " prefix should be JM3"; + + public Class[] groups() default {}; + + public Class[] payload() default {}; +} diff --git a/src/com/jm3007/learn/spring/web/BatchCodeContraintValidator.java b/src/com/jm3007/learn/spring/web/BatchCodeContraintValidator.java new file mode 100644 index 0000000..b794932 --- /dev/null +++ b/src/com/jm3007/learn/spring/web/BatchCodeContraintValidator.java @@ -0,0 +1,22 @@ +package com.jm3007.learn.spring.web; + +import static java.util.Optional.*; + +import javax.validation.ConstraintValidator; +import javax.validation.ConstraintValidatorContext; + +public class BatchCodeContraintValidator implements ConstraintValidator { + + private String prefix; + + @Override + public void initialize(BatchCode batchCode) { + this.prefix = batchCode.value(); + } + + @Override + public boolean isValid(String value, ConstraintValidatorContext context) { + return ofNullable(value).map(nonNullValue -> nonNullValue.startsWith(prefix)).orElse(true); + } + +} diff --git a/src/com/jm3007/learn/spring/web/User.java b/src/com/jm3007/learn/spring/web/User.java index 12b62ff..3d374b8 100644 --- a/src/com/jm3007/learn/spring/web/User.java +++ b/src/com/jm3007/learn/spring/web/User.java @@ -1,20 +1,74 @@ package com.jm3007.learn.spring.web; +import java.util.Date; + +import javax.validation.constraints.Future; +import javax.validation.constraints.Max; +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Past; +import javax.validation.constraints.Pattern; +import javax.validation.constraints.Size; + +import org.springframework.format.annotation.DateTimeFormat; + public class User { + + @NotNull(message = " enter valid name") + @Size(min = 2, max = 12, message = " name should not be less than 2 characters") + @Size(max = 12, message = " name should not be more than 12 characters") private String name; + @Min(value = 18, message = " age should not be less than 18") + @Max(value = 60, message = " age should not be more than 60") private int age; private String gender; private String country; - + private String[] courses; - + private boolean graduated; - + private String feedback; + @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) + @Past(message = " must be in past") + private Date dob; + + @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) + @Future(message = " must be in future") + private Date lastBatchDate; + + public Date getDob() { + return dob; + } + + public void setDob(Date dob) { + this.dob = dob; + } + + public Date getLastBatchDate() { + return lastBatchDate; + } + + public void setLastBatchDate(Date lastBatchDate) { + this.lastBatchDate = lastBatchDate; + } + + @BatchCode(value = "JM2", message = " prefix should be JM2") + @Pattern(regexp = "^[a-zA-Z0-9]{6}", message = " should not contain special characters") + private String batchCode; + + public String getBatchCode() { + return batchCode; + } + + public void setBatchCode(String batchCode) { + this.batchCode = batchCode; + } + public String[] getCourses() { return courses; } diff --git a/src/com/jm3007/learn/spring/web/UserController.java b/src/com/jm3007/learn/spring/web/UserController.java index 0de247f..419460c 100644 --- a/src/com/jm3007/learn/spring/web/UserController.java +++ b/src/com/jm3007/learn/spring/web/UserController.java @@ -1,7 +1,13 @@ package com.jm3007.learn.spring.web; +import javax.validation.Valid; + +import org.springframework.beans.propertyeditors.StringTrimmerEditor; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -10,6 +16,12 @@ @RequestMapping("/users") public class UserController { + @InitBinder + public void preprocessWebData(WebDataBinder webDataBinder) { + StringTrimmerEditor stringTrimmerEditor = new StringTrimmerEditor(true); + webDataBinder.registerCustomEditor(String.class, stringTrimmerEditor); + } + @RequestMapping(value = "/show-form", method = RequestMethod.GET) public String showUserRegistrationForm(Model model) { model.addAttribute("user", new User()); @@ -18,7 +30,11 @@ public String showUserRegistrationForm(Model model) { } @RequestMapping(value = "/process-user-registration", method = RequestMethod.POST) - public String processUserRegistration(@ModelAttribute("user") User u) { + public String processUserRegistration(@Valid @ModelAttribute("user") User u, BindingResult bindingResult) { + if (bindingResult.hasErrors()) { + return "user-registration"; + + } return "user-profile"; } } From bb931d5e4cb645bcd7b95d0b2b6ec86aded0ca8a Mon Sep 17 00:00:00 2001 From: Code WellnWill Date: Sat, 26 Jan 2019 12:43:07 +0530 Subject: [PATCH 13/19] Hibernate Introduction --- pom.xml | 14 +++-- .../jm3007/learn/hibernate/HibernateApp.java | 49 ++++++++++++++++ src/com/jm3007/learn/hibernate/User.java | 57 +++++++++++++++++++ .../learn/hibernate/important-queries.sql | 5 ++ src/hibernate.cfg.xml | 22 +++++++ 5 files changed, 143 insertions(+), 4 deletions(-) create mode 100644 src/com/jm3007/learn/hibernate/HibernateApp.java create mode 100644 src/com/jm3007/learn/hibernate/User.java create mode 100644 src/com/jm3007/learn/hibernate/important-queries.sql create mode 100644 src/hibernate.cfg.xml diff --git a/pom.xml b/pom.xml index 938c2d0..0518fda 100644 --- a/pom.xml +++ b/pom.xml @@ -20,11 +20,17 @@ hibernate-validator 6.0.13.Final - + + org.hibernate + hibernate-core + 5.4.0.Final + + + com.h2database + h2 + 1.4.193 + - - - src diff --git a/src/com/jm3007/learn/hibernate/HibernateApp.java b/src/com/jm3007/learn/hibernate/HibernateApp.java new file mode 100644 index 0000000..ed53f67 --- /dev/null +++ b/src/com/jm3007/learn/hibernate/HibernateApp.java @@ -0,0 +1,49 @@ +package com.jm3007.learn.hibernate; + +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; + +public class HibernateApp { + + public static void main(String[] args) { + SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(User.class) + .buildSessionFactory(); + + Session session = sessionFactory.getCurrentSession(); + + try { + session.beginTransaction(); + + // my opereation +// User user = new User(3L, "Virat", 59); +// session.save(user); + + User user = session.get(User.class, 1L); + System.out.println(user.getName()); + + /*List users = session.createQuery("from User").getResultList(); + for (User user : users) { + System.out.println(user.getName()); + }*/ + + /*List users = session.createQuery("from User u where u.name = 'Virat'").getResultList(); + for (User user : users) { + System.out.println(user.getName()); + }*/ + +// User user = session.get(User.class, 2L); +// user.setName("Sachin"); + +// User user = session.get(User.class, 1L); +// session.delete(user); + + + session.getTransaction().commit(); + } finally { + sessionFactory.close(); + } + } +} diff --git a/src/com/jm3007/learn/hibernate/User.java b/src/com/jm3007/learn/hibernate/User.java new file mode 100644 index 0000000..84dc002 --- /dev/null +++ b/src/com/jm3007/learn/hibernate/User.java @@ -0,0 +1,57 @@ +package com.jm3007.learn.hibernate; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "JM3007_USER") +public class User { + + @Id + @Column(name = "id") + private Long id; + + @Column(name = "name") + private String name; + + @Column(name = "age") + private int age; + + public User(Long id, String name, int age) { + super(); + this.id = id; + this.name = name; + this.age = age; + } + + public User() { + super(); + // TODO Auto-generated constructor stub + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } +} diff --git a/src/com/jm3007/learn/hibernate/important-queries.sql b/src/com/jm3007/learn/hibernate/important-queries.sql new file mode 100644 index 0000000..a2fa4c8 --- /dev/null +++ b/src/com/jm3007/learn/hibernate/important-queries.sql @@ -0,0 +1,5 @@ +CREATE TABLE JM3007_USER( +ID NUMBER PRIMARY KEY, +NAME VARCHAR(50), +AGE NUMBER +); \ No newline at end of file diff --git a/src/hibernate.cfg.xml b/src/hibernate.cfg.xml new file mode 100644 index 0000000..a817de3 --- /dev/null +++ b/src/hibernate.cfg.xml @@ -0,0 +1,22 @@ + + + + + + + + + + org.h2.Driver + jdbc:h2:~/test + sa + + 1 + org.hibernate.dialect.H2Dialect + true + thread + + + \ No newline at end of file From 87ead1023044e1b71de18d592ff8e6e6298adf5b Mon Sep 17 00:00:00 2001 From: Code WellnWill Date: Sun, 27 Jan 2019 12:24:13 +0530 Subject: [PATCH 14/19] Identity --- .../hibernate/identifier/auto/AutoUser.java | 59 ++++++++++++++++ .../identifier/auto/AutoUserClient.java | 25 +++++++ .../identifier/identity/IdentityUser.java | 64 ++++++++++++++++++ .../identity/IdentityUserClient.java | 27 ++++++++ .../identifier/sequence/SequenceUser.java | 66 ++++++++++++++++++ .../sequence/SequenceUserClient.java | 29 ++++++++ .../hibernate/identifier/table/TableUser.java | 67 +++++++++++++++++++ .../identifier/table/TableUserClient.java | 29 ++++++++ .../learn/hibernate/important-queries.sql | 39 +++++++++++ src/hibernate.cfg.xml | 2 +- 10 files changed, 406 insertions(+), 1 deletion(-) create mode 100644 src/com/jm3007/learn/hibernate/identifier/auto/AutoUser.java create mode 100644 src/com/jm3007/learn/hibernate/identifier/auto/AutoUserClient.java create mode 100644 src/com/jm3007/learn/hibernate/identifier/identity/IdentityUser.java create mode 100644 src/com/jm3007/learn/hibernate/identifier/identity/IdentityUserClient.java create mode 100644 src/com/jm3007/learn/hibernate/identifier/sequence/SequenceUser.java create mode 100644 src/com/jm3007/learn/hibernate/identifier/sequence/SequenceUserClient.java create mode 100644 src/com/jm3007/learn/hibernate/identifier/table/TableUser.java create mode 100644 src/com/jm3007/learn/hibernate/identifier/table/TableUserClient.java diff --git a/src/com/jm3007/learn/hibernate/identifier/auto/AutoUser.java b/src/com/jm3007/learn/hibernate/identifier/auto/AutoUser.java new file mode 100644 index 0000000..4e6328b --- /dev/null +++ b/src/com/jm3007/learn/hibernate/identifier/auto/AutoUser.java @@ -0,0 +1,59 @@ +package com.jm3007.learn.hibernate.identifier.auto; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "JM3007_IDENTIFIER_AUTO_USER") +public class AutoUser { + + @Id + @Column(name = "id") + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + @Column(name = "name") + private String name; + + @Column(name = "age") + private int age; + + public AutoUser(String name, int age) { + super(); + this.name = name; + this.age = age; + } + + public AutoUser() { + super(); + // TODO Auto-generated constructor stub + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } +} diff --git a/src/com/jm3007/learn/hibernate/identifier/auto/AutoUserClient.java b/src/com/jm3007/learn/hibernate/identifier/auto/AutoUserClient.java new file mode 100644 index 0000000..7a929ca --- /dev/null +++ b/src/com/jm3007/learn/hibernate/identifier/auto/AutoUserClient.java @@ -0,0 +1,25 @@ +package com.jm3007.learn.hibernate.identifier.auto; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; + +public class AutoUserClient { + + public static void main(String[] args) { + SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml") + .addAnnotatedClass(AutoUser.class).buildSessionFactory(); + + Session session = sessionFactory.getCurrentSession(); + + try { + session.beginTransaction(); + AutoUser autoUser = new AutoUser("Bikas", 20); + session.save(autoUser); + session.getTransaction().commit(); + } finally { + sessionFactory.close(); + } + } + +} diff --git a/src/com/jm3007/learn/hibernate/identifier/identity/IdentityUser.java b/src/com/jm3007/learn/hibernate/identifier/identity/IdentityUser.java new file mode 100644 index 0000000..f51d422 --- /dev/null +++ b/src/com/jm3007/learn/hibernate/identifier/identity/IdentityUser.java @@ -0,0 +1,64 @@ +package com.jm3007.learn.hibernate.identifier.identity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "JM3007_IDENTIFIER_IDENTITY_USER") +public class IdentityUser { + + @Override + public String toString() { + return "IdentityUser [id=" + id + ", name=" + name + ", age=" + age + "]"; + } + + @Id + @Column(name = "id") + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "name") + private String name; + + @Column(name = "age") + private int age; + + public IdentityUser(String name, int age) { + super(); + this.name = name; + this.age = age; + } + + public IdentityUser() { + super(); + // TODO Auto-generated constructor stub + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } +} diff --git a/src/com/jm3007/learn/hibernate/identifier/identity/IdentityUserClient.java b/src/com/jm3007/learn/hibernate/identifier/identity/IdentityUserClient.java new file mode 100644 index 0000000..d2678bb --- /dev/null +++ b/src/com/jm3007/learn/hibernate/identifier/identity/IdentityUserClient.java @@ -0,0 +1,27 @@ +package com.jm3007.learn.hibernate.identifier.identity; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; + +public class IdentityUserClient { + + public static void main(String[] args) { + SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml") + .addAnnotatedClass(IdentityUser.class).buildSessionFactory(); + + Session session = sessionFactory.getCurrentSession(); + + try { + session.beginTransaction(); + IdentityUser autoUser = new IdentityUser("Bikas", 20); + Long id = (Long)session.save(autoUser); + IdentityUser identityUser = session.get(IdentityUser.class, id); + System.out.println(identityUser); + session.getTransaction().commit(); + } finally { +// sessionFactory.close(); + } + } + +} diff --git a/src/com/jm3007/learn/hibernate/identifier/sequence/SequenceUser.java b/src/com/jm3007/learn/hibernate/identifier/sequence/SequenceUser.java new file mode 100644 index 0000000..4f65e3b --- /dev/null +++ b/src/com/jm3007/learn/hibernate/identifier/sequence/SequenceUser.java @@ -0,0 +1,66 @@ +package com.jm3007.learn.hibernate.identifier.sequence; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +@Entity +@Table(name = "JM3007_IDENTIFIER_SEQUENCE_USER") +public class SequenceUser { + + @Override + public String toString() { + return "IdentityUser [id=" + id + ", name=" + name + ", age=" + age + "]"; + } + + @Id + @Column(name = "id") + @SequenceGenerator(name = "mySequence", sequenceName = "IDENTIFIER_SEQUENCE", allocationSize = 1, schema = "PUBLIC") + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "mySequence") + private Long id; + + @Column(name = "name") + private String name; + + @Column(name = "age") + private int age; + + public SequenceUser(String name, int age) { + super(); + this.name = name; + this.age = age; + } + + public SequenceUser() { + super(); + // TODO Auto-generated constructor stub + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } +} diff --git a/src/com/jm3007/learn/hibernate/identifier/sequence/SequenceUserClient.java b/src/com/jm3007/learn/hibernate/identifier/sequence/SequenceUserClient.java new file mode 100644 index 0000000..300b72d --- /dev/null +++ b/src/com/jm3007/learn/hibernate/identifier/sequence/SequenceUserClient.java @@ -0,0 +1,29 @@ +package com.jm3007.learn.hibernate.identifier.sequence; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; + +public class SequenceUserClient { + + public static void main(String[] args) { + SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml") + .addAnnotatedClass(SequenceUser.class).buildSessionFactory(); + + Session session = sessionFactory.getCurrentSession(); + + try { + session.beginTransaction(); + SequenceUser sequenceUser = new SequenceUser("Bikas", 20); + Long id = (Long)session.save(sequenceUser); + SequenceUser sequenceUserFromDb = session.get(SequenceUser.class, id); + System.out.println(sequenceUserFromDb); + sequenceUserFromDb.setAge(100); + System.out.println(sequenceUserFromDb); + session.getTransaction().commit(); + } finally { + sessionFactory.close(); + } + } + +} diff --git a/src/com/jm3007/learn/hibernate/identifier/table/TableUser.java b/src/com/jm3007/learn/hibernate/identifier/table/TableUser.java new file mode 100644 index 0000000..b24fe19 --- /dev/null +++ b/src/com/jm3007/learn/hibernate/identifier/table/TableUser.java @@ -0,0 +1,67 @@ +package com.jm3007.learn.hibernate.identifier.table; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; +import javax.persistence.TableGenerator; + +@Entity +@Table(name = "JM3007_IDENTIFIER_TABLE_USER") +public class TableUser { + + @Override + public String toString() { + return "IdentityUser [id=" + id + ", name=" + name + ", age=" + age + "]"; + } + + @Id + @Column(name = "id") + @TableGenerator(name = "mySequence", table = "JM3007_IDENTIFIER_SEQUENCE_TABLE", pkColumnName = "SEQ_NAME", pkColumnValue = "IDENTIFIER_TABLE_SEQUENCE", valueColumnName = "NEXT_VAL", allocationSize = 1, schema = "PUBLIC") + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "mySequence") + private Long id; + + @Column(name = "name") + private String name; + + @Column(name = "age") + private int age; + + public TableUser(String name, int age) { + super(); + this.name = name; + this.age = age; + } + + public TableUser() { + super(); + // TODO Auto-generated constructor stub + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } +} diff --git a/src/com/jm3007/learn/hibernate/identifier/table/TableUserClient.java b/src/com/jm3007/learn/hibernate/identifier/table/TableUserClient.java new file mode 100644 index 0000000..6e1fb4e --- /dev/null +++ b/src/com/jm3007/learn/hibernate/identifier/table/TableUserClient.java @@ -0,0 +1,29 @@ +package com.jm3007.learn.hibernate.identifier.table; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; + +public class TableUserClient { + + public static void main(String[] args) { + SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml") + .addAnnotatedClass(TableUser.class).buildSessionFactory(); + + Session session = sessionFactory.getCurrentSession(); + + try { + session.beginTransaction(); + TableUser tableUser = new TableUser("Bikas", 20); + Long id = (Long)session.save(tableUser); +// TableUser tableUserFromDb = session.get(TableUser.class, id); +// System.out.println(tableUserFromDb); +// tableUserFromDb.setAge(100); +// System.out.println(tableUserFromDb); + session.getTransaction().commit(); + } finally { + sessionFactory.close(); + } + } + +} diff --git a/src/com/jm3007/learn/hibernate/important-queries.sql b/src/com/jm3007/learn/hibernate/important-queries.sql index a2fa4c8..01db507 100644 --- a/src/com/jm3007/learn/hibernate/important-queries.sql +++ b/src/com/jm3007/learn/hibernate/important-queries.sql @@ -2,4 +2,43 @@ CREATE TABLE JM3007_USER( ID NUMBER PRIMARY KEY, NAME VARCHAR(50), AGE NUMBER +); + +-- IDENTIFIER AUTO +DROP SEQUENCE HIBERNATE_SEQUENCE; +CREATE SEQUENCE HIBERNATE_SEQUENCE; +ALTER SEQUENCE HIBERNATE_SEQUENCE RESTART WITH 1001; +CREATE TABLE JM3007_IDENTIFIER_AUTO_USER( +ID BIGINT PRIMARY KEY, +NAME VARCHAR(50), +AGE NUMBER +); + +-- IDENTIFIER IDENTITY +CREATE TABLE JM3007_IDENTIFIER_IDENTITY_USER( +ID BIGINT AUTO_INCREMENT PRIMARY KEY, +NAME VARCHAR(50), +AGE NUMBER +); + +-- IDENTIFIER SEQUENCE +CREATE SEQUENCE IDENTIFIER_SEQUENCE; +CREATE TABLE JM3007_IDENTIFIER_SEQUENCE_USER( +ID BIGINT PRIMARY KEY, +NAME VARCHAR(50), +AGE NUMBER +); + + +-- IDENTIFIER TABLE +CREATE SEQUENCE IDENTIFIER_TABLE_SEQUENCE; +CREATE TABLE JM3007_IDENTIFIER_SEQUENCE_TABLE( +SEQ_NAME VARCHAR, +NEXT_VAL BIGINT +); +INSERT INTO JM3007_IDENTIFIER_SEQUENCE_TABLE VALUES('IDENTIFIER_TABLE_SEQUENCE', 5001); +CREATE TABLE JM3007_IDENTIFIER_TABLE_USER( +ID BIGINT PRIMARY KEY, +NAME VARCHAR(50), +AGE NUMBER ); \ No newline at end of file diff --git a/src/hibernate.cfg.xml b/src/hibernate.cfg.xml index a817de3..329cd6f 100644 --- a/src/hibernate.cfg.xml +++ b/src/hibernate.cfg.xml @@ -13,7 +13,7 @@ jdbc:h2:~/test sa - 1 + 2 org.hibernate.dialect.H2Dialect true thread From 106f943c09074666ddeb12303f4f678cc0f1f007 Mon Sep 17 00:00:00 2001 From: Code WellnWill Date: Sat, 2 Feb 2019 11:57:24 +0530 Subject: [PATCH 15/19] Associations --- .../association/onetomany/uni/Assignment.java | 43 +++++++++ .../association/onetomany/uni/Course.java | 60 ++++++++++++ .../association/onetomany/uni/CourseApp.java | 46 +++++++++ .../onetomany/uni/one-to-many-uni.sql | 11 +++ .../association/onetoone/bi/Student.java | 95 +++++++++++++++++++ .../association/onetoone/bi/StudentApp.java | 33 +++++++ .../onetoone/bi/StudentDetail.java | 79 +++++++++++++++ .../association/onetoone/bi/ont-to-one-bi.sql | 14 +++ .../association/onetoone/uni/Student.java | 94 ++++++++++++++++++ .../association/onetoone/uni/StudentApp.java | 32 +++++++ .../onetoone/uni/StudentDetail.java | 65 +++++++++++++ .../onetoone/uni/ont-to-one-uni.sql | 14 +++ 12 files changed, 586 insertions(+) create mode 100644 src/com/jm3007/learn/hibernate/association/onetomany/uni/Assignment.java create mode 100644 src/com/jm3007/learn/hibernate/association/onetomany/uni/Course.java create mode 100644 src/com/jm3007/learn/hibernate/association/onetomany/uni/CourseApp.java create mode 100644 src/com/jm3007/learn/hibernate/association/onetomany/uni/one-to-many-uni.sql create mode 100644 src/com/jm3007/learn/hibernate/association/onetoone/bi/Student.java create mode 100644 src/com/jm3007/learn/hibernate/association/onetoone/bi/StudentApp.java create mode 100644 src/com/jm3007/learn/hibernate/association/onetoone/bi/StudentDetail.java create mode 100644 src/com/jm3007/learn/hibernate/association/onetoone/bi/ont-to-one-bi.sql create mode 100644 src/com/jm3007/learn/hibernate/association/onetoone/uni/Student.java create mode 100644 src/com/jm3007/learn/hibernate/association/onetoone/uni/StudentApp.java create mode 100644 src/com/jm3007/learn/hibernate/association/onetoone/uni/StudentDetail.java create mode 100644 src/com/jm3007/learn/hibernate/association/onetoone/uni/ont-to-one-uni.sql diff --git a/src/com/jm3007/learn/hibernate/association/onetomany/uni/Assignment.java b/src/com/jm3007/learn/hibernate/association/onetomany/uni/Assignment.java new file mode 100644 index 0000000..d2b7113 --- /dev/null +++ b/src/com/jm3007/learn/hibernate/association/onetomany/uni/Assignment.java @@ -0,0 +1,43 @@ +package com.jm3007.learn.hibernate.association.onetomany.uni; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "JM3007_ONETOMANY_UNI_ASSIGNMENT") +public class Assignment { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "name") + private String name; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "Assignment [id=" + id + ", name=" + name + "]"; + } + +} diff --git a/src/com/jm3007/learn/hibernate/association/onetomany/uni/Course.java b/src/com/jm3007/learn/hibernate/association/onetomany/uni/Course.java new file mode 100644 index 0000000..00bff53 --- /dev/null +++ b/src/com/jm3007/learn/hibernate/association/onetomany/uni/Course.java @@ -0,0 +1,60 @@ +package com.jm3007.learn.hibernate.association.onetomany.uni; + +import java.util.List; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToMany; +import javax.persistence.Table; + +@Entity +@Table(name = "JM3007_ONETOMANY_UNI_COURSE") +public class Course { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "name") + private String name; + + @JoinColumn(name = "COURSE_ID") + @OneToMany(cascade = CascadeType.ALL) + private List assignments; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getAssignments() { + return assignments; + } + + public void setAssignments(List assignments) { + this.assignments = assignments; + } + + @Override + public String toString() { + return "Course [id=" + id + ", name=" + name + ", assignments=" + assignments + "]"; + } + +} diff --git a/src/com/jm3007/learn/hibernate/association/onetomany/uni/CourseApp.java b/src/com/jm3007/learn/hibernate/association/onetomany/uni/CourseApp.java new file mode 100644 index 0000000..2817068 --- /dev/null +++ b/src/com/jm3007/learn/hibernate/association/onetomany/uni/CourseApp.java @@ -0,0 +1,46 @@ +package com.jm3007.learn.hibernate.association.onetomany.uni; + +import java.util.ArrayList; +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; + +public class CourseApp { + public static void main(String[] args) { + SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml") + .addAnnotatedClass(Course.class).addAnnotatedClass(Assignment.class).buildSessionFactory(); + + Session session = sessionFactory.getCurrentSession(); + + try { + session.beginTransaction(); + + /* Assignment assignemnt1 = new Assignment(); + assignemnt1.setName("CRUD operations"); + + Assignment assignemnt2 = new Assignment(); + assignemnt2.setName("Identifeirs"); + + List assignments = new ArrayList<>(); + assignments.add(assignemnt1); + assignments.add(assignemnt2); + + Course course = new Course(); + course.setName("Hibernate"); + course.setAssignments(assignments);*/ + +// session.save(course); + + Course course = session.get(Course.class, 2L); + course.setName("Spring"); + course.getAssignments().get(0).setName("CURD operation"); + + session.getTransaction().commit(); + + } finally { + sessionFactory.close(); + } + } +} diff --git a/src/com/jm3007/learn/hibernate/association/onetomany/uni/one-to-many-uni.sql b/src/com/jm3007/learn/hibernate/association/onetomany/uni/one-to-many-uni.sql new file mode 100644 index 0000000..4b0f522 --- /dev/null +++ b/src/com/jm3007/learn/hibernate/association/onetomany/uni/one-to-many-uni.sql @@ -0,0 +1,11 @@ +CREATE TABLE JM3007_ONETOMANY_UNI_COURSE( +ID BIGINT AUTO_INCREMENT PRIMARY KEY, +NAME VARCHAR(50) +); + +CREATE TABLE JM3007_ONETOMANY_UNI_ASSIGNMENT( +ID BIGINT AUTO_INCREMENT PRIMARY KEY, +NAME VARCHAR(50), +COURSE_ID BIGINT, +FOREIGN KEY (COURSE_ID) REFERENCES JM3007_ONETOMANY_UNI_COURSE(ID) +); \ No newline at end of file diff --git a/src/com/jm3007/learn/hibernate/association/onetoone/bi/Student.java b/src/com/jm3007/learn/hibernate/association/onetoone/bi/Student.java new file mode 100644 index 0000000..631ff74 --- /dev/null +++ b/src/com/jm3007/learn/hibernate/association/onetoone/bi/Student.java @@ -0,0 +1,95 @@ +package com.jm3007.learn.hibernate.association.onetoone.bi; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +import org.springframework.web.bind.annotation.Mapping; + +@Entity +@Table(name = "JM3007_ONETOONE_BI_STUDENT") +public class Student { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "name") + private String name; + + @Column(name = "age") + private int age; + + public Student() { + super(); + // TODO Auto-generated constructor stub + } + + public Student(String name, int age, String nationality, StudentDetail studentDetail) { + super(); + this.name = name; + this.age = age; + this.nationality = nationality; + this.studentDetail = studentDetail; + } + + @Column(name = "nationality") + private String nationality; + + @JoinColumn(name = "STUDENT_DETAIL_ID") + @OneToOne(cascade = CascadeType.ALL) + private StudentDetail studentDetail; + + public StudentDetail getStudentDetail() { + return studentDetail; + } + + public void setStudentDetail(StudentDetail studentDetail) { + this.studentDetail = studentDetail; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getNationality() { + return nationality; + } + + public void setNationality(String nationality) { + this.nationality = nationality; + } + + @Override + public String toString() { + return "Student [id=" + id + ", name=" + name + ", age=" + age + ", nationality=" + nationality + + ", studentDetail=" + studentDetail + "]"; + } +} diff --git a/src/com/jm3007/learn/hibernate/association/onetoone/bi/StudentApp.java b/src/com/jm3007/learn/hibernate/association/onetoone/bi/StudentApp.java new file mode 100644 index 0000000..844f5fc --- /dev/null +++ b/src/com/jm3007/learn/hibernate/association/onetoone/bi/StudentApp.java @@ -0,0 +1,33 @@ +package com.jm3007.learn.hibernate.association.onetoone.bi; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; + +public class StudentApp { + public static void main(String[] args) { + SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml") + .addAnnotatedClass(Student.class).addAnnotatedClass(StudentDetail.class).buildSessionFactory(); + + Session session = sessionFactory.getCurrentSession(); + + try { + session.beginTransaction(); + + StudentDetail studentDetail = new StudentDetail("New Horizon", 1001); + Student student = new Student("Satish", 22, "Indian", studentDetail); + studentDetail.setStudent(student); + + +// session.save(studentDetail); + + StudentDetail std = session.get(StudentDetail.class, 1L); + System.out.println(std); + System.out.println(std.getStudent()); + + session.getTransaction().commit(); + + } finally { + } + } +} diff --git a/src/com/jm3007/learn/hibernate/association/onetoone/bi/StudentDetail.java b/src/com/jm3007/learn/hibernate/association/onetoone/bi/StudentDetail.java new file mode 100644 index 0000000..959e7ae --- /dev/null +++ b/src/com/jm3007/learn/hibernate/association/onetoone/bi/StudentDetail.java @@ -0,0 +1,79 @@ +package com.jm3007.learn.hibernate.association.onetoone.bi; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +@Entity +@Table(name = "JM3007_ONETOONE_BI_STUDENT_DETAIL") +public class StudentDetail { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "college_name") + private String collegeName; + + @Column(name = "ROLL_NO") + private Integer rollNo; + + @OneToOne(cascade = {CascadeType.ALL}, mappedBy="studentDetail") + private Student student; + + public Student getStudent() { + return student; + } + + public void setStudent(Student student) { + this.student = student; + } + + public Long getId() { + return id; + } + + public StudentDetail(String collegeName, Integer rollNo) { + super(); + this.collegeName = collegeName; + this.rollNo = rollNo; + } + + public StudentDetail() { + super(); + // TODO Auto-generated constructor stub + } + + public void setId(Long id) { + this.id = id; + } + + public String getCollegeName() { + return collegeName; + } + + public void setCollegeName(String collegeName) { + this.collegeName = collegeName; + } + + public Integer getRollNo() { + return rollNo; + } + + public void setRollNo(Integer rollNo) { + this.rollNo = rollNo; + } + + @Override + public String toString() { + return "StudentDetail [id=" + id + ", collegeName=" + collegeName + ", rollNo=" + rollNo + "]"; + } + + +} diff --git a/src/com/jm3007/learn/hibernate/association/onetoone/bi/ont-to-one-bi.sql b/src/com/jm3007/learn/hibernate/association/onetoone/bi/ont-to-one-bi.sql new file mode 100644 index 0000000..8193a06 --- /dev/null +++ b/src/com/jm3007/learn/hibernate/association/onetoone/bi/ont-to-one-bi.sql @@ -0,0 +1,14 @@ +CREATE TABLE JM3007_ONETOONE_BI_STUDENT_DETAIL( +ID BIGINT AUTO_INCREMENT PRIMARY KEY, +COLLEGE_NAME VARCHAR(50), +ROLL_NO NUMBER, +); + +CREATE TABLE JM3007_ONETOONE_BI_STUDENT( +ID BIGINT AUTO_INCREMENT PRIMARY KEY, +NAME VARCHAR(50), +AGE NUMBER, +NATIONALITY VARCHAR(50), +STUDENT_DETAIL_ID BIGINT, +FOREIGN KEY (STUDENT_DETAIL_ID) REFERENCES JM3007_ONETOONE_BI_STUDENT_DETAIL(ID) +); \ No newline at end of file diff --git a/src/com/jm3007/learn/hibernate/association/onetoone/uni/Student.java b/src/com/jm3007/learn/hibernate/association/onetoone/uni/Student.java new file mode 100644 index 0000000..3eb01c5 --- /dev/null +++ b/src/com/jm3007/learn/hibernate/association/onetoone/uni/Student.java @@ -0,0 +1,94 @@ +package com.jm3007.learn.hibernate.association.onetoone.uni; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +import org.springframework.web.bind.annotation.Mapping; + +@Entity +@Table(name = "JM3007_ONETOONE_UNI_STUDENT") +public class Student { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "name") + private String name; + + @Column(name = "age") + private int age; + + public Student() { + super(); + } + + public Student(String name, int age, String nationality, StudentDetail studentDetail) { + super(); + this.name = name; + this.age = age; + this.nationality = nationality; + this.studentDetail = studentDetail; + } + + @Column(name = "nationality") + private String nationality; + + @JoinColumn(name = "STUDENT_DETAIL_ID") + @OneToOne(cascade = CascadeType.ALL) + private StudentDetail studentDetail; + + public StudentDetail getStudentDetail() { + return studentDetail; + } + + public void setStudentDetail(StudentDetail studentDetail) { + this.studentDetail = studentDetail; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getNationality() { + return nationality; + } + + public void setNationality(String nationality) { + this.nationality = nationality; + } + + @Override + public String toString() { + return "Student [id=" + id + ", name=" + name + ", age=" + age + ", nationality=" + nationality + + ", studentDetail=" + studentDetail + "]"; + } +} diff --git a/src/com/jm3007/learn/hibernate/association/onetoone/uni/StudentApp.java b/src/com/jm3007/learn/hibernate/association/onetoone/uni/StudentApp.java new file mode 100644 index 0000000..a17a79b --- /dev/null +++ b/src/com/jm3007/learn/hibernate/association/onetoone/uni/StudentApp.java @@ -0,0 +1,32 @@ +package com.jm3007.learn.hibernate.association.onetoone.uni; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; + +public class StudentApp { + public static void main(String[] args) { + SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml") + .addAnnotatedClass(Student.class).addAnnotatedClass(StudentDetail.class).buildSessionFactory(); + + Session session = sessionFactory.getCurrentSession(); + + try { + session.beginTransaction(); + +// StudentDetail studentDetail = new StudentDetail("New Horizon", 1001); +// Student student = new Student("Satish", 22, "Indian", studentDetail); +// session.save(student); + + Student std = session.get(Student.class, 1L); + System.out.println(std); + + session.delete(std); + + session.getTransaction().commit(); + + } finally { + sessionFactory.close(); + } + } +} diff --git a/src/com/jm3007/learn/hibernate/association/onetoone/uni/StudentDetail.java b/src/com/jm3007/learn/hibernate/association/onetoone/uni/StudentDetail.java new file mode 100644 index 0000000..f7f8a7f --- /dev/null +++ b/src/com/jm3007/learn/hibernate/association/onetoone/uni/StudentDetail.java @@ -0,0 +1,65 @@ +package com.jm3007.learn.hibernate.association.onetoone.uni; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "JM3007_ONETOONE_UNI_STUDENT_DETAIL") +public class StudentDetail { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "college_name") + private String collegeName; + + @Column(name = "ROLL_NO") + private Integer rollNo; + + public Long getId() { + return id; + } + + public StudentDetail(String collegeName, Integer rollNo) { + super(); + this.collegeName = collegeName; + this.rollNo = rollNo; + } + + public StudentDetail() { + super(); + // TODO Auto-generated constructor stub + } + + public void setId(Long id) { + this.id = id; + } + + public String getCollegeName() { + return collegeName; + } + + public void setCollegeName(String collegeName) { + this.collegeName = collegeName; + } + + public Integer getRollNo() { + return rollNo; + } + + public void setRollNo(Integer rollNo) { + this.rollNo = rollNo; + } + + @Override + public String toString() { + return "StudentDetail [id=" + id + ", collegeName=" + collegeName + ", rollNo=" + rollNo + "]"; + } + +} diff --git a/src/com/jm3007/learn/hibernate/association/onetoone/uni/ont-to-one-uni.sql b/src/com/jm3007/learn/hibernate/association/onetoone/uni/ont-to-one-uni.sql new file mode 100644 index 0000000..886e658 --- /dev/null +++ b/src/com/jm3007/learn/hibernate/association/onetoone/uni/ont-to-one-uni.sql @@ -0,0 +1,14 @@ +CREATE TABLE JM3007_ONETOONE_UNI_STUDENT_DETAIL( +ID BIGINT AUTO_INCREMENT PRIMARY KEY, +COLLEGE_NAME VARCHAR(50), +ROLL_NO NUMBER, +); + +CREATE TABLE JM3007_ONETOONE_UNI_STUDENT( +ID BIGINT AUTO_INCREMENT PRIMARY KEY, +NAME VARCHAR(50), +AGE NUMBER, +NATIONALITY VARCHAR(50), +STUDENT_DETAIL_ID BIGINT, +FOREIGN KEY (STUDENT_DETAIL_ID) REFERENCES JM3007_ONETOONE_UNI_STUDENT_DETAIL(ID) +); \ No newline at end of file From c9c9c129061bfc2c897d28d027ce870d6d2f7cdf Mon Sep 17 00:00:00 2001 From: Code WellnWill Date: Sun, 3 Feb 2019 14:57:18 +0530 Subject: [PATCH 16/19] Many to Many --- .../association/manytomany/bi/Address.java | 59 +++++++++++++ .../manytomany/bi/ManyToManyBiApp.java | 67 +++++++++++++++ .../association/manytomany/bi/Person.java | 67 +++++++++++++++ .../manytomany/bi/hibernate.cfg.xml | 22 +++++ .../manytomany/bi/manytomany-bi.sql | 27 ++++++ .../association/manytomany/uni/Address.java | 60 +++++++++++++ .../manytomany/uni/ManyToManyUniApp.java | 84 +++++++++++++++++++ .../association/manytomany/uni/Person.java | 73 ++++++++++++++++ .../manytomany/uni/manytomany-uni.sql | 25 ++++++ .../association/onetomany/bi/Assignment.java | 68 +++++++++++++++ .../association/onetomany/bi/Course.java | 78 +++++++++++++++++ .../association/onetomany/bi/CourseApp.java | 37 ++++++++ .../onetomany/bi/one-to-many-bi.sql | 11 +++ .../association/onetoone/bi/Student.java | 6 ++ 14 files changed, 684 insertions(+) create mode 100644 src/com/jm3007/learn/hibernate/association/manytomany/bi/Address.java create mode 100644 src/com/jm3007/learn/hibernate/association/manytomany/bi/ManyToManyBiApp.java create mode 100644 src/com/jm3007/learn/hibernate/association/manytomany/bi/Person.java create mode 100644 src/com/jm3007/learn/hibernate/association/manytomany/bi/hibernate.cfg.xml create mode 100644 src/com/jm3007/learn/hibernate/association/manytomany/bi/manytomany-bi.sql create mode 100644 src/com/jm3007/learn/hibernate/association/manytomany/uni/Address.java create mode 100644 src/com/jm3007/learn/hibernate/association/manytomany/uni/ManyToManyUniApp.java create mode 100644 src/com/jm3007/learn/hibernate/association/manytomany/uni/Person.java create mode 100644 src/com/jm3007/learn/hibernate/association/manytomany/uni/manytomany-uni.sql create mode 100644 src/com/jm3007/learn/hibernate/association/onetomany/bi/Assignment.java create mode 100644 src/com/jm3007/learn/hibernate/association/onetomany/bi/Course.java create mode 100644 src/com/jm3007/learn/hibernate/association/onetomany/bi/CourseApp.java create mode 100644 src/com/jm3007/learn/hibernate/association/onetomany/bi/one-to-many-bi.sql diff --git a/src/com/jm3007/learn/hibernate/association/manytomany/bi/Address.java b/src/com/jm3007/learn/hibernate/association/manytomany/bi/Address.java new file mode 100644 index 0000000..2978797 --- /dev/null +++ b/src/com/jm3007/learn/hibernate/association/manytomany/bi/Address.java @@ -0,0 +1,59 @@ +package com.jm3007.learn.hibernate.association.manytomany.bi; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToMany; +import javax.persistence.Table; + +@Entity +@Table(name = "JM3007_MANYTOMANY_BI_Address") +public class Address { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "street") + private String street; + + @Column(name = "number") + private String number; + + @ManyToMany(mappedBy = "addresses", cascade=CascadeType.ALL) + private List owners = new ArrayList(); + + public Address() { + } + + public Address(String street, String number) { + this.street = street; + this.number = number; + } + + public Long getId() { + return id; + } + + public String getStreet() { + return street; + } + + public String getNumber() { + return number; + } + + public List getOwners() { + return owners; + } + + public void setOwners(List owners) { + this.owners = owners; + } +} diff --git a/src/com/jm3007/learn/hibernate/association/manytomany/bi/ManyToManyBiApp.java b/src/com/jm3007/learn/hibernate/association/manytomany/bi/ManyToManyBiApp.java new file mode 100644 index 0000000..0647ad4 --- /dev/null +++ b/src/com/jm3007/learn/hibernate/association/manytomany/bi/ManyToManyBiApp.java @@ -0,0 +1,67 @@ +package com.jm3007.learn.hibernate.association.manytomany.bi; + +import java.util.ArrayList; +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; + +public class ManyToManyBiApp { + + static SessionFactory sessionFacoty = null; + static Session session = null; + + public static void main(String[] args) { + + try { + sessionFacoty = new Configuration() + .configure("hibernate.cfg.xml") + .addAnnotatedClass(Person.class) + .addAnnotatedClass(Address.class) + .buildSessionFactory(); + session = sessionFacoty.getCurrentSession(); + + insert(); +// remove(); + + } finally { + sessionFacoty.close(); + } + } + + public static void insert() { + session.beginTransaction(); + + Person person1 = new Person("ABC-123"); + Person person2 = new Person("DEF-456"); + + Address address1 = new Address("12th Avenue", "12A"); + Address address2 = new Address("18th Avenue", "18B"); + + person1.addAddress(address1); + person1.addAddress(address2); + + person2.addAddress(address1); + +// session.save(person1); +// session.save(person2); + + session.save(address1); + session.save(address2); + + session.getTransaction().commit(); + } + + public static void remove() { + session.beginTransaction(); + + Person person1 = session.get(Person.class, 1l); + Address address1 = session.get(Address.class, 1l); + Address address2 = session.get(Address.class, 1l); + + person1.getAddresses().remove(address1); + + session.getTransaction().commit(); + } +} diff --git a/src/com/jm3007/learn/hibernate/association/manytomany/bi/Person.java b/src/com/jm3007/learn/hibernate/association/manytomany/bi/Person.java new file mode 100644 index 0000000..ec0ca3c --- /dev/null +++ b/src/com/jm3007/learn/hibernate/association/manytomany/bi/Person.java @@ -0,0 +1,67 @@ +package com.jm3007.learn.hibernate.association.manytomany.bi; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToMany; +import javax.persistence.Table; + +@Entity +@Table(name = "JM3007_MANYTOMANY_BI_Person") +public class Person { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "name") + private String name; + + @ManyToMany(cascade = { CascadeType.ALL }) + private List
addresses = new ArrayList<>(); + + public Person() { + } + + public List
getAddresses() { + return addresses; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Person(String name) { + super(); + this.name = name; + } + + //hand-shaking method + public void addAddress(Address address) { + addresses.add(address); + address.getOwners().add(this); + } + + public void removeAddress(Address address) { + addresses.remove(address); + address.getOwners().remove(this); + } +} diff --git a/src/com/jm3007/learn/hibernate/association/manytomany/bi/hibernate.cfg.xml b/src/com/jm3007/learn/hibernate/association/manytomany/bi/hibernate.cfg.xml new file mode 100644 index 0000000..0755370 --- /dev/null +++ b/src/com/jm3007/learn/hibernate/association/manytomany/bi/hibernate.cfg.xml @@ -0,0 +1,22 @@ + + + + + + + + + + org.h2.Driver + jdbc:h2:~/hfw_manytomany_bi + sa + sa + 1 + org.hibernate.dialect.H2Dialect + true + thread + + + \ No newline at end of file diff --git a/src/com/jm3007/learn/hibernate/association/manytomany/bi/manytomany-bi.sql b/src/com/jm3007/learn/hibernate/association/manytomany/bi/manytomany-bi.sql new file mode 100644 index 0000000..e46a182 --- /dev/null +++ b/src/com/jm3007/learn/hibernate/association/manytomany/bi/manytomany-bi.sql @@ -0,0 +1,27 @@ +alter table JM3005_MANYTOMANY_BI_Person_JM3005_MANYTOMANY_BI_ADDRESS drop constraint BI_Owners_id_fk; + +CREATE TABLE JM3007_MANYTOMANY_BI_ADDRESS ( + idBIGINT AUTO_INCREMENT, + number VARCHAR(255) , + street VARCHAR(255) , + PRIMARY KEY ( id ) +); + +CREATE TABLE JM3007_MANYTOMANY_BI_Person ( + id BIGINT AUTO_INCREMENT, + name varchar, + PRIMARY KEY ( id ) +); + +CREATE TABLE JM3007_MANYTOMANY_BI_Person_JM3007_MANYTOMANY_BI_ADDRESS ( + Owners_id BIGINT NOT NULL , + addresses_id BIGINT NOT NULL +); + +ALTER TABLE JM3007_MANYTOMANY_BI_Person_JM3007_MANYTOMANY_BI_ADDRESS +ADD CONSTRAINT BI_addresses_id_fk +FOREIGN KEY (addresses_id) REFERENCES JM3007_MANYTOMANY_BI_ADDRESS; + +ALTER TABLE JM3007_MANYTOMANY_BI_Person_JM3007_MANYTOMANY_BI_ADDRESS +ADD CONSTRAINT BI_Owners_id_fk +FOREIGN KEY (Owners_id) REFERENCES JM3007_MANYTOMANY_BI_Person; \ No newline at end of file diff --git a/src/com/jm3007/learn/hibernate/association/manytomany/uni/Address.java b/src/com/jm3007/learn/hibernate/association/manytomany/uni/Address.java new file mode 100644 index 0000000..97ed9ca --- /dev/null +++ b/src/com/jm3007/learn/hibernate/association/manytomany/uni/Address.java @@ -0,0 +1,60 @@ +package com.jm3007.learn.hibernate.association.manytomany.uni; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "JM3007_MANYTOMANY_UNI_Address") +public class Address { + + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + private Long id; + + @Column(name="street") + private String street; + + @Column(name = "number") + private String number; + + public Address() { + } + + public Address(String street, String number) { + this.street = street; + this.number = number; + } + + public Long getId() { + return id; + } + + public String getStreet() { + return street; + } + + public String getNumber() { + return number; + } + + public void setId(Long id) { + this.id = id; + } + + public void setStreet(String street) { + this.street = street; + } + + public void setNumber(String number) { + this.number = number; + } + + @Override + public String toString() { + return "Address [id=" + id + ", street=" + street + ", number=" + number + "]"; + } +} diff --git a/src/com/jm3007/learn/hibernate/association/manytomany/uni/ManyToManyUniApp.java b/src/com/jm3007/learn/hibernate/association/manytomany/uni/ManyToManyUniApp.java new file mode 100644 index 0000000..c4ff5ae --- /dev/null +++ b/src/com/jm3007/learn/hibernate/association/manytomany/uni/ManyToManyUniApp.java @@ -0,0 +1,84 @@ +package com.jm3007.learn.hibernate.association.manytomany.uni; + +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; + +public class ManyToManyUniApp { + + static SessionFactory sessionFacoty = null; + static Session session = null; + + public static void main(String[] args) { + + try { + sessionFacoty = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Person.class) + .addAnnotatedClass(Address.class).buildSessionFactory(); + session = sessionFacoty.getCurrentSession(); + +// insert(); +// getPerson(); +// addOneMoreAddressInExistingPerson(); + remove(); + + } finally { + sessionFacoty.close(); + } + } + + private static void addOneMoreAddressInExistingPerson() { + session.beginTransaction(); + + Person p = session.get(Person.class, 1L); + List
addrs = p.getAddresses(); + + Address address3 = new Address("Marathalli", "HDFC Bank"); + addrs.add(address3); + + session.getTransaction().commit(); + } + + private static void getPerson() { + session.beginTransaction(); + + Person p = session.get(Person.class, 1L); + System.out.println(p); + + session.getTransaction().commit(); + + } + + public static void insert() { + session.beginTransaction(); + + Person person1 = new Person("Atul"); + Person person2 = new Person("At"); + + Address address1 = new Address("12th Avenue", "12A"); + Address address2 = new Address("18th Avenue", "18B"); + + person1.getAddresses().add(address1); + person1.getAddresses().add(address2); + + person2.getAddresses().add(address1); + + session.save(person1); + session.save(person2); + + session.getTransaction().commit(); + } + + public static void remove() { + session.beginTransaction(); + +// Person person1 = session.get(Person.class, 1l); + Person person2 = session.get(Person.class, 2l); +// Address address1 = session.get(Address.class, 1l); + +// person1.getAddresses().remove(address1); + session.remove(person2); + session.getTransaction().commit(); + } +} diff --git a/src/com/jm3007/learn/hibernate/association/manytomany/uni/Person.java b/src/com/jm3007/learn/hibernate/association/manytomany/uni/Person.java new file mode 100644 index 0000000..bed7d09 --- /dev/null +++ b/src/com/jm3007/learn/hibernate/association/manytomany/uni/Person.java @@ -0,0 +1,73 @@ +package com.jm3007.learn.hibernate.association.manytomany.uni; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToMany; +import javax.persistence.Table; + +@Entity +@Table(name = "JM3007_MANYTOMANY_UNI_Person") +public class Person { + + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name="name") + private String name; + + @ManyToMany(cascade = { CascadeType.ALL }) + private List
addresses = new ArrayList<>(); + + public Person() { + } + + public List
getAddresses() { + return addresses; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Person(String name) { + super(); + this.name = name; + } + + public void setAddr(Address addr) { + if(addresses == null) { + addresses = new ArrayList<>(); + } + addresses.add(addr); + } + + @Override + public String toString() { + return "Person [id=" + id + ", name=" + name + ", addresses=" + addresses + "]"; + } + + public void setAddresses(List
addresses) { + this.addresses = addresses; + } +} diff --git a/src/com/jm3007/learn/hibernate/association/manytomany/uni/manytomany-uni.sql b/src/com/jm3007/learn/hibernate/association/manytomany/uni/manytomany-uni.sql new file mode 100644 index 0000000..c4316de --- /dev/null +++ b/src/com/jm3007/learn/hibernate/association/manytomany/uni/manytomany-uni.sql @@ -0,0 +1,25 @@ +CREATE TABLE JM3007_MANYTOMANY_UNI_Person ( + id BIGINT AUTO_INCREMENT, + name varchar, + PRIMARY KEY ( id ) +); + +CREATE TABLE JM3007_MANYTOMANY_UNI_Address ( + id BIGINT AUTO_INCREMENT, + number VARCHAR(255) , + street VARCHAR(255) , + PRIMARY KEY ( id ) +); + +CREATE TABLE JM3007_MANYTOMANY_UNI_Person_JM3007_MANYTOMANY_UNI_Address ( + Person_id BIGINT NOT NULL , + addresses_id BIGINT NOT NULL +); + +ALTER TABLE JM3007_MANYTOMANY_UNI_Person_JM3007_MANYTOMANY_UNI_Address +ADD CONSTRAINT addresses_id_fk +FOREIGN KEY (addresses_id) REFERENCES JM3007_MANYTOMANY_UNI_Address; + +ALTER TABLE JM3007_MANYTOMANY_UNI_Person_JM3007_MANYTOMANY_UNI_Address +ADD CONSTRAINT Person_id_fk +FOREIGN KEY (Person_id) REFERENCES JM3007_MANYTOMANY_UNI_Person; \ No newline at end of file diff --git a/src/com/jm3007/learn/hibernate/association/onetomany/bi/Assignment.java b/src/com/jm3007/learn/hibernate/association/onetomany/bi/Assignment.java new file mode 100644 index 0000000..5e7996f --- /dev/null +++ b/src/com/jm3007/learn/hibernate/association/onetomany/bi/Assignment.java @@ -0,0 +1,68 @@ +package com.jm3007.learn.hibernate.association.onetomany.bi; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Table; + +@Entity +@Table(name = "JM3007_ONETOMANY_BI_ASSIGNMENT") +public class Assignment { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + public Course getCourse() { + return course; + } + + public void setCourse(Course course) { + this.course = course; + } + + @Column(name = "name") + private String name; + + @JoinColumn(name="COURSE_ID") + @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE}) + private Course course; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Assignment() { + super(); + // TODO Auto-generated constructor stub + } + + public Assignment(String name) { + super(); + this.name = name; + } + + @Override + public String toString() { + return "Assignment [id=" + id + ", name=" + name + "]"; + } + +} diff --git a/src/com/jm3007/learn/hibernate/association/onetomany/bi/Course.java b/src/com/jm3007/learn/hibernate/association/onetomany/bi/Course.java new file mode 100644 index 0000000..2c7d67a --- /dev/null +++ b/src/com/jm3007/learn/hibernate/association/onetomany/bi/Course.java @@ -0,0 +1,78 @@ +package com.jm3007.learn.hibernate.association.onetomany.bi; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToMany; +import javax.persistence.Table; + +@Entity +@Table(name = "JM3007_ONETOMANY_BI_COURSE") +public class Course { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "name") + private String name; + + @OneToMany(cascade = CascadeType.ALL, mappedBy = "course") + private List assignments; + + public Long getId() { + return id; + } + + public Course(String name) { + super(); + this.name = name; + } + + public Course() { + super(); + // TODO Auto-generated constructor stub + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getAssignments() { + return assignments; + } + + public void setAssignments(List assignments) { + this.assignments = assignments; + } + + public void addAssignment(Assignment assignment) { + if (assignments == null) { + assignments = new ArrayList<>(); + } + assignment.setCourse(this); + assignments.add(assignment); + } + + @Override + public String toString() { + return "Course [id=" + id + ", name=" + name + ", assignments=" + assignments + "]"; + } + +} diff --git a/src/com/jm3007/learn/hibernate/association/onetomany/bi/CourseApp.java b/src/com/jm3007/learn/hibernate/association/onetomany/bi/CourseApp.java new file mode 100644 index 0000000..7b835d4 --- /dev/null +++ b/src/com/jm3007/learn/hibernate/association/onetomany/bi/CourseApp.java @@ -0,0 +1,37 @@ +package com.jm3007.learn.hibernate.association.onetomany.bi; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; + +public class CourseApp { + public static void main(String[] args) { + SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml") + .addAnnotatedClass(Course.class).addAnnotatedClass(Assignment.class).buildSessionFactory(); + + Session session = sessionFactory.getCurrentSession(); + + try { + session.beginTransaction(); + + /*Assignment assignemnt = new Assignment("Bi Directional 1"); + Course course = new Course("Mapping"); + course.addAssignment(assignemnt); + session.save(assignemnt); + session.getTransaction().commit(); +*/ + + /* Assignment assignemnt = new Assignment("Bi Directional 1"); + Course course = session.get(Course.class, 2L); + course.addAssignment(assignemnt); + session.save(assignemnt); + session.getTransaction().commit();*/ + + Assignment assignment = session.get(Assignment.class, 3L); + session.delete(assignment); + session.getTransaction().commit(); + } finally { + sessionFactory.close(); + } + } +} diff --git a/src/com/jm3007/learn/hibernate/association/onetomany/bi/one-to-many-bi.sql b/src/com/jm3007/learn/hibernate/association/onetomany/bi/one-to-many-bi.sql new file mode 100644 index 0000000..42f013f --- /dev/null +++ b/src/com/jm3007/learn/hibernate/association/onetomany/bi/one-to-many-bi.sql @@ -0,0 +1,11 @@ +CREATE TABLE JM3007_ONETOMANY_BI_COURSE( +ID BIGINT AUTO_INCREMENT PRIMARY KEY, +NAME VARCHAR(50) +); + +CREATE TABLE JM3007_ONETOMANY_BI_ASSIGNMENT( +ID BIGINT AUTO_INCREMENT PRIMARY KEY, +NAME VARCHAR(50), +COURSE_ID BIGINT, +FOREIGN KEY (COURSE_ID) REFERENCES JM3007_ONETOMANY_BI_COURSE(ID) +); \ No newline at end of file diff --git a/src/com/jm3007/learn/hibernate/association/onetoone/bi/Student.java b/src/com/jm3007/learn/hibernate/association/onetoone/bi/Student.java index 631ff74..ce175b8 100644 --- a/src/com/jm3007/learn/hibernate/association/onetoone/bi/Student.java +++ b/src/com/jm3007/learn/hibernate/association/onetoone/bi/Student.java @@ -55,6 +55,12 @@ public void setStudentDetail(StudentDetail studentDetail) { this.studentDetail = studentDetail; } + public void addStudentDetail(StudentDetail studentDetail) { + studentDetail.setStudent(this); + this.studentDetail = studentDetail; + } + + public Long getId() { return id; } From 71d4d6727f109aa2d29a88b129f92133763dc369 Mon Sep 17 00:00:00 2001 From: Code WellnWill Date: Sun, 10 Feb 2019 13:35:22 +0530 Subject: [PATCH 17/19] Spring REST --- WebContent/WEB-INF/spring-config.xml | 37 +++++++++++- WebContent/WEB-INF/sql/imp-sql.sql | 5 ++ pom.xml | 46 +++++++++++++++ .../rest/controller/CustomerController.java | 51 ++++++++++++++++ .../learn/spring/rest/dao/CustomerDao.java | 17 ++++++ .../spring/rest/dao/CustomerDaoImpl.java | 51 ++++++++++++++++ .../learn/spring/rest/model/Customer.java | 59 +++++++++++++++++++ .../spring/rest/service/CustomerService.java | 17 ++++++ .../rest/service/CustomerServiceImpl.java | 42 +++++++++++++ 9 files changed, 324 insertions(+), 1 deletion(-) create mode 100644 WebContent/WEB-INF/sql/imp-sql.sql create mode 100644 src/com/jm3007/learn/spring/rest/controller/CustomerController.java create mode 100644 src/com/jm3007/learn/spring/rest/dao/CustomerDao.java create mode 100644 src/com/jm3007/learn/spring/rest/dao/CustomerDaoImpl.java create mode 100644 src/com/jm3007/learn/spring/rest/model/Customer.java create mode 100644 src/com/jm3007/learn/spring/rest/service/CustomerService.java create mode 100644 src/com/jm3007/learn/spring/rest/service/CustomerServiceImpl.java diff --git a/WebContent/WEB-INF/spring-config.xml b/WebContent/WEB-INF/spring-config.xml index 823bc77..60dcd5e 100644 --- a/WebContent/WEB-INF/spring-config.xml +++ b/WebContent/WEB-INF/spring-config.xml @@ -17,7 +17,7 @@ http://www.springframework.org/schema/aop/spring-aop.xsd"> + base-package="com.jm3007.learn.spring.rest" /> + + + + + + + + + + + + + + + + + + + org.hibernate.dialect.H2Dialect + true + true + + + + + + + + + \ No newline at end of file diff --git a/WebContent/WEB-INF/sql/imp-sql.sql b/WebContent/WEB-INF/sql/imp-sql.sql new file mode 100644 index 0000000..b69bf04 --- /dev/null +++ b/WebContent/WEB-INF/sql/imp-sql.sql @@ -0,0 +1,5 @@ +CREATE TABLE JM3007_CUSTOMER( +ID BIGINT PRIMARY KEY AUTO_INCREMENT, +NAME VARCHAR(50), +AGE NUMBER +) \ No newline at end of file diff --git a/pom.xml b/pom.xml index 0518fda..924382b 100644 --- a/pom.xml +++ b/pom.xml @@ -15,16 +15,62 @@ spring-webmvc 5.1.3.RELEASE + + + org.springframework + spring-orm + 5.1.3.RELEASE + + org.hibernate.validator hibernate-validator 6.0.13.Final + + + org.hibernate hibernate-core 5.4.0.Final + + org.hibernate + hibernate-c3p0 + 5.4.0.Final + + + org.hibernate + hibernate-ehcache + 5.4.0.Final + + + net.sf.ehcache + ehcache + 2.10.6 + + + org.hibernate + hibernate-entitymanager + 5.4.0.Final + + + org.hibernate + hibernate-envers + 5.4.0.Final + + + org.hibernate + hibernate-infinispan + 5.4.0.Final + + + com.fasterxml.jackson.core + jackson-databind + 2.9.5 + + com.h2database h2 diff --git a/src/com/jm3007/learn/spring/rest/controller/CustomerController.java b/src/com/jm3007/learn/spring/rest/controller/CustomerController.java new file mode 100644 index 0000000..30ce79c --- /dev/null +++ b/src/com/jm3007/learn/spring/rest/controller/CustomerController.java @@ -0,0 +1,51 @@ +package com.jm3007.learn.spring.rest.controller; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import com.jm3007.learn.spring.rest.model.Customer; +import com.jm3007.learn.spring.rest.service.CustomerService; + +@RestController +@RequestMapping(value = "/rest/v1/customers") +public class CustomerController { + + @Autowired + private CustomerService customerService; + + @PostMapping(value = "/") + public Long saveCustomer(@RequestBody Customer customer) { + return customerService.saveCustomer(customer); + } + + @RequestMapping(value = "/{id}", method = RequestMethod.GET) + public Customer getCustomer(@PathVariable("id") Long id) { + return customerService.getCustomer(id); + } + + @GetMapping("/") + public List getCustomers() { + return customerService.getCustomers(); + } + + @PutMapping("/") + void updateCustomer(@RequestBody Customer customer) { + customerService.updateCustomer(customer); + } + + @DeleteMapping("/{id}") + void deleteCustomer(@PathVariable("id") Long id) { + customerService.deleteCustomer(id); + } + +} diff --git a/src/com/jm3007/learn/spring/rest/dao/CustomerDao.java b/src/com/jm3007/learn/spring/rest/dao/CustomerDao.java new file mode 100644 index 0000000..32e4eac --- /dev/null +++ b/src/com/jm3007/learn/spring/rest/dao/CustomerDao.java @@ -0,0 +1,17 @@ +package com.jm3007.learn.spring.rest.dao; + +import java.util.List; + +import com.jm3007.learn.spring.rest.model.Customer; + +public interface CustomerDao { + Long saveCustomer(Customer customer); + + Customer getCustomer(Long id); + + List getCustomers(); + + void updateCustomer(Customer customer); + + void deleteCustomer(Long id); +} diff --git a/src/com/jm3007/learn/spring/rest/dao/CustomerDaoImpl.java b/src/com/jm3007/learn/spring/rest/dao/CustomerDaoImpl.java new file mode 100644 index 0000000..a0e3ff2 --- /dev/null +++ b/src/com/jm3007/learn/spring/rest/dao/CustomerDaoImpl.java @@ -0,0 +1,51 @@ +package com.jm3007.learn.spring.rest.dao; + +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +import com.jm3007.learn.spring.rest.model.Customer; + +@Repository +public class CustomerDaoImpl implements CustomerDao { + + @Autowired + private SessionFactory sessionFactory; + + @Override + @Transactional + public Long saveCustomer(Customer customer) { + return (Long) sessionFactory.openSession().save(customer); + } + + @Override + @Transactional + public Customer getCustomer(Long id) { + return sessionFactory.openSession().get(Customer.class, id); + } + + @Override + @Transactional + public List getCustomers() { + return sessionFactory.openSession().createQuery("from Customer").getResultList(); + } + + @Override + @Transactional + public void updateCustomer(Customer customer) { + sessionFactory.getCurrentSession().saveOrUpdate(customer); + } + + @Override + @Transactional + public void deleteCustomer(Long id) { + Session session = sessionFactory.getCurrentSession(); + Customer customer = session.get(Customer.class, id); + session.delete(customer); + } + +} diff --git a/src/com/jm3007/learn/spring/rest/model/Customer.java b/src/com/jm3007/learn/spring/rest/model/Customer.java new file mode 100644 index 0000000..c53e848 --- /dev/null +++ b/src/com/jm3007/learn/spring/rest/model/Customer.java @@ -0,0 +1,59 @@ +package com.jm3007.learn.spring.rest.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "JM3007_CUSTOMER") +public class Customer { + + @Id + @Column(name = "id") + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "name") + private String name; + + @Column(name = "age") + private int age; + + public Customer(String name, int age) { + super(); + this.name = name; + this.age = age; + } + + public Customer() { + super(); + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + +} diff --git a/src/com/jm3007/learn/spring/rest/service/CustomerService.java b/src/com/jm3007/learn/spring/rest/service/CustomerService.java new file mode 100644 index 0000000..7927c15 --- /dev/null +++ b/src/com/jm3007/learn/spring/rest/service/CustomerService.java @@ -0,0 +1,17 @@ +package com.jm3007.learn.spring.rest.service; + +import java.util.List; + +import com.jm3007.learn.spring.rest.model.Customer; + +public interface CustomerService { + Long saveCustomer(Customer customer); + + Customer getCustomer(Long id); + + List getCustomers(); + + void updateCustomer(Customer customer); + + void deleteCustomer(Long id); +} diff --git a/src/com/jm3007/learn/spring/rest/service/CustomerServiceImpl.java b/src/com/jm3007/learn/spring/rest/service/CustomerServiceImpl.java new file mode 100644 index 0000000..0618e65 --- /dev/null +++ b/src/com/jm3007/learn/spring/rest/service/CustomerServiceImpl.java @@ -0,0 +1,42 @@ +package com.jm3007.learn.spring.rest.service; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.jm3007.learn.spring.rest.dao.CustomerDao; +import com.jm3007.learn.spring.rest.model.Customer; + +@Service +public class CustomerServiceImpl implements CustomerService { + + @Autowired + private CustomerDao customerDao; + + @Override + public Long saveCustomer(Customer customer) { + return customerDao.saveCustomer(customer); + } + + @Override + public Customer getCustomer(Long id) { + return customerDao.getCustomer(id); + } + + @Override + public List getCustomers() { + return customerDao.getCustomers(); + } + + @Override + public void updateCustomer(Customer customer) { + customerDao.updateCustomer(customer); + } + + @Override + public void deleteCustomer(Long id) { + customerDao.deleteCustomer(id); + } + +} From d6afd17989e65406d8962e8632400844a0b56115 Mon Sep 17 00:00:00 2001 From: Code WellnWill Date: Sat, 16 Feb 2019 11:28:11 +0530 Subject: [PATCH 18/19] AOP --- WebContent/WEB-INF/spring-config.xml | 2 +- pom.xml | 15 +++++++---- .../spring/rest/aspect/LoggingAspect.java | 27 +++++++++++++++++++ 3 files changed, 38 insertions(+), 6 deletions(-) create mode 100644 src/com/jm3007/learn/spring/rest/aspect/LoggingAspect.java diff --git a/WebContent/WEB-INF/spring-config.xml b/WebContent/WEB-INF/spring-config.xml index 60dcd5e..561122d 100644 --- a/WebContent/WEB-INF/spring-config.xml +++ b/WebContent/WEB-INF/spring-config.xml @@ -15,7 +15,7 @@ http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> - + diff --git a/pom.xml b/pom.xml index 924382b..ba5e779 100644 --- a/pom.xml +++ b/pom.xml @@ -15,6 +15,11 @@ spring-webmvc 5.1.3.RELEASE + + org.aspectj + aspectjweaver + 1.9.2 + org.springframework @@ -45,11 +50,11 @@ hibernate-ehcache 5.4.0.Final - - net.sf.ehcache - ehcache - 2.10.6 - + + net.sf.ehcache + ehcache + 2.10.6 + org.hibernate hibernate-entitymanager diff --git a/src/com/jm3007/learn/spring/rest/aspect/LoggingAspect.java b/src/com/jm3007/learn/spring/rest/aspect/LoggingAspect.java new file mode 100644 index 0000000..d95e401 --- /dev/null +++ b/src/com/jm3007/learn/spring/rest/aspect/LoggingAspect.java @@ -0,0 +1,27 @@ +package com.jm3007.learn.spring.rest.aspect; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.After; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.aspectj.lang.annotation.Pointcut; +import org.springframework.stereotype.Component; + +@Component +@Aspect +public class LoggingAspect { + + @Pointcut("execution (* com.jm3007.learn.spring.rest.*.*.get*(..))") + public void allTheMethodsInLayers() { + } + + @Before(value = "allTheMethodsInLayers()") + public void doSomething(JoinPoint joinPoint) { + System.out.println(">> " + joinPoint.getSignature().getName()); + } + + @After(value = "allTheMethodsInLayers()") + public void doAnotherThing(JoinPoint joinPoint) { + System.out.println("<< " + joinPoint.getSignature().getName()); + } +} From 0e7557c01f8b9b2e88bed958553447699e995b71 Mon Sep 17 00:00:00 2001 From: Code WellnWill Date: Sun, 17 Feb 2019 10:53:09 +0530 Subject: [PATCH 19/19] AOP --- .../spring/rest/aspect/LoggingAspect.java | 51 +++++++++++++++++-- .../spring/rest/dao/CustomerDaoImpl.java | 6 ++- 2 files changed, 53 insertions(+), 4 deletions(-) diff --git a/src/com/jm3007/learn/spring/rest/aspect/LoggingAspect.java b/src/com/jm3007/learn/spring/rest/aspect/LoggingAspect.java index d95e401..d757e9d 100644 --- a/src/com/jm3007/learn/spring/rest/aspect/LoggingAspect.java +++ b/src/com/jm3007/learn/spring/rest/aspect/LoggingAspect.java @@ -1,27 +1,72 @@ package com.jm3007.learn.spring.rest.aspect; +import java.util.Collections; +import java.util.List; + import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.After; +import org.aspectj.lang.annotation.AfterReturning; +import org.aspectj.lang.annotation.AfterThrowing; +import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; +import com.jm3007.learn.spring.rest.model.Customer; + @Component @Aspect public class LoggingAspect { - @Pointcut("execution (* com.jm3007.learn.spring.rest.*.*.get*(..))") + @Pointcut("execution (* com.jm3007.learn.spring.rest.*.*.*(..))") public void allTheMethodsInLayers() { } + @Pointcut("execution (* com.jm3007.learn.spring.rest.*.*.get*(..))") + public void allGetMethodsInLayers() { + } + + @Pointcut("execution (* com.jm3007.learn.spring.rest.dao.CustomerDaoImpl.getCustomers(..))") + public void getCustomersMethodInDao() { + } + @Before(value = "allTheMethodsInLayers()") public void doSomething(JoinPoint joinPoint) { - System.out.println(">> " + joinPoint.getSignature().getName()); + System.out.println( + ">> " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); } - @After(value = "allTheMethodsInLayers()") + @After(value = "allGetMethodsInLayers()") public void doAnotherThing(JoinPoint joinPoint) { System.out.println("<< " + joinPoint.getSignature().getName()); } + + @AfterReturning(pointcut = "allGetMethodsInLayers()", returning = "retVal") + public void afterReturning(Object retVal) { + if (retVal instanceof Customer) { + System.out.println(((Customer) retVal).getName()); + } + } + + @AfterThrowing(pointcut = "allGetMethodsInLayers()", throwing = "ex") + public void afterThrowing(Exception ex) { + System.out.println("------" + ex.getMessage()); + } + + @Around(value="getCustomersMethodInDao()") + public void getCustomersMethodAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{ + //pre-processing: like Before Advice of around + System.out.println("I'm here"); + +// Object obj = proceedingJoinPoint.proceed(); + + //post-processing: like After Advice of around +// if(obj instanceof List) { +// System.out.println(((List) obj).get(0).getName()); +// } +// return Collections.emptyList(); + } + } diff --git a/src/com/jm3007/learn/spring/rest/dao/CustomerDaoImpl.java b/src/com/jm3007/learn/spring/rest/dao/CustomerDaoImpl.java index a0e3ff2..938235d 100644 --- a/src/com/jm3007/learn/spring/rest/dao/CustomerDaoImpl.java +++ b/src/com/jm3007/learn/spring/rest/dao/CustomerDaoImpl.java @@ -25,7 +25,11 @@ public Long saveCustomer(Customer customer) { @Override @Transactional public Customer getCustomer(Long id) { - return sessionFactory.openSession().get(Customer.class, id); + Customer c = sessionFactory.openSession().get(Customer.class, id); + if(c == null) { + throw new RuntimeException("Customer Not Found!!!"); + } + return c; } @Override