Skip to content

Instantly share code, notes, and snippets.

@SafNaaz
Last active Jul 15, 2020
Embed
What would you like to do?
Spring
All about Hibernate
-framework for persisting java objects to DB
- handles all low level SQL code
- minimizes amount of JDBC code
- provides ORM (Object to Relational Mapping)
ORM
- developer defines mapping between java class and database table using xml or java
saving objects
- create objects
- session.save() - session object is provided by hibernate framework , will return id as well(primary key)
- sessioin.get(classname, id) - gives back the data from db
all the students
- create query = session.createQuery("from Student")
list = query.list()
---------------------------------------------------------
Hibernate and JDBC??
Hibernate uses JDBC for all db communication
- another layer of extraction on top of jdbc
-----------------------------------------------
environmental setup
- Java IDE
- DB server
- Hibernate jar files and JDBC driver
- first make db ready
- then eclipse
- new project
- add hibernate files - lib->required copy,
- add mysql jdbc driver - mysql java connector -> connector.jar
- add jar files to build path
------------------------------
test jdbc
- start mysql server from xampp or other
- just give url, and try to connect it with boilerplate code - new class
--------------------------------------
hibernate development process
- add hibernate config - tells how to connect to db (bulk is jdbc things) , sql dialect, log sql or not, session context=thread, pool size etc
- annotata java class - called Entity(@entity) class - java class with setters and getters with annotations specific to hibernate
- map class to table @table & map fields to columns (@column) , @id for primary key
// if same name for field and db - no need of annotaition - still preferred
use imports from java persistence api JPA
//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.
- develop java code to perform db operations
create factory using hibernate config xml(name not mandatory) and entity files
create session suing factory
do operations with session
- begin transaction
- save/retrieve
-commit transaction etc
--------------------------------------------------
Key players
SessionFactory
- Reads hibernate config files
- Creates session objects
- Only created once in app - heavy weighted
Session
- wrapper around jdbc connection
- main object for save/retrieve objects
- short lived - use and throw
- retreived from sessionfactory
Spring - 5 is the main guy -
- reactive programming with webflux and all
java EE 7 is also similar
features-
light weight
seperation with ioc, and DI
application wide services with AOP
core-
creating beans and making it available
AOP-
application wide - logging, etc
using annotations and config files
Data Access Layer
JDBC
ORM
JMS
transactions
if springs integrated services 50 % code reduction
Web layer
home of web application
servlet
websocket
portlets
Test layer
unit
integration
mock
-------------------
other addons
spring security
batch
cloud
web services etc
---------------------------
env setup
1.tomcat 9 installed as a service - start and stop using monitor
2,eclipes EE edition - web support is there
3, add server in eclipse - point to tomcat path - will show server then
-----------------
www.spring.io - starter kit
--------------------
starter
- just create a java project
- download spring release dist.zip - contains all jar, core, aop etc
- extract it and add to project - lib directory
- add it to java build path - libraries - will show up in referenced libraries in eclipse
--------------------------------------
inversion of control
outsourcing the construction and mngnt of objects
traditionally - we have to do hard change. ioc helps to do with config files
one object factory will return the needed object - concept
-----------------------------------------------------
Spring container -
creates and manages object - ioc
inject object's dependencies - DI
configuring spring container
xml - legacy - add everything in xml
java annotations - add component scan alone in xml, rest annotations
java source code - no xml files at all., config also using java source code
-------------------------------------------
Development process
configuring spring beans
create spring container
retrieve beans from container
eg:
1. applicationContext.xml
bean id = className // used to retrieve a bean from a container
class= fullpath
spring container = application context
specific implemenations like classpathxmlappcontxt, annotationconfigappcontext etc
create the container using this context object and by passing xml to it
2. retreiving beans
use context.getbean(beanId in config file, classname)
// A "Spring Bean" is simply a Java object.
When Java objects are created by the Spring Container, then Spring refers to them as "Spring Beans".
//
3. call method on that bean object.
- now app is configurable - just change the className in context.xml - app will behave differently
//
reason for giving interface name in getBeans param :
Behaves the same as getBean(String), but provides a measure of type safety by throwing a BeanNotOfRequiredTypeException if the bean is not of the required type. This means that ClassCastException can't be thrown on casting the result correctly, as can happen with getBean(String).
-----------------------------------------
Dependency injection
delegates the construction of object to another
- many types
common
- constructor injection
- setter injection
- also autowiring is there
------------------------------
constructor injection
Development process:
1,define dependency interface and class - new interface and implementation class
2, create constructor in your class for injection - add that attribute and create a constructor where we want to implement it
3, config in config file - define both above in config file
---------------
setter injection
Development process:
1, configure setter method in class for injections - no arg constructor & setter method
2, config in config file
injecting literal values ( email address etc)
1, add property and setters
2, add in config - hardcode value
getting values from property file - avoid hardcoding
- create ppty file
- load in config file
- reference value from ppty file
-------------------------------------------------------------------------------------
------------------------------------------------------------------
bean scopes
lifecycle
default singleton
- only one instance is created, cached and reference is shared
- stateless bean
other scopes -
prototype = new instance of each container request - stateful data
request
session
global-session -all 3 web
----------------------------------------
prototype
just add scope = prototype in config - will point to different memory location - indicates different objects are created like the new keyword
---------------------------------------------------------------------
bean lifecycle
init, destroy can be called- add in config file
// For "prototype" scoped beans, Spring does not call the destroy method. Gasp!
-----------------------------------------------------------
configuration using annotations - ioc
special labels or markers added to java class
provide meta-data about class - infos
processed at compile or run time
"xml config can be verbose and difficult to maintain - so annotations"
steps:
enable annotation in config - add entry with package
add @component in class
retrieve bean from container
------------------------------------------------------------------
default bean id - instead of we giving , spring will generate auto
- just remove explicit bean id - spring generates classname based bean with first letter small
no explicit name given, automatically does eg: Home = home
special case of when BOTH the first and second characters of the class name are upper case, then the name is NOT converted. eg: REST = REST
-------------------------------------------------------------
DI using annotations
- uses 'autowiring'
looks for matching class or interface and automatically injects
types
- constructor injection
- setter injection
- field injection
steps
- define dependency interface and class
- create constructore in class for injections
- configure with @Autowired annotation
@Qualifier annotation - if there are multiple implemenations
-----------------------------------------------
constructor based autowiring
- create interface and impl
- create method in class's interface
- create local variable and constructor in impl and autowire
- use it as usual
//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.
-----------------------------------------------------------------------------------
setter based autowiring
-- create setter method & no arg constructor in class
-- use @
can be used with any method name
-----------------------------------------
field injection using @autowired
- even on private field
-------------------------------------
// use any of the above and stick to it
---------------------------------------
Qualifier
- give bean name - default is fine
// in constructer based - @Autowired
public TennisCoach(@Qualifier("randomFortuneService") FortuneService theFortuneService) {
// inside
-------------------------------------
values from ppty file
- similar
- add in config
then inject
eg: @Value("${foo.email}")
private String email;
--------------------------------------------------
bean scopes with annotation
add @scope(scopename)
----------------------------------------
bean lifecycle/ hooks
@postConstruct and @preDestroy
-------------------------------------------------------------------------------------------------------
Spring cofiguration using java source code
steps
java class for config and annotate as @configuration
add component scan support using @componentscan (optional)
read java config file - no quotations - use annotationconfigappcontext
retrieve bean
-------------------------------------------------------------------
Define spring bean with java code
- define mehtod to expose bean
-inject bean dependencies
- read spring java config class
- retreive bean
-----------------------------------
injecting value from ppty file using java
- create , load and reference
@propertySource(filename)
All about Spring MVC
- framwork for building web apps
- based on MVC
- Leverages core spring things - ioc, DI
web browser - front controller (creates model) - controller (model) - View template - browser
-------------------------------
components of spring MVC
- set of web pages
- collection of spring beans (controllers, services)
-Spring config (xml, annotations, java)
working
front controller (dispatcherServlet) already present
we will create model, the view pages and controller (business logic)
---------------------------------------
Controller
- handle request
- Store/retrieve data (db, web service etc)
- place data in model
- send to appropriate view
-----------------------------------------
Model
- contains data ( any type)
- controllers places data here ( like a suitcase)
-----------------------------------------------
View
- supports many,flexible
common - JSP + JSTL
also thymeleaf, groovy etc
displays data from model to users
-----------------------------------------------
environmental setup
- eclipse (JEE perspective)
- tomcat
- connect it
- add configs to WEB-INF/web.xml
1, spring mvc dispatcherServlet
2, setup URL mappings to spring mvc dispatcherServlet
- add configs to WEB-INF/spring-mvc-demo-servlet.xml
1, add support to spring componet scanning
2,add support to conversion, formatiing and validation
3, configure spring mvc view resolver
-------------------
new - dynamic web project
- copy all spring jars to web content- web inf - lib
- copy jstl support jar files as well
- copy web.xml (with web app tag) - contains dispatcherServlet setup and path to it
and application context xml (with bean tag) - contains component scan, validators support , view location and url prefix/suffix to it
- create a view folder in web.inf
// setup can also done wihtout xml - later
-----------------------------------------
a flow
steps
controller class - > -- use @controller - it extends @component - so scanning will pickup
controller method - > -- add a method - any name is fine ( can accept many params like reqparam etc) & also can return many combos - later
request mapping -- add @requestMapping annotation with url
return view name -- return from method , name - springconfig will append pre and suffix and page is found
develop view page -- normal jsp page with markups
create a package inside java resources - src & create controller there
and view file in view folder
then run on server - (change hyphen in tomcat console if port error, also change the default browser)
///tomcat auto reloads
--------------------------------------------------------------
form - add 2 request mappings - one for showing form and getting input from form
- usual way, get it and show it from param
---------------------------------------
adding data to spring model
- value from can be accessed using httpservletrequest.getParameter - which is available in controller
- then add model also in parameter
- model.addAttribute will put in model, with a name
-----------------------------------------------------------------
accessing static resources
- place in webcontent -> resources folder (any name, and segregate to corresponding folder if needed)
-then add below lines in app context.xml
<mvc:resources mapping="/resources/**" location="/resources/"></mvc:resources>
-then access as below
<link rel="stylesheet" type="text/css"
href="${pageContext.request.contextPath}/resources/css/my-test.css">
<script src="${pageContext.request.contextPath}/resources/js/simple-test.js"></script>
<img src="${pageContext.request.contextPath}/resources/images/spring-logo.png" />
----------------------------------------------------------------------------------------------------------------------
Deploying your App to Tomcat as a Web Application Archive (WAR) file
The Web Application Archive (WAR) file is a compressed version of your web application. It uses the zip file format but the file has the .war extension.
1. In Eclipse, stop Tomcat
2. Right-click your project and select Export > WAR File
3. In the Destination field, enter: <any-directory>/mycoolapp.war
4. Outside of Eclipse, start Tomcat
- If you are using MS Windows, then you should find it on the Start menu
5. Make sure Tomcat is up and running by visiting: http://localhost:8080
6. Deploy your new WAR file by copying it to <tomcat-install-directory>\webapps
Give it about 10-15 seconds to make the deployment. You'll know the deployment is over because you'll see a new folder created in webapps ... with your WAR file name.
7. Visit your new app. If your war file was: mycoolapp.war then you can access it with: http://localhost:8080/mycoolapp/
-----------------------------------------------------------------------------------
Request Param & Request mapping
- instead of getting from servlet- add annotation @requestparam
---------------------------------------------------------------
controller request mapping (/foo) - all other controllers underneath are relative then (/foo/bar)
- can be used to resolve issues, when 2 same mappings are there in different controllers
----------------------------------------
FORM tags eg: <form:form>
- lot of form related tags are there, which will auto binds data to model ( add spring taglib library for form in jsp page)
- model has to be injected
- in controller, add form object as model attribute
- add same name as model attribute in <form:form> as well
after submitting
- in controller add a new mapping where modelattribte is taken as param
- then in return jsp, model is available, fetch from it show to user
tags: examples
form:Select
----------------------------------------
How to use properties file to load country options
Answer:
This solution will show you how to place the country options in a properties file. The values will no longer be hard coded in the Java code.
1. Create a properties file to hold the countries. It will be a name value pair. Country code is name. Country name is the value.
New text file: WEB-INF/countries.properties
BR=Brazil
FR=France
CO=Colombia
IN=India
Note the location of the properties file is very important. It must be stored in WEB-INF/countries.properties
2. Update header section for Spring config file
We are going to use a new set of Spring tags for <util>. As a result, you need to update the header information in the Spring config file.
File: spring-mvc-dmo-servlet.xml
Remove the previous header and add this.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
3. Load the country options properties file in the Spring config file. Bean id: countryOptions
File: spring-mvc-dmo-servlet.xml
Add the following lines:
<util:properties id="countryOptions" location="classpath:../countries.properties" />
4.1 In StudentController.java, add the following import statement:
import java.util.Map;
4.2 Inject the properties values into your Spring Controller: StudentController.java
@Value("#{countryOptions}")
private Map<String, String> countryOptions;
5. Add the country options to the Spring MVC model. Attribute name: theCountryOptions
@RequestMapping("/showForm")
public String showForm(Model theModel) {
// create a student object Student
Student theStudent = new Student();
// add student object to the model
theModel.addAttribute("student", theStudent);
// add the country options to the model
theModel.addAttribute("theCountryOptions", countryOptions);
return "student-form";
}
6. Update the JSP page, student-form.jsp, to use the new model attribute for the drop-down list: theCountryOptions
<form:select path="country">
<form:options items="${theCountryOptions}" />
</form:select>
7. Remove all references to country option from your Student.java.
----------------------------------------------------------------------------
radio buttons
- form:radio
from list in java class
<form:radiobuttons path="favoriteLanguage" items="${student.favoriteLanguageOptions}" />
checkbox
- form checkbox - more than one option
- get in a array and display using c tag from jstl
-------------------------------------------------------------------------
FORM Validations
- java has standard bean validation api
- not tied to web or persistence layer
@NotNull, @Min, @Size, @pattern etc
- Hibernate validator is used - download the zip
- in dist, copy main 3 jars and jars in required folder to lib
- steps
- when validation fails, request is redirected back
1, add validation annotations to field, with messages
2, add form:error in form , add css class as well
3, check form errors in controller in bindingResult, ( add @valid to customer attribute & add to bindingResult)
//the BindingResult parameter must appear immediately after the model attribute.
redirect back to form or redirect to success page based on result
// whitespace should be trimmed
@initbinder preprocessor is used
--------------
@min & @max
add min/max value and messages
------------------------
regex
@pattern (regex and message)
------------------------
@required for int
wont work - make it to primitive
------------------------
handling string input for integer field
custom errors
- add property file under src/resources - and check errrorcode and bypass it with from ppty value (debug and see)
- add entry in appcontext to read the ppty file
--------------------------------------------------------------------------------------------
CUSTOM business validation
- create custom annotation
steps
- new package
- new annotation class
- add @constraint - clas which validates, @Target - field/method, @retention - runtime etc
- default value and error - and some default things
in extened constrainValidator - initialize the value, compare with present and return result, as an example
- also can be validated against array of strings
---------------------------------------------------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment