Springboot Interview Questions
Springboot Interview Questions
4. Why is it “opinionated”?
- It follows “Opinionated Defaults Configuration”
Approach to reduce Developer effort. Due to
opinionated view of spring boot, what is
required to get started but also we can get out
if not suitable for application.
• Spring Boot uses sensible defaults,
“opinions”, mostly based on the
classpath contents.
• For example
– Sets up a JPA Entity Manager
Factory if a JPA implementation
is on the classpath.
– Creates a default Spring MVC
setup, if Spring MVC is on the
classpath.
• Everything can be overridden easily
– But most of the time not
needed
5. How does it work? How does it know what to
configure?
• Auto-configuration works by analyzing
the classpath
– If you forget a dependency,
Spring Boot can’t configure it
– A dependency management
tool is recommended
– Spring Boot parent and starters
make it much easier
• Spring Boot works with Maven, Gradle,
Ant/Ivy
– Our content here will show
Maven
@Configuration
@EnableAutoConfiguration
public class MyAppConfig {
public static void main(String[] args) {
SpringApplication.run(MyAppConfig.class, args);
}
}
@SpringBootApplication was available from Spring Boot
1.2
It is very common to use @EnableAutoConfiguration,
@Configuration, and @ComponentScan together.
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class MyAppConfig {
...
}
With @SpringBootApplication annotation
@SpringBootApplication
public class MyAppConfig {
...
}
10. What is a Spring Boot starter POM? Why is it
useful?
Starters are a set of convenient dependency descriptors
that you can include in your application. The starters
contain a lot of the dependencies that you need to get a
project up and running quickly and with a consistent,
supported set of managed transitive dependencies.
The starter POMs are convenient dependency
descriptors that can be added to your application’s
Maven. In simple words, if you are developing a project
that uses Spring Batch for batch processing, you just
have to include spring-boot-starter-batch that will
import all the required dependencies for the Spring
Batch application. This reduces the burden of searching
and configuring all the dependencies required for a
framework.
logging.level.org.springframework=DEBUG
logging.level.com.acme.your.code=INFO
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
<version>1.2.6.RELEASE</version>
</dependency>
Automatic restart
Applications that use spring-boot-devtools will
automatically restart whenever files on the classpath
change. This can be a useful feature when working in an
IDE as it gives a very fast feedback loop for code
changes. By default, any entry on the classpath that
points to a folder will be monitored for changes.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
This can be achieved using DEV Tools. With this
dependency any changes you save, the embedded
tomcat will restart. Spring Boot has a Developer tools
(DevTools) module which helps to improve the
productivity of developers. One of the key challenge for
the Java developers is to auto deploy the file changes to
server and auto restart the server. Developers can
reload changes on Spring Boot without having to restart
my server. This will eliminates the need for manually
deploying the changes every time. Spring Boot doesn’t
have this feature when it has released it’s first version.
This was a most requested features for the developers.
The module DevTools does exactly what is needed for
the developers. This module will be disabled in the
production environment.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-
name=com.mysql.jdbc.Driver
– Spring Boot will create a DataSource with properties
set
– Will even use a connection pool if the library is found
on the classpath!
database.host = localhost
database.user = admin
application.yml
database:
host: localhost
user: admin
• YAML is convenient for hierarchical configuration data
– Spring Boot properties are organized in groups
– Examples: server, database, etc
Microservices Architecture
Spring enables separation-of-concerns
Loose Coupling– Effect of changes isolated
Tight Cohesion– Code perform a single well defined task
Microservices provide the same strength as Spring
provide
Loose Coupling– Application build from collaboration
services or processes, so any process change without
effecting another processes.
Tight Cohesion-An individual service or process that
deals with a single view of data.
Microservices Benefits
Smaller code base is easy to maintain.
Easy to scale as individual component.
Technology diversity i.e. we can mix libraries,
databases, frameworks etc.
Fault isolation i.e. a process failure should not
bring whole system down.
Better support for smaller and parallel team.
Independent deployment
Deployment time reduce
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-
eureka-server</artifactId>
</dependency>
DiscoveryMicroserviceServerApplication.java
package com.doj.discovery;
import
org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringB
ootApplication;
import
org.springframework.cloud.netflix.eureka.serve
r.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class
DiscoveryMicroserviceServerApplication {
application.yml
eureka:
instance:
hostname: localhost
registerWithEureka: false
fetchRegistry: false
server:
port: 1111
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-
starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-
eureka</artifactId>
</dependency>
<dependency>
@Bean
@LoadBalanced
}
Core Spring annotations
1. @Required : This annotation is applied on bean
setter methods. Consider a scenario where you need to
enforce a required property. The @Required annotation
indicates that the affected bean must be populated at
configuration time with the required property.
Otherwise an exception of type
BeanInitializationException is thrown.
2. @Autowired
This annotation is applied on fields, setter methods,
and constructors. The @Autowired annotation injects
object dependency implicitly.
@Component
public class Customer {
private Person person;
@Autowired
public Customer (Person person) {
this.person=person;
}
}
@Component
public class Customer {
private Person person;
@Autowired
public Customer (Person person) {
this.person=person;
}
}
NOTE: As of Spring 4.3, @Autowired became optional
on classes with a single constructor. In the above
example, Spring would still inject an instance of the
Person class if you omitted the @Autowired
annotation.
@Qualifier
This annotation is used along with @Autowired
annotation. When you need more control of the
dependency injection process, @Qualifier can be used.
@Qualifier can be specified on individual constructor
arguments or method parameters. This annotation is
used to avoid confusion which occurs when you create
more than one bean of the same type and want to wire
only one of them with a property.
Consider an example where an interface BeanInterface
is implemented by two beans BeanB1 and BeanB2.
@Component
public class BeanB1 implements BeanInterface {
//
}
@Component
public class BeanB2 implements BeanInterface {
//
}
Now if BeanA autowires this interface, Spring will not
know which one of the two implementations to inject.
One solution to this problem is the use of the
@Qualifier annotation.
@Component
public class BeanA {
@Autowired
@Qualifier("beanB2")
private BeanInterface dependency;
...
}
With the @Qualifier annotation added, Spring will now
know which bean to autowire where beanB2 is the
name of BeanB2.
@Configuration
It is used on classes which define beans.
@Configuration is an analog for XML configuration file
– it is configuration using Java class. J
ava class annotated with @Configuration is a
configuration by itself and will have methods to
instantiate and configure the dependencies.
Here is an example:
@Configuration
public class DataConfig{
@Bean
public DataSource source(){
DataSource source = new OracleDataSource();
source.setURL();
source.setUser();
return source;
}
@Bean
public PlatformTransactionManager manager(){
PlatformTransactionManager manager = new
BasicDataSourceTransactionManager();
manager.setDataSource(source());
return manager;
}
}
@ComponentScan
This annotation is used with @Configuration annotation
to allow Spring to know the packages to scan for
annotated components.
It is also used to specify base packages using
basePackageClasses or basePackage attributes to scan.
If specific packages are not defined, scanning will occur
from the package of the class that declares this
annotation
@Bean
This annotation is used at the method level. @Bean
annotation works with @Configuration to create Spring
beans. As mentioned earlier, @Configuration will have
methods to instantiate and configure dependencies.
Such methods will be annotated with @Bean. The
method annotated with this annotation works as bean
ID and it creates and returns the actual bean.
@Lazy
This annotation is used on component classes.
By default all autowired dependencies are created and
configured at startup.
But if you want to initialize a bean lazily, you can use
@Lazy annotation over the class.
This means that the bean will be created and initialized
only when it is first requested for.
You can also use this annotation on @Configuration
classes.
This indicates that all @Bean methods within that
@Configuration should be lazily initialized.
@Value
This annotation is used at the field, constructor parameter,
and method parameter level. The @Valueannotation
indicates a default value expression for the field or
parameter to initialize the property with. As
the @Autowired annotation tells Spring to inject object into
another when it loads your application context, you can
also use @Value annotation to inject values from a
property file into a bean’s attribute. It supports
both #{...} and ${...} placeholders.
Spring Framework
Stereotype Annotations
@Component
This annotation is used on classes to indicate a Spring
component. The @Component annotation marks the Java
class as a bean or say component so that the component-
scanning mechanism of Spring can add into the application
context.
@Controller
The @Controller annotation is used to indicate the class is
a Spring controller. This annotation can be used to identify
controllers for Spring MVC or Spring WebFlux.
@Service
This annotation is used on a class. The @Service marks a
Java class that performs some service, such as execute
business logic, perform calculations and call external APIs.
This annotation is a specialized form of
the @Component annotation intended to be used in the
service layer.
@Repository
This annotation is used on Java classes which directly
access the database. The @Repository annotation works as
marker for any class that fulfills the role of repository or
Data Access Object.
This annotation has a automatic translation feature. For
example, when an exception occurs in
the@Repository there is a handler for that exception and
there is no need to add a try catch block.
Spring Boot
Annotations
@EnableAutoConfiguration
This annotation is usually placed on the main application
class. The @EnableAutoConfiguration annotation
implicitly defines a base “search package”. This annotation
tells Spring Boot to start adding beans based on classpath
settings, other beans, and various property settings.
@SpringBootApplication
This annotation is used on the application class while
setting up a Spring Boot project. The class that is annotated
with the @SpringBootApplication must be kept in the base
package. The one thing that
the@SpringBootApplication does is a component scan. But
it will scan only its sub-packages. As an example, if you
put the class annotated
with @SpringBootApplication in com.example then @Spri
ngBootApplication will scan all its sub-packages, such
as com.example.a, com.example.b, and com.example.a.x.
The @SpringBootApplication is a convenient annotation
that adds all the following:
@Configuration
@EnableAutoConfiguration
@ComponentScan
Spring MVC and REST
Annotations
@Controller
This annotation is used on Java classes that play the role of
controller in your application. The @Controllerannotation
allows autodetection of component classes in the classpath
and auto-registering bean definitions for them. To enable
autodetection of such annotated controllers, you can add
component scanning to your configuration. The Java class
annotated with @Controller is capable of handling multiple
request mappings.
This annotation can be used with Spring MVC and Spring
WebFlux.
@RequestMapping
This annotation is used both at class and method level.
The @RequestMapping annotation is used to map web
requests onto specific handler classes and handler methods.
When @RequestMapping is used on class level it creates a
base URI for which the controller will be used. When this
annotation is used on methods it will give you the URI on
which the handler methods will be executed. From this you
can infer that the class level request mapping will remain
the same whereas each handler method will have their own
request mapping.
Sometimes you may want to perform different operations
based on the HTTP method used, even though the request
URI may remain the same. In such situations, you can use
the method attribute of @RequestMappingwith an HTTP
method value to narrow down the HTTP methods in order
to invoke the methods of your class.
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping("/")
String get(){
//mapped to hostname:port/home/
return "Hello from get";
}
@RequestMapping("/index")
String index(){
//mapped to hostname:port/home/index/
return "Hello from index";
}
}
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = "/id")
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = "/name")
String getName(@RequestParam(value = "person",
required = false) String personName){
return "Required element of request param";
}
}
In this code snippet, as the required element is specified
as false, the getName() handler method will be called
for both of these URLs:
/home/name?person=xyz
/home/name
The default value of the @RequestParam is used to
provide a default value when the request param is not
provided or is empty
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = "/name")
String getName(@RequestParam(value = "person",
defaultValue = "John") String personName ){
return "Required element of request param";
}
}
In this code, if the person request param is empty in a
request, the getName() handler method will receive the
default value John as its parameter
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(method = RequestMethod.GET)
String get(){
return "Hello from get";
}
@RequestMapping(method = RequestMethod.DELETE)
String delete(){
return "Hello from delete";
}
@RequestMapping(method = RequestMethod.POST)
String post(){
return "Hello from post";
}
@RequestMapping(method = RequestMethod.PUT)
String put(){
return "Hello from put";
}
@RequestMapping(method = RequestMethod.PATCH)
String patch(){
return "Hello from patch";
}
}
You can also consume the object with the requested media
type using the consumes element of @RequestMapping in
combination with the @RequestBody annotation.
@RestController
@RequestMapping("/home")
@ResponseBody
String getProduces(){
return "Produces attribute";
String getConsumes(){
@RestController
@RequestMapping("/home")
String post(){
}
}
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = "/head", headers =
{"content-type=text/plain", "content-type=text/html"})
String post(){
return "Mapping applied along with headers";
}
}
Here it implies that both text/plain as well as text/html
are accepted by the post() handler method.
@RequestMapping with
Request Parameters
The params element of the @RequestMapping annotation
further helps to narrow down request mapping. Using
the params element, you can have multiple handler methods
handling requests to the same URL, but with different
parameters.
You can define params as myParams = myValue. You can
also use the negation operator to specify that a particular
parameter value is not supported in the request.
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = "/fetch", params =
{"personId=10"})
String getParams(@RequestParam("personId") String
id){
return "Fetched parameter using params attribute =
"+id;
}
@RequestMapping(value = "/fetch", params =
{"personId=20"})
String
getParamsDifferent(@RequestParam("personId") String
id){
return "Fetched parameter using params attribute =
"+id;
}
}
Using
@RequestMapping with
Dynamic URIs
The @RequestMapping annotation is used in combination
with the @PathVaraible annotation to handle dynamic
URIs. In this use case, the URI values can act as the
parameter of the handler methods in the controller. You can
also use regular expressions to only accept the dynamic
URI values that match the regular expression.
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = "/fetch/{id}", method =
RequestMethod.GET)
String getDynamicUriValue(@PathVariable String id){
System.out.println("ID is "+id);
return "Dynamic URI parameter fetched";
}
@RequestMapping(value = "/fetch/{id:[a-z]+}/{name}",
method = RequestMethod.GET)
String
getDynamicUriValueRegex(@PathVariable("name")
String name){
System.out.println("Name is "+name);
return "Dynamic URI parameter fetched using regex";
}
}
In this code, the method getDynamicUriValue() will
execute for a request to localhost:8080/home/fetch/10.
Also, the id parameter of the getDynamicUriValue()
handler method will be populated with the value 10
dynamically.
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping()
String default(){
@RequestMapping Shortcuts
Spring 4.3 introduced method-level variants, also known
as composed annotations of @RequestMapping. The
composed annotations better express the semantics of
the annotated methods. They act as wrapper to
@RequestMapping and have become the standard
ways of defining the endpoints.
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
The following code shows using the composed
annotations.
@RestController
@RequestMapping("/home")
public class IndexController {
@GetMapping("/person")
public @ResponseBody ResponseEntity<String>
getPerson() {
return new ResponseEntity<String>("Response from
GET", HttpStatus.OK);
}
@GetMapping("/person/{id}")
public @ResponseBody ResponseEntity<String>
getPersonById(@PathVariable String id){
return new ResponseEntity<String>("Response from
GET with id " +id,HttpStatus.OK);
}
@PostMapping("/person")
public @ResponseBody ResponseEntity<String>
postPerson() {
return new ResponseEntity<String>("Response from
POST method", HttpStatus.OK);
}
@PutMapping("/person")
public @ResponseBody ResponseEntity<String>
putPerson() {
return new ResponseEntity<String>("Response from
PUT method", HttpStatus.OK);
}
@DeleteMapping("/person")
public @ResponseBody ResponseEntity<String>
deletePerson() {
return new ResponseEntity<String>("Response from
DELETE method", HttpStatus.OK);
}
@PatchMapping("/person")
public @ResponseBody ResponseEntity<String>
patchPerson() {
return new ResponseEntity<String>("Response from
PATCH method", HttpStatus.OK);
}
}
@RequestMapping Conclusion
As you can see in this post, the @RequestMapping
annotation is very versatile. You can use this annotation
to configure Spring MVC to handle a variety of use
cases. It can be used to configure traditional web page
requests, and well as RESTFul web services in Spring
MVC.
protected Customer() {}
@Override
public String toString() {
return String.format(
"Customer[id=%d, firstName='%s',
lastName='%s']",
id, firstName, lastName);
}
}
application.properties
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/
db_example
spring.datasource.username=springuser
spring.datasource.password=ThePassword
@JsonIgnore
@ManyToOne
private Account account;
/user/Ranga/todos/1
/person/Ranga
XML
HTML
JSON
A resource will have state. The representation of a
resource should capture its current state.
200 - SUCESS
404 - RESOURCE NOT FOUND
400 - BAD REQUEST
201 - CREATED
401 - UNAUTHORIZED
415 - UNSUPPORTED TYPE -
Representation not supported for the
resource
500 - SERVER ERROR
SQL Database
Static Domain Model
Mostly CRUD
Mostly Simple Queries/Mappings
Bootstrapping with Spring Initializr
Creating a REST service with Spring Initializr
is a cake walk. We will use Spring Web MVC
as our web framework.
@Entity
@Id
@GeneratedValue
private Long id;
/src/main/resources/data.sql
values(10001,'Ranga', 'E1234567');
values(10002,'Ravi', 'A1234568');
When the application reloads you would see
following statements in the log indicating
that the sql files are picked up.
@Repository
Notes
JpaRepository
JpaRepository (Defined in Spring Data JPA)
is the JPA specific Repository interface.
extends
PagingAndSortingRepository<T, ID>,
QueryByExampleExecutor<T> {
JpaRepository extends
PagingAndSortingRepository which in turn
extends CrudRepository interface. So,
JpaRepository inherits all the methods from
the two interfaces shown below.
PagingAndSortingRepository
public abstract interface
PagingAndSortingRepository extends
CrudRepository {
CrudRepository
T findOne(ID primaryKey);
Iterable<T> findAll();
Long count();
}
Exposing Resources using
StudentResource
Lets start with setting up the
StudentResource class and then move into
creating methods to handle different kinds of
request methods to the Student Resouce.
@Autowired
private StudentRepository
studentRepository;
Notes
: Combination of
@RestController
@Controller and @ResponseBody.
Beans returned are converted to/from
JSON/XML.
@Autowired private StudentRepository
studentRepository : Autowire the
StudentRepository so that we can
retrieve and save data to database.
@GetMapping("/students")
return studentRepository.findAll();
Response
"id": 10001,
"name": "Ranga",
"passportNumber": "E1234567"
},
"id": 10002,
"name": "Ravi",
"passportNumber": "A1234568"
}
]
@GetMapping("/students/{id}")
Optional<Student> student =
studentRepository.findById(id);
if (!student.isPresent())
throw new
StudentNotFoundException("id-" + id);
return student.get();
}
Let’s execute another GET
request
URL -
http://localhost:8080/students/1000
2
Request Method - GET
Response
"id": 10002,
"name": "Ravi",
"passportNumber": "A1234568"
@DeleteMapping("/students/{id}")
public void deleteStudent(@PathVariable long
id) {
studentRepository.deleteById(id);
@PostMapping("/students")
public ResponseEntity<Object>
createStudent(@RequestBody Student student) {
Student savedStudent =
studentRepository.save(student);
URI location =
ServletUriComponentsBuilder.fromCurrentReques
t().path("/{id}")
.buildAndExpand(savedStudent.getId())
.toUri();
return
ResponseEntity.created(location).build();
Request
"name": "Tom",
"passportNumber": "Z1234567"
Response
@PutMapping("/students/{id}")
public ResponseEntity<Object>
updateStudent(@RequestBody Student student,
@PathVariable long id) {
Optional<Student> studentOptional =
studentRepository.findById(id);
if (!studentOptional.isPresent())
return
ResponseEntity.notFound().build();
student.setId(id);
studentRepository.save(student);
return
ResponseEntity.noContent().build();
Request
"name": "Tom",
"passportNumber": "Z1234567"
EXAMPLE
@GetMapping("/students")
public List<Student> retrieveAllStudents() {
return studentRepository.findAll();
}
@GetMapping("/students/{id}")
public Student retrieveStudent(@PathVariable
long id) {
Optional<Student> student =
studentRepository.findById(id);
if (!student.isPresent())
throw new
StudentNotFoundException("id-" + id);
return student.get();
}
@DeleteMapping("/students/{id}")
public void deleteStudent(@PathVariable long
id) {
studentRepository.deleteById(id);
}
@PostMapping("/students")
public ResponseEntity<Object>
createStudent(@RequestBody Student student) {
Student savedStudent =
studentRepository.save(student);
URI location =
ServletUriComponentsBuilder.fromCurrentRequest().pa
th("/{id}")
.buildAndExpand(savedStudent.getId()).toUri();
return
ResponseEntity.created(location).build();
@PutMapping("/students/{id}")
public ResponseEntity<Object>
updateStudent(@RequestBody Student student,
@PathVariable long id) {
Optional<Student> studentOptional =
studentRepository.findById(id);
if (!studentOptional.isPresent())
return
ResponseEntity.notFound().build();
student.setId(id);
studentRepository.save(student);
return
ResponseEntity.noContent().build();
}
}
spring-boot-starter-web-services -
SOAP Web Services
spring-boot-starter-web - Web &
RESTful applications
spring-boot-starter-test - Unit testing
and Integration Testing
spring-boot-starter-jdbc - Traditional
JDBC
spring-boot-starter-hateoas - Add
HATEOAS features to your services
spring-boot-starter-security -
Authentication and Authorization
using Spring Security
spring-boot-starter-data-jpa - Spring
Data JPA with Hibernate
spring-boot-starter-cache - Enabling
Spring Framework’s caching support
spring-boot-starter-data-rest - Expose
Simple REST Services using Spring
Data REST
spring-boot-starter-actuator - To use
advanced features like monitoring &
tracing to your application out of the
box
spring-boot-starter-undertow, spring-
boot-starter-jetty, spring-boot-starter-
tomcat - To pick your specific choice of
Embedded Servlet Container
spring-boot-starter-logging - For
Logging using logback
spring-boot-starter-log4j2 - Logging
using Log4j2
Pros:
" When long transactions are required due to user think-
time, it is the best practice to break the long transaction up
into two or more transactions. You can use detached
objects from the first transaction to carry data all the way up
to the presentation layer. These detached objects get
modified outside a transaction and later on re-attached to a
new transaction via another session.
Cons
" In general, working with detached objects is quite
cumbersome, and better to not clutter up the session with
them if possible. It is better to discard them and re-fetch
them on subsequent requests. This approach is not only
more portable but also more efficient because - the objects
hang around in Hibernate's cache anyway.
order collection :-
Order collection is sorting a collection by specifying the
order-by clause for sorting this collection when retrieval.
If your collection is very large, it will be more efficient way to
sort it .
org.springframework.orm.hibernate.HibernateTemplate is a
helper class which provides different methods for
querying/retrieving data from the database. It also converts
checked HibernateExceptions into unchecked
DataAccessExceptions.
Use update() if you are sure that the session does not
contain an already persistent instance with the same
identifier, and merge() if you want to merge your
modifications at any time without consideration of the state
of the session.
get():-
If you are not sure that the object exists, then use one of
the get() methods.
get() method will return null if the unique id is not found in
the database.
get() will hit the database immediately.
Hibernate simplifies:
Example :
<hibernate-mapping>
<class name=”com.test.User” table=”user”>
<property column=”USER_NAME” length=”255″
name=”userName” not-null=”true” type=”java.lang.String”/>
<property column=”USER_PASSWORD” length=”255″
name=”userPassword” not-null=”true”
type=”java.lang.String”/>
</class>
</hibernate-mapping>
SessionFactory sessionFactory =
configuration.buildSessionFactory();
34. What role does the Session interface play in
Hibernate?
POJO stands for plain old java objects. These are just basic
JavaBeans that have defined setter and getter methods for
all the properties that are there in that bean. Besides they
can also have some business logic related to that property.
Hibernate applications works efficiently with POJOs rather
then simple java classes.
► Improved performance
* Sophisticated caching
* Eager loading
► Improved maintainability
* A lot less code to write
► Improved portability
* ORM framework generates database-specific SQL for you
2. What is prototype?
jspinit(),_jspService(),jspdestroy()
public someClass{
public synchronised methodA(){
//write your code
}
}
13. Explain what is synchronization?
Struts:
1.Struts is only for web Applications.We can not develop
any
type of Java,J2EE applications by using Struts Framework.
2.We can not Integrate other Frameworks with Any other
Java
Oriented Frameworks.
Spring:
1.Spring is for developing any kind of Java,J2EE
applications.
2.It is Layered architecture.We can integrate any no of
Frameworks with Spring.
3.It has So many features like AOP,IOC.
Pass by value.
1. When passing primitives, it passes a copy of the
variable to the method. Any change made in the method
does
not reflect in the calling method.
2. When dealing with objects, a copy of their
reference/address is passed. Thus the change made to the
object is reflected in the calling method.
17. How will the struts know which action class to call
when you submit a form?
yes you can have and if you specify different url patter
like
*.do for one action servlet
*.abc for other action servlet
in your web.xml file