-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpring Notes.txt
838 lines (648 loc) · 40.3 KB
/
Spring Notes.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
Download the jars from: https://repo.spring.io/release/org/springframework/spring/
****************************************************************************************************************************************************************************************************************************************************
Inversion of Control (IoC): The approach of outsourcing the construction and management of objects.
Spring Container > Primary Functions:
• Create and manage objects (Inversion of Control)
• Inject object’s dependencies (Dependency Injection)
Configuring Spring Container
• XML configuration file (legacy, but most legacy apps still use this)
• Java Annotations (modern)
• Java Source Code (modern)
Spring Development Process
1. Configure your Spring Beans
2. Create a Spring Container
3. Retrieve Beans from Spring Container
In newer spring versions by default logging is disabled. Refer "HEADS UP" video in IoC section to enable logging. (Video number: 25)
****************************************************************************************************************************************************************************************************************************************************
Dependency Injection (The dependency inversion principle):
• The client delegates to calls to another object the responsibility of providing its dependencies.
• Injecting helper objects.
Injection Types
• There are many types of injection with Spring
• We will cover the two most common
• Constructor Injection
• Setter Injection
• Will talk about "auto-wiring" in the Annotations section later
Development Process - Constructor Injection
1. Define the dependency interface and class
2. Create a constructor in your class for injections
3. Configure the dependency injection in Spring config file
Development Process - Setter Injection
1. Create setter method(s) in your class for injections
2. Configure the dependency injection in Spring config file
Development Process - Properties File
1. Create Properties File
2. Load Properties File in Spring config file
3. Reference values from Properties File
****************************************************************************************************************************************************************************************************************************************************
Bean Scopes
• Scope refers to the lifecycle of a bean
• How long does the bean live?
• How many instances are created?
• How is the bean shared?
Default Scope: Singleton
What Is a Singleton?
• Spring Container creates only one instance of the bean, by default
• It is cached in memory
• All requests for the bean will return a SHARED reference to the SAME bean
Spring Bean Scopes
• singleton : Create a single shared instance of the bean. Default scope.
• prototype : Creates a new bean instance for each container request.
• request : Scoped to an HTTP web request. Only used for web apps.
• session : Scoped to an HTTP web session. Only used for web apps.
• global-session : Scoped to a global HTTP web session. Only used for web apps.
Bean Lifecycle
# Start:-
STEP 1: Container Started
STEP 2: Bean Instantiated
STEP 3: Dependencies Injected
STEP 4: Internal Spring Processing
STEP 5: Your Custom Init Method --> USER DEFINED
STEP 6: Bean Is Ready For Use
# Stop:-
STEP 1: Your Custom Destroy Method --> USER DEFINED
STEP 2: Stop the container
# Development Process:-
STEP 1: Define your methods for init and destroy
STEP 2: Configure the method names in Spring config file
# Special Note about init and destroy Method Signatures:-
When using XML configuration; the additional details regarding the method signatures of the init-method and destroy-method are as follows.
• Access modifier:
> The method can have any access modifier (public, protected, private).
• Return type:
> The method can have any return type.
> However, "void' is most commonly used.
> If you give a return type just note that you will not be able to capture the return value.
> As a result, "void" is commonly used.
• Method name:
> The method can have any method name.
• Arguments:
> The method can not accept any arguments.
> The method should be no-arg.
# Special Note about Destroy Lifecycle and Prototype Scope:-
There is a subtle point you need to be aware of with "prototype" scoped beans.
• For "prototype" scoped beans, Spring does not call the destroy method.
• In contrast to the other scopes, Spring does not manage the complete lifecycle of a prototype bean:
the container instantiates, configures, and otherwise assembles a prototype object, and hands it to the client,
with no further record of that prototype instance.
• Thus, although initialization lifecycle callback methods are called on all objects regardless of scope,
in the case of prototypes, configured destruction lifecycle callbacks are not called.
The client code must clean up prototype-scoped objects and release expensive resources that the prototype bean(s) are holding.
• This also applies to both XML configuration and Annotation-based configuration.
****************************************************************************************************************************************************************************************************************************************************
What are Java Annotations?
• Special labels/markers added to Java classes
• Provides meta-data about the class
• Processed at compile time or run-time for special processing
Why Spring Configuration with Annotations?
• XML configuration can be verbose
• Configure your Spring beans with Annotations
• Annotations minimizes the XML configuration
Scanning for Component Classes
• Spring will scan your Java classes for special annotations
• Automatically register the beans in the Spring container
Development Process
1. Enable component scanning in Spring config file
2. Add the @Component Annotation to your Java classes
3. Retrieve bean from Spring container
Spring also supports Default Bean IDs
• Though we can give a bean any ID of our liking but default ID is generally used
• Default bean id: the class name, make first letter lower-case
• Example: TennisCoach (Class Name) => tennisCoach (Default Bean Id)
****************************************************************************************************************************************************************************************************************************************************
What is Spring AutoWiring?
• For dependency injection, Spring can use auto wiring
• Spring will look for a class that matches the property
• Matches by type: class or interface
• Spring will inject it automatically … hence it is autowired
Autowiring Injection Types
• Constructor Injection
• Setter Injection
• Field Injections
Development Process - Constructor Injection
1. Define the dependency interface and class
2. Create a constructor in your class for injections
3. Configure the dependency injection with @Autowired Annotation
What if there are multiple FortuneService(Autowired Object) implementations?
Spring has special support to handle this case. Use the @Qualifier annotation.
Autowired - (Refer: "BaseballCoach" class in the third project part 1.)
• As of Spring Framework 4.3, an @Autowired annotation on such a constructor is
no longer necessary if the target bean only defines one constructor to begin with.
However, if several constructors are available, at least one must be annotated to
teach the container which one to use.
• I personally prefer to use the @Autowired annotation because it makes the code more
readable. But as mentioned, the @Autowired is not required for this scenario.
Development Process - Setter Injection
1. Create setter method(s) in your class for injections
2. Configure the dependency injection with @Autowired Annotation
Development Process - Method Injection
1. Create method(s) in your class for injections
2. Configure the dependency injection with @Autowired Annotation
Field Injection - Inject dependencies by setting field values on your class directly (even private fields). Accomplished by using Java Reflection.
Development Process - Field Injection
1. Configure the dependency injection with Autowired Annotation
✤ Applied directly to the field
✤ No need for setter methods
Annotations - Default Bean Names and the Special Case
In general, when using Annotations, for the default bean name, Spring uses the following rule.
If the annotation's value doesn't indicate a bean name, an appropriate name will be built based
on the short name of the class (with the first letter lower-cased). For example:
HappyFortuneService --> happyFortuneService
However, for the special case of when BOTH the first and second characters of the class name are
upper case, then the name is NOT converted. For example: RESTFortuneService --> RESTFortuneService
No conversion since the first two characters are upper case. Behind the scenes, Spring uses the
Java Beans Introspector to generate the default bean name. Here's a link to the documentation:
https://docs.oracle.com/javase/8/docs/api/java/beans/Introspector.html#decapitalize(java.lang.String)
As always, you can give explicit names to your beans.
@Component("foo")
public class RESTFortuneService .... {
}
Then you can access it using the name of "foo".
Using @Qualifier with Constructors
@Qualifier is a nice feature, but it is tricky when used with Constructors.
The syntax is much different from other examples and not exactly intuitive.
You have to place the @Qualifier annotation inside of the constructor arguments.
Here's an example:
@Component
public class TennisCoach implements Coach {
.....
@Autowired
public TennisCoach(@Qualifier("randomFortuneService") FortuneService theFortuneService) {
fortuneService = theFortuneService;
}
.....
}
For detailed documentation on using @Qualifier with Constructors, see the following link:
https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-autowired-annotation-qualifiers
When Spring creates the beans it follows this general process
1. Construct an instance of class
2. Inject dependencies
3. Set properties etc (@Value)
****************************************************************************************************************************************************************************************************************************************************
Bean Scope with annotations
1) Singleton
@Component
@Scope("singleton")
public class TennisCoach implements Coach {
...
}
2) Prototype
@Component
@Scope("prototype")
public class TennisCoach implements Coach {
...
}
Development Process - Bean Lifecycle Methods - Annotations
1. Define your methods for init and destroy
2. Add annotations: @PostConstruct and @PreDestroy
Special Note about @PostConstruct and @PreDestroy Method Signatures
I want to provide additional details regarding the method signatures of @PostContruct and @PreDestroy methods.
Access modifier
The method can have any access modifier (public, protected, private).
Return type
The method can have any return type. However, "void' is most commonly used.
If you give a return type just note that you will not be able to capture the return value.
As a result, "void" is commonly used.
Method name
The method can have any method name.
Arguments
The method can not accept any arguments. The method should be no-arg.
HEADS UP - FOR JAVA 9, 10 and 11 USERS - @PostConstruct and @PreDestroy
If you are using Java 9 or higher, then you will encounter an error when using
@PostConstruct and @PreDestroy in your code. These are the steps to resolve it.
Error: Eclipse is unable to import @PostConstruct or @PreDestroy
This happens because of Java 9 and higher. When using Java 9 and higher,
javax.annotation has been removed from its default classpath. That's why
Eclipse can't find it.
Solution:
1. Download the javax.annotation-api-1.3.2.jar from:
https://search.maven.org/remotecontent?filepath=javax/annotation/javax.annotation-api/1.3.2/javax.annotation-api-1.3.2.jar
2. Copy the JAR file to the lib folder of your project.
Use the following steps to add it to your Java Build Path.
3. Right-click your project, select Properties.
4. On left-hand side, click Java Build Path.
5. In top-center of dialog, click Libraries.
6. Click Classpath and then click Add JARs ...
7. Navigate to the JAR file <your-project>/lib/javax.annotation-api-1.3.2.jar.
8. Click OK then click Apply and Close.
Eclipse will perform a rebuild of your project and it will resolve the related build errors.
Special Note about Destroy Lifecycle and Prototype Scope
Here is a subtle point you need to be aware of with "prototype" scoped beans.
For "prototype" scoped beans, Spring does not call the @PreDestroy method.
Here is the answer from the Spring reference manual. Section 1.5.2:
https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-factory-scopes-prototype
In contrast to the other scopes, Spring does not manage the complete lifecycle of a
prototype bean: the container instantiates, configures, and otherwise assembles a
prototype object, and hands it to the client, with no further record of that prototype
instance.
Thus, although initialization lifecycle callback methods are called on all objects
regardless of scope, in the case of prototypes, configured destruction lifecycle
callbacks are not called. The client code must clean up prototype-scoped objects
and release expensive resources that the prototype bean(s) are holding.
To get the Spring container to release resources held by prototype-scoped beans,
try using a custom bean post-processor, which holds a reference to beans that
need to be cleaned up.
This also applies to XML configuration.
QUESTION: How can I create code to call the destroy method on prototype scope beans?
ANSWER:
You can destroy prototype beans but custom coding is required.
This examples shows how to destroy prototype scoped beans.
1. Create a custom bean processor. This bean processor will keep track of prototype scoped
beans. During shutdown it will call the destroy() method on the prototype scoped beans.
2. The prototype scoped beans MUST implement the DisposableBean interface. This interface
defines a "destory()" method. This method should be used instead of the @PreDestroy annotation.
3. In this app, BeanProcessorDemoApp.java is the main program. TennisCoach.java is the prototype
scoped bean. TennisCoach implements the DisposableBean interface and provides the destroy() method.
The custom bean processing is handled in the MyCustomBeanProcessor class.
See source code in the project named: 3-spring-config-with-annotations-part-3
****************************************************************************************************************************************************************************************************************************************************
Java Configuration
• Instead of configuring Spring container using XML
• Configure the Spring container with Java code
3 Ways of Configuring Spring Container
1. Full XML Config (Project number 1 & 2)
2. XML Component Scan (Project number 3 - all 3 parts)
3. Java Configuration Class (Project number 4)
Development Process - Java Configuration Class
1. Create a Java class and annotate as @Configuration
2. Add component scanning support: @ComponentScan (optional)
3. Read Spring Java configuration class
4. Retrieve bean from Spring container
In newer spring versions by default logging is disabled. Refer "HEADS UP" video (Video number: 86) OR refer forked gist on GitHub.
Development Process - Defining Bean - Java Configuration Class
1. Define method to expose bean
2. Inject bean dependencies
3. Read Spring Java configuration class
4. Retrieve bean from Spring container
Development Process - Properties File - Java Configuration Class
1. Create Properties File
2. Load Properties File in Spring config
3. Reference values from Properties File
****************************************************************************************************************************************************************************************************************************************************
What is Spring MVC?
• Framework for building web applications in Java
• Based on Model-View-Controller design pattern
• Leverages features of the Core Spring Framework (IoC, DI)
Spring MVC Benefits
• The Spring way of building web app UIs in Java
• Leverage a set of reusable UI components
• Help manage application state for web requests
• Process form data: validation, conversion etc
• Flexible configuration for the view layer
Components of a Spring MVC Application
• A set of web pages to layout UI components
• A collection of Spring beans (controllers, services, etc…)
• Spring configuration (XML, Annotations or Java)
Web Browser --> Front Controller --(Model)--> Controller --(Model)--> View Template --> Web Browser
Front Controller:
• Front controller known as DispatcherServlet.
• Part of the Spring Framework.
• Already developed by Spring Dev Team.
Controller:
• Code created by developer
• Contains your business logic
• Handle the request
• Store/retrieve data (db, web service…)
• Place data in model
• Send to appropriate view template
Model:
• Contains your data
• Store/retrieve data via backend systems
• database, web service, etc…
• Use a Spring bean if you like
• Place your data in the model
• Data can be any Java object/collection
View Template:
• Spring MVC is flexible
• Supports many view templates
• Most common is JSP + JSTL
• Developer creates a page
• Displays data
------------------------------------------------------------------------------------------------------------
|Spring MVC Configuration Process - Part 1 |
------------------------------------------------------------------------------------------------------------
| Add configurations to file: WEB-INF/web.xml |
| STEP 1: CONFIGURE SPRING DISPATCHER SERVLET |
| <web-app> |
| <servlet> |
| <servlet-name>dispatcher</servlet-name> |
| <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> |
| <init-param> |
| <param-name>contextConfigLocation</param-name> |
| <param-value>/WEB-INF/spring-mvc-demo-servlet.xml</param-value> |
| </init-param> |
| <load-on-startup>1</load-on-startup> |
| </servlet> |
| </web-app> |
| |
| STEP 2: SET UP URL MAPPINGS TO SPRING MVC DISPATCHER SERVLET |
| <web-app> |
| <servlet> |
| <servlet-name>dispatcher</servlet-name> |
| <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> |
| ... |
| </servlet> |
| <servlet-mapping> |
| <servlet-name>dispatcher</servlet-name> |
| <url-pattern>/</url-pattern> |
| </servlet-mapping> |
| </web-app> |
------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------
|Spring MVC Configuration Process - Part 2 |
------------------------------------------------------------------------------------------------------------
| Add configurations to file: WEB-INF/spring-mvc-demo-servlet.xml |
| STEP 3: ADD SUPPORT FOR SPRING COMPONENT SCANNING |
| <beans> |
| <!-- Step 3: Add support for component scanning --> |
| <context:component-scan base-package="com.luv2code.springdemo" /> |
| </beans> |
| |
| STEP 4: ADD SUPPORT FOR CONVERSION, FORMATTING AND VALIDATION |
| <beans> |
| <!-- Step 3: Add support for component scanning --> |
| <context:component-scan base-package="com.luv2code.springdemo" /> |
| <!-- Step 4: Add support for conversion, formatting and validation support --> |
| <mvc:annotation-driven/> |
| </beans> |
| |
| STEP 5: CONFIGURE SPRING MVC VIEW RESOLVER |
| <beans> |
| <!-- Step 3: Add support for component scanning --> |
| <context:component-scan base-package="com.luv2code.springdemo" /> |
| <!-- Step 4: Add support for conversion, formatting and validation support --> |
| <mvc:annotation-driven/> |
| <!-- Step 5: Define Spring MVC view resolver --> |
| <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> |
| <property name="prefix" value="/WEB-INF/view/" /> |
| <property name="suffix" value=".jsp" /> |
| </bean> |
| </beans> |
------------------------------------------------------------------------------------------------------------
Development Process - Spring MVC
1. Create Controller class
@Controller
public class HomeController {
}
2. Define Controller method
@Controller
public class HomeController {
public String showMyPage() {
…
}
}
3. Add Request Mapping to Controller method
@Controller
public class HomeController {
@RequestMapping("/")
public String showMyPage() {
…
}
}
4. Return View Name
@Controller
public class HomeController {
@RequestMapping("/")
public String showMyPage() {
return "main-menu";
}
}
5. Develop View Page - File: /WEB-INF/view/main-menu.jsp
<html>
<body>
<h2>Spring MVC Demo - Home Page</h2>
</body>
</html>
QUESTION: How do I use CSS, JavaScript and Images in a Spring MVC Web App?
ANSWER:
Here are the steps on how to access static resources in a Spring MVC.
For example, you can use this to access images, css, JavaScript files etc.
Any static resource is processed as a URL Mapping in Spring MVC. You can
configure references to static resources in the spring-mvc-demo-servlet.xml.
In my example, I'm going to have the following directory structure:
I chose to put everything in the "resources" directory. But you can use any
name for "resources", such as "assets", "foobar" etc. Also, you can give any
name that you want for the subdirectories under "resources".
---
Step 1: Add the following entry to your Spring MVC configuration file: spring-mvc-demo-servlet.xml
You can place this entry anywhere in your Spring MVC config file.
<mvc:resources mapping="/resources/**" location="/resources/"></mvc:resources>
"resources" folder is placed inside "WebContent" folder.
Step 2: Now in your view pages, you can access the static files using this syntax:
<img src="${pageContext.request.contextPath}/resources/images/spring-logo.png">
You need to use the JSP expression ${pageContext.request.contextPath} to access
the correct root directory for your web application.
Apply the same technique for reading CSS and JavaScript. In case of doubt refer forked gists on GitHub.
Spring MVC Form Tags
• Spring MVC Form Tags are the building block for a web page
• Form Tags are configurable and reusable for a web page
• Form tags will generate HTML for you
• form:form - main form container
• form:input - text field
• form:textarea - multi-line text field
• form:checkbox - check box
• form:radiobutton - radio buttons
• form:select - drop down list
• more …
Data Binding
• Spring MVC Form Tags can make use of data binding
• Automatically setting / retrieving data from a Java object / bean
How To Reference Spring MVC Form Tags
• Specify the Spring namespace at beginning of JSP file
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
Showing Form - In your Spring Controller
• Before you show the form, you must add a model attribute
• This is a bean that will hold form data for the data binding
Development Process - Spring MVC "form" Tag (Project 5 - Part 3 - Version 1)
1. Create Student class
2. Create Student controller class
3. Create HTML form
4. Create form processing code
5. Create confirmation page
****************************************************************************************************************************************************************************************************************************************************
Java’s Standard Bean Validation API (Reference: http://www.beanvalidation.org)
• Java has a standard Bean Validation API
• Defines a metadata model and API for entity validation
• Not tied to either the web tier or the persistence tier
• Available for server-side apps and also client-side JavaFX/Swing apps
Spring and Validation
• Spring version 4 and higher supports Bean Validation API
• Preferred method for validation when building Spring apps
• Simply add Validation JARs to our project
Bean Validation Features
• required
• validate length
• validate numbers
• validate with regular expressions
• custom validation
Validation Annotations
• @NotNull : Checks that the annotated value is not null
• @Min : Must be a number >= value
• @Max : Must be a number <= value
• @Size : Size must match the given size
• @Pattern : Must match a regular expression pattern
• @Future / @Past : Date must be in future or past of given date
• others …
We use Hibernate Validator as it is fully compliant with "Java’s Standard Bean Validation API": http://www.hibernate.org/validator
@InitBinder
• @InitBinder annotation works as a pre-processor
• It will pre-process each web request to our controller
• Method annotated with @InitBinder is executed
• We will use this to trim Strings - remove leading and trailing white space
• If String only has white spaces … trim it to null - validation problem resolution
****************************************************************************************************************************************************************************************************************************************************
What is Hibernate?
• A framework for persisting / saving Java objects in a database
Benefits of Hibernate
• Hibernate handles all of the low-level SQL
• Minimizes the amount of JDBC code you have to develop
• Hibernate provides the Object-to-Relational Mapping (ORM)
Hibernate Dev Process - To Do List
1. Add Hibernate Configuration file
2. Annotate Java Class
3. Develop Java Code to perform database operations
Entity Class: Java class that is mapped to a database table.
QUESTION: (During development)
Why we are using JPA Annotation instead of Hibernate?
For example, why we are not using this org.hibernate.annotations.Entity?
ANSWER:
JPA is a standard specification. Hibernate is an implementation of the JPA specification. Hibernate implements
all of the JPA annotations. The Hibernate team recommends the use of JPA annotations as a best practice.
Two Key Players:
• SessionFactory:
• Reads the hibernate config file
• Creates Session objects
• Heavy-weight object
• Only create once in your app
• Session
• Wraps a JDBC connection
• Main object used to save/retrieve objects
• Short-lived object
• Retrieved from SessionFactory
ID Generation Strategies - Primary Key Generation Strategies - [ @GeneratedValue(strategy=GenerationType.IDENTITY) ]
• GenerationType.AUTO : Pick an appropriate strategy for the particular database
• GenerationType.IDENTITY : Assign primary keys using database identity column
• GenerationType.SEQUENCE : Assign primary keys using a database sequence
• GenerationType.TABLE : Assign primary keys using an underlying database table to ensure uniqueness
• You can define your own CUSTOM generation strategy
• Create implementation of: org.hibernate.id.IdentifierGenerator
• Override the method: public Serializable generate(…)
Hibernate Query Language (HQL)
• Query language for retrieving objects
• Similar in nature to SQL: where, like, order by, join, in, etc…
• Examples:
• Retrieving all Students
List<Student> theStudents = session.createQuery("from Student").getResultList();
• Retrieving Students where lastName = ‘Doe’
List<Student> theStudents = session.createQuery("from Student s where s.lastName='Doe'").getResultList();
• Retrieving Students using OR predicate
List<Student> theStudents = session.createQuery("from Student s where s.lastName='Doe' OR s.firstName='Daffy'").getResultList();
• Retrieving Students using LIKE predicate
List<Student> theStudents = session.createQuery("from Student s where s.email LIKE '%luv2code.com'").getResultList();
• Update a Student
int studentId = 1;
Student myStudent = session.get(Student.class, studentId);
// update first name to "Scooby"
myStudent.setFirstName("Scooby");
// commit the transaction
session.getTransaction().commit();
• Update email for all students
session.createQuery("update Student set email='[email protected]'").executeUpdate();
• Delete a Student
int studentId = 1;
Student myStudent = session.get(Student.class, studentId);
// delete the student
session.delete(myStudent);
// commit the transaction
session.getTransaction().commit();
• Another way of deleting
session.createQuery("delete from Student where id=2").executeUpdate();
Advanced Mappings
• In the database, you most likely will have
• Multiple Tables
• Relationships between Tables
• Need to model this with Hibernate
Advanced Mappings - Types
• One-to-One
• One-to-Many, Many-to-One
• Many-to-Many
Fetch Types: Eager vs Lazy Loading
• When we fetch / retrieve data, should we retrieve EVERYTHING?
• Eager will retrieve everything
• Lazy will retrieve on request
Read the Hibernate PDFs from number 18 to 27 for deatils about entity lifecycle and advanced mappings.
****************************************************************************************************************************************************************************************************************************************************
IMPORTANT: Read the PDFs in "PDFs part 4 - Spring MVC CRUD App" folder for understanding the CRUD app.
Spring @Transactional:
• Spring provides an @Transactional annotation
• Automatically begins and ends a transaction for your Hibernate code
• No need for you to explicitly do the following in your code
// start a transaction
session.beginTransaction();
// DO YOUR HIBERNATE STUFF HERE
// ...
// commit transaction
session.getTransaction().commit();
• This Spring magic happens behind the scenes
IMPORTANT: @GetMapping and @PostMapping.
****************************************************************************************************************************************************************************************************************************************************
IMPORTANT: Read the PDFs in "PDFs part 5 - Spring AOP" folder.
IMPORTANT: Download AspectJ jars from this link - https://mvnrepository.com/artifact/org.aspectj/aspectjweaver
ACCESS THE RETURN VALUE:
@AfterReturning(pointcut="execution(* com.luv2code.aopdemo.dao.AccountDAO.findAccounts(..))", returning="result")
public void afterReturningFindAccountsAdvice(JoinPoint theJoinPoint, List<Account> result) {
// print out the results of the method call
// NOTE: {returning="result"} and {List<Account> result} have the same name "result". It's a must to have the same name.
System.out.println("\n=====>>> result is: " + result);
}
LOGGING / PRINTING TO THE SAME STREAM:
package com.luv2code.aopdemo;
import java.util.logging.Logger;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.luv2code.aopdemo.service.TrafficFortuneService;
public class AroundWithLoggerDemoApp {
private static Logger myLogger = Logger.getLogger(getClass().getName());
public static void main(String[] args) {
// read spring config java class
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DemoConfig.class);
// get the bean from spring container
TrafficFortuneService theFortuneService = context.getBean("trafficFortuneService", TrafficFortuneService.class);
/*
* IMPORTANT:
*
* We use "myLogger.info()" instead of "System.out.println()".
*
*/
myLogger.info("\nMain Program: AroundDemoApp");
myLogger.info("Calling getFortune");
String data = theFortuneService.getFortune();
myLogger.info("\nMy fortune is: " + data);
myLogger.info("Finished");
// close the context
context.close();
}
}
****************************************************************************************************************************************************************************************************************************************************
MAVEN
------
IMPORTANT: Read pom.xml for "mycoolapp" and "mycoolwebapp" projects.
IMPORTANT: Read the PDFs.
****************************************************************************************************************************************************************************************************************************************************
SPRING SECURITY
---------------
IMPORTANT: Read the PDFs while reading the source code of the spring security projects.
MISSING TOPICS:
1) Manual session & cookie management and access. (For "REMEMBER ME" feature.)
2) Manual database configuration. (To make use of user defined tables which have names other than the Spring Security default names.)
****************************************************************************************************************************************************************************************************************************************************
SPRING REST
-----------
IMPORTANT: @ExceptionHandler vs @ControllerAdvice
****************************************************************************************************************************************************************************************************************************************************
SPRING BOOT
-----------
IMPORTANT: Spring Boot Starter details :- https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-starter
IMPORTANT: Read PDFs thoroughly. Certain parts have been skipped.
VERY IMPORTANT: Spring Data JPA.
VERY IMPORTANT: Read the screenshots in "14-spring-boot-projects\8-spring-boot-demo-app-thymeleafdemo\Readme - IMPORTANT - Spring Data JPA Query Methods".
****************************************************************************************************************************************************************************************************************************************************