0% found this document useful (0 votes)
707 views27 pages

Spring Boot Annotations Overview

This document summarizes various Spring annotations used for different purposes like component scanning, autowiring dependencies, managing transactions, defining scopes, mapping URLs to controllers, binding request parameters to method arguments, and managing session attributes. It provides details on how to use annotations like @Component, @Service, @Repository, @Autowired, @Transactional, @Scope, @Controller, @RequestMapping, @PathVariable, @RequestParam, @ModelAttribute, and @SessionAttributes in Spring applications. It also explains how to configure component scanning and enable annotation-based configuration in Spring.

Uploaded by

mahesh gowtham
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
707 views27 pages

Spring Boot Annotations Overview

This document summarizes various Spring annotations used for different purposes like component scanning, autowiring dependencies, managing transactions, defining scopes, mapping URLs to controllers, binding request parameters to method arguments, and managing session attributes. It provides details on how to use annotations like @Component, @Service, @Repository, @Autowired, @Transactional, @Scope, @Controller, @RequestMapping, @PathVariable, @RequestParam, @ModelAttribute, and @SessionAttributes in Spring applications. It also explains how to configure component scanning and enable annotation-based configuration in Spring.

Uploaded by

mahesh gowtham
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
  • Spring Annotations
  • Spring MVC Annotations
  • Hibernate JPA Annotations
  • Spring Security Annotations
  • Hibernate Inheritance Mapping Annotations
  • RESTful Web Service JAX-RS Annotations
  • JAXB Annotations
  • Using JAX-RS Annotations with JAXB and JPA
  • Spring JUnit Annotations

Spring Annotations: Contents:

Annotation Package Detail/Import statement


@Service import [Link];
@Repository import [Link];
@Component import [Link];
@Autowired import [Link];
@Transactional import [Link];
@Scope import [Link];
Spring MVC Annotations
@Controller import [Link];
@RequestMapping import [Link];
@PathVariable import [Link];
@RequestParam import [Link];
@ModelAttribute import [Link];
@SessionAttributes import [Link];
Spring Security Annotations
@PreAuthorize import [Link];

For spring to process annotations, add the following lines in your [Link]
file.
<context:annotation-config />
<context:component-scan base-package="...specify your package
name..." />
Spring supports both Annotation based and XML based configurations. You can
even mix them together. Annotation injection is performed before XML
injection, thus the latter configuration will override the former for properties
wired through both approaches.

@Service

Annotate all your service classes with @Service. All your business logic should be in Service
classes.
@Service
public class CompanyServiceImpl implements CompanyService {
...
}

@Repository
Annotate all your DAO classes with @Repository. All your database access logic should be
in DAO classes.
@Repository
public class CompanyDAOImpl implements CompanyDAO {
...
}

@Component

Annotate your other components (for example REST resource classes) with @Component.
@Component
public class ContactResource {
...
}
@Component is a generic stereotype for any Spring-managed component. @Repository,
@Service, and @Controller are specializations of @Component for more specific use cases,
for example, in the persistence, service, and presentation layers, respectively.

@Autowired

Let Spring auto-wire other beans into your classes using @Autowired annotation.
@Service
public class CompanyServiceImpl implements CompanyService {

@Autowired
private CompanyDAO companyDAO;

...
}
Spring beans can be wired by name or by type.

 @Autowire by default is a type driven injection. @Qualifier spring


annotation can be used to further fine-tune autowiring.
 @Resource ([Link]) annotation can be used for
wiring by name.

Beans that are themselves defined as a collection or map type cannot be injected
through @Autowired, because type matching is not properly applicable to them.
Use @Resource for such beans, referring to the specific collection or map bean
by unique name.
@Transactional

Configure your transactions with @Transactional spring annotation.


@Service
public class CompanyServiceImpl implements CompanyService {

@Autowired
private CompanyDAO companyDAO;

@Transactional
public Company findByName(String name) {

Company company = [Link](name);


return company;
}
...
}

To activate processing of Spring's @Transactional annotation, use the


<tx:annotation-driven/> element in your spring's configuration file.

The default @Transactional settings are as follows:

 Propagation setting is PROPAGATION_REQUIRED.


 Isolation level is ISOLATION_DEFAULT.
 Transaction is read/write.
 Transaction timeout defaults to the default timeout of the underlying transaction
system, or to none if timeouts are not supported.
 Any RuntimeException triggers rollback, and any checked Exception does not.

These default settings can be changed using various properties of the @Transactional spring
annotation.

Specifying the @Transactional annotation on the bean class means that it applies
to all applicable business methods of the class. Specifying the annotation on a
method applies it to that method only. If the annotation is applied at both the
class and the method level, the method value overrides if the two disagree.

@Scope

As with Spring-managed components in general, the default and most common scope for
autodetected components is singleton. To change this default behavior, use @Scope spring
annotation.
@Component
@Scope("request")
public class ContactResource {
...
}
Similarly, you can annotate your component with @Scope("prototype") for beans with
prototype scopes.
Please note that the dependencies are resolved at instantiation time. For
prototype scope, it does NOT create a new instance at runtime more than once. It
is only during instantiation that each bean is injected with a separate instance of
prototype bean.

Spring MVC Annotations


@Controller

Annotate your controller classes with @Controller.


@Controller
public class CompanyController {
...
}

@RequestMapping

You use the @RequestMapping spring annotation to map URLs onto an entire class or a
particular handler method. Typically the class-level annotation maps a specific request path
(or path pattern) onto a form controller, with additional method-level annotations narrowing
the primary mapping.
@Controller
@RequestMapping("/company")
public class CompanyController {

@Autowired
private CompanyService companyService;
...
}

@PathVariable

You can use the @PathVariable spring annotation on a method argument to bind it to the
value of a URI template variable. In our example below, a request path of /company/techferry
will bind companyName variable with 'techferry' value.
@Controller
@RequestMapping("/company")
public class CompanyController {

@Autowired
private CompanyService companyService;

@RequestMapping("{companyName}")
public String getCompany(Map<String, Object> map,
@PathVariable String companyName) {
Company company = [Link](companyName);
[Link]("company", company);
return "company";
}
...
}

@RequestParam
You can bind request parameters to method variables using spring annotation
@RequestParam.
@Controller
@RequestMapping("/company")
public class CompanyController {

@Autowired
private CompanyService companyService;

@RequestMapping("/companyList")
public String listCompanies(Map<String, Object> map,
@RequestParam int pageNum) {
[Link]("pageNum", pageNum);
[Link]("companyList", [Link](pageNum));
return "companyList";
}
...
}
Similarly, you can use spring annotation @RequestHeader to bind request headers.

@ModelAttribute

An @ModelAttribute on a method argument indicates the argument should be retrieved from


the model. If not present in the model, the argument should be instantiated first and then
added to the model. Once present in the model, the argument's fields should be populated
from all request parameters that have matching names. This is known as data binding in
Spring MVC, a very useful mechanism that saves you from having to parse each form field
individually.
@Controller
@RequestMapping("/company")
public class CompanyController {

@Autowired
private CompanyService companyService;

@RequestMapping("/add")
public String saveNewCompany(@ModelAttribute Company company) {
[Link](company);
return "redirect:" + [Link]();
}
...
}

@SessionAttributes

@SessionAttributes spring annotation declares session attributes. This will typically list the
names of model attributes which should be transparently stored in the session, serving as
form-backing beans between subsequent requests.
@Controller
@RequestMapping("/company")
@SessionAttributes("company")
public class CompanyController {

@Autowired
private CompanyService companyService;
...
}
@SessionAttribute works as follows:

 @SessionAttribute is initialized when you put the corresponding attribute into model
(either explicitly or using @ModelAttribute-annotated method).
 @SessionAttribute is updated by the data from HTTP parameters when controller
method with the corresponding model attribute in its signature is invoked.
 @SessionAttributes are cleared when you call setComplete() on SessionStatus object
passed into controller method as an argument.

The following listing illustrate these concepts. It is also an example for pre-populating Model
objects.
@Controller
@RequestMapping("/owners/{ownerId}/pets/{petId}/edit")
@SessionAttributes("pet")
public class EditPetForm {

@ModelAttribute("types")

public Collection<PetType> populatePetTypes() {


return [Link]();
}

@RequestMapping(method = [Link])
public String processSubmit(@ModelAttribute("pet") Pet pet,
BindingResult result, SessionStatus status) {
new PetValidator().validate(pet, result);
if ([Link]()) {
return "petForm";
}else {
[Link](pet);
[Link]();
return "redirect:[Link]?ownerId="
+ [Link]().getId();
}
}
}

Spring Security Annotations


@PreAuthorize

Using Spring Security @PreAuthorize annotation, you can authorize or deny a functionality.
In our example below, only a user with Admin role has the access to delete a contact.
@Transactional
@PreAuthorize("hasRole('ROLE_ADMIN')")
public void removeContact(Integer id) {
[Link](id);
}

Hibernate JPA Annotations - Contents:


Annotation Package Detail/Import statement
@Entity import [Link];
@Table import [Link];
@Column import [Link];
@Id import [Link];
@GeneratedValue import [Link];
@Version import [Link];
@OrderBy import [Link];
@Transient import [Link];
@Lob import [Link];
Hibernate Association Mapping Annotations
@OneToOne import [Link];
@ManyToOne import [Link];
@OneToMany import [Link];
@ManyToMany import [Link];
@PrimaryKeyJoinColumn import [Link];
@JoinColumn import [Link];
@JoinTable import [Link];
@MapsId import [Link];
Hibernate Inheritance Mapping Annotations
@Inheritance import [Link];
@DiscriminatorColumn import [Link];
@DiscriminatorValue import [Link];

@Entity

Annotate all your entity beans with @Entity.

1@Entity
2public class Company implements Serializable {
3...
4}

@Table

Specify the database table this Entity maps to using the name attribute of @Table annotation.
In the example below, the data will be stored in 'company' table in the database.

1@Entity
2@Table(name = "company")
3public class Company implements Serializable {
...
4}
5

@Column

Specify the column mapping using @Column annotation.


1
@Entity
2@Table(name = "company")
3public class Company implements Serializable {
4
5 @Column(name = "name")
6 private String name;
7
8...
}
9

@Id

Annotate the id column using @Id.


1
@Entity
2 @Table(name = "company")
3 public class Company implements Serializable {
4
5 @Id
6 @Column(name = "id")
7 private int id;
8
...
9 }
10

@GeneratedValue

Let database generate (auto-increment) the id column.


1
2 @Entity
@Table(name = "company")
3 public class Company implements Serializable {
4
5 @Id
6 @Column(name = "id")
7 @GeneratedValue
private int id;
8
9 ...
10}
11

@Version
Control versioning or concurrency using @Version annotation.
1
@Entity
2 @Table(name = "company")
3 public class Company implements Serializable {
4
5 @Version
6 @Column(name = "version")
7 private Date version;
8
...
9 }
10

@OrderBy

Sort your data using @OrderBy annotation. In example below, it will sort all contacts in a
company by their firstname in ascending order.
1@OrderBy("firstName asc")
2private Set contacts;

@Transient

Annotate your transient properties with @Transient.

@Lob

Annotate large objects with @Lob.

Hibernate Association Mapping Annotations


Example App DB Schema
The database for this tutorial is designed to illustrate various association mapping concepts.
In RDBMS implementations, entities are joined using the following ways:

 Shared Primary Key


 Foreign Key
 Association Table

In our example app,

 Tables company and companyDetail have shared values for primary key. It is a one-
to-one assoication.
 Tables contact and contactDetail are linked through a foreign key. It is also a one to
one association.
 Tables contact and company are linked through a foriegn key in many-to-one
association with contact being the owner.
 Tables company and companyStatus are linked through a foreign key in many-to-one
association with company being the owner.

@OneToOne

 Use @PrimaryKeyJoinColumn for associated entities sharing the same


primary key.
 Use @JoinColumn & @OneToOne mappedBy attribute when foreign
key is held by one of the entities.
 Use @JoinTable and mappedBy entities linked through an association
table.
 Persist two entities with shared key using @MapsId
For entities Company and CompanyDetail sharing the same primary key, we can associate
them using @OneToOne and @PrimaryKeyJoinColumn as shown in the example below.

Notice that the id property of CompanyDetail is NOT annotated with @GeneratedValue. It


will be populated by id value of Company.
1
2
3 @Entity
@Table(name = "company")
4 public class Company implements Serializable {
5
6 @Id
7 @Column(name = "id")
8 @GeneratedValue
private int id;
9
10 @OneToOne(cascade = [Link])
11 @PrimaryKeyJoinColumn
12 private CompanyDetail companyDetail;
13
14 ...
15}
16
@Entity
17@Table(name = "companyDetail")
18public class CompanyDetail implements Serializable {
19
20 @Id
21 @Column(name = "id")
22 private int id;
23
...
24}
25
26
For entities Contact and ContactDetail linked through a foriegn key, we can use @OneToOne
and @JoinColumn annotations. In example below, the id genereated for Contact will be
mapped to 'contact_id' column of ContactDetail table. Please note the usage of @MapsId for
the same.
1 @Entity
@Table(name = "contactDetail")
2 public class ContactDetail implements Serializable {
3
4 @Id
5 @Column(name = "id")
6 @GeneratedValue
private int id;
7
8 @OneToOne
9 @MapsId
10 @JoinColumn(name = "contactId")
11 private Contact contact;
12
13 ...
}
14
15@Entity
16@Table(name = "contact")
17public class Contact implements Serializable {
18
@Id
19 @Column(name = "ID")
20 @GeneratedValue
21 private Integer id;
22
23 @OneToOne(mappedBy = "contact", cascade = [Link])
24 private ContactDetail contactDetail;
25 ....
26}
27
28
29
30
31
Also note that the relationship between Company and CompanyDetail is uni-directional. On
the other hand, the relationship between Contact and Contact Detail is bi-directional and that
can be achieved using 'mappedBy' attribute.

The rationale to have one relationship as uni-directional and other as bi-directional in this
tutorial is to illustrate both concepts and their usage. You can opt for uni-directional or bi-
directional relationships to suit your needs.

@ManyToOne

 Use @JoinColumn when foreign key is held by one of the entities.


 Use @JoinTable for entities linked through an association table.

The two examples below illustrate many-to-one relationships. Contact to Company and
Company to CompanyStatus. Many contacts can belong to a company. Similary many
companies can share the same status (Lead, Prospect, Customer) - there will be many
companies that are currently leads.
1 @Entity
2 @Table(name = "contact")
3 public class Contact implements Serializable {
4 @ManyToOne
5 @JoinColumn(name = "companyId")
6 private Company company;
7
8 ...
9
10 }
11
12@Entity
@Table(name = "company")
13public class Company implements Serializable {
14
15 @ManyToOne
16 @JoinColumn(name = "statusId")
17 private CompanyStatus status;
18
19 ...
20
}
21
22
23

@OneToMany

 Use mappedBy attribute for bi-directional associations with ManyToOne


being the owner.
 OneToMany being the owner or unidirectional with foreign key - try to
avoid such associations but can be achieved with @JoinColumn
 @JoinTable for Unidirectional with association table

Please see the many-to-one relationship between Contact and Company above. Company to
Contact will be a one-to-many relationship. The owner of this relationship is Contact and
hence we will use 'mappedBy' attribute in Company to make it bi-directional relationship.
1
@Entity
2 @Table(name = "company")
3 public class Company implements Serializable {
4
5 @OneToMany(mappedBy = "company", fetch = [Link])
6 @OrderBy("firstName asc")
private Set contacts;
7
8
...
9
10 }
11
Again, for this tutorial, we have kept Company to CompanyStatus relationship as uni-
directional.

@ManyToMany

 Use @JoinTable for entities linked through an association table.


 Use mappedBy attribute for bi-directional association.

@PrimaryKeyJoinColumn

@PrimaryKeyJoinColumn annotation is used for associated entities sharing the same primary
key. See OneToOne section for details.
1 @Entity
2 @Table(name = "company")
public class Company implements Serializable {
3
4 @Id
5 @Column(name = "id")
6 @GeneratedValue
7 private int id;
8
@OneToOne(cascade = [Link])
9 @PrimaryKeyJoinColumn
10 private CompanyDetail companyDetail;
11
12 ...
13}
14
15

@JoinColumn

Use @JoinColumn annotation for one-to-one or many-to-one associations when foreign key
is held by one of the entities. We can use @OneToOne or @ManyToOne mappedBy attribute
for bi-directional relations. Also see OneToOne and ManyToOne sections for more details.
1@ManyToOne
2@JoinColumn(name = "statusId")
3private CompanyStatus status;

@JoinTable

Use @JoinTable and mappedBy for entities linked through an association table.

@MapsId

Persist two entities with shared key (when one entity holds a foreign key to the other) using
@MapsId annotation. See OneToOne section for details.
1@OneToOne
2@MapsId
3@JoinColumn(name = "contactId")
4private Contact contact;

Hibernate Inheritance Mapping Annotations


To understand Inheritance Mapping annotations, you must first understand Inheritance
Mapping in Hiberate in detail. Once you understand Inheritance mapping concepts, please
review below for annotations to be used.

 table per class hierarchy - single table per Class Hierarchy Strategy: the <subclass>
element in Hibernate

1 @Entity
2 @Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="planetype",
3 discriminatorType=[Link] )
4
5 @DiscriminatorValue("Plane")
6 public class Plane { ... }
7
8 @Entity
9 @DiscriminatorValue("A320")
public class A320 extends Plane { ... }
10

 table per class/subclass - joined subclass Strategy: the <joined-subclass> element in


Hibernate

1@Entity
2@Inheritance(strategy=[Link])
3public class Boat implements Serializable { ... }
4
5@Entity
6@PrimaryKeyJoinColumn
public class Ferry extends Boat { ... }
7

 table per concrete class - table per Class Strategy: the <union-class> element in
Hibernate

1 @Entity
2 @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
3 public class Flight implements Serializable { ... }

Note: This strategy does not support the IDENTITY generator strategy:
the id has to be shared across several tables. Consequently, when using
this strategy, you should not use AUTO nor IDENTITY.

@Inheritance

See Hibernate Inheritance Mapping Annotations section for details.


1@Entity
2@Inheritance(strategy=InheritanceType.SINGLE_TABLE)

@DiscriminatorColumn

See Hibernate Inheritance Mapping Annotations section for details.


1@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
2@DiscriminatorColumn(name="planetype",
3discriminatorType=[Link] )

@DiscriminatorValue

See Hibernate Inheritance Mapping Annotations section for details.


1 @Entity
2 @Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="planetype",
3 discriminatorType=[Link] )
4
5 @DiscriminatorValue("Plane")
6 public class Plane { ... }
7
8 @Entity
9 @DiscriminatorValue("A320")
public class A320 extends Plane { ... }
10

RESTful Web Service - JAX-RS Annotations - Contents:


Annotation Package Detail/Import statement
@GET import [Link];
@Produces import [Link];
@Path import [Link];
@PathParam import [Link];
@QueryParam import [Link];
@POST import [Link];
@Consumes import [Link];
@FormParam import [Link];
@PUT import [Link];
@DELETE import [Link];

As stated earlier in Example Application, we are using Jersey for RESTful Web services and
JAX-RS annotations.

REST follows one-to-one mapping between create, read, update, and delete
(CRUD) operations and HTTP methods.

 To create a resource on the server, use POST.


 To retrieve a resource, use GET.
 To change the state of a resource or to update it, use PUT.
 To remove or delete a resource, use DELETE.

@GET

Annotate your Get request methods with @GET.


1@GET
2public String getHTML() {
3 ...
4}
@Produces

@Produces annotation specifies the type of output this method (or web service) will produce.
1@GET
2@Produces("application/xml")
3public Contact getXML() {
4 ...
5}
1@GET
2@Produces("application/json")
3public Contact getJSON() {
4 ...
5}

@Path

@Path annotation specify the URL path on which this method will be invoked.
1@GET
2@Produces("application/xml")
3@Path("xml/{firstName}")
4public Contact getXML() {
5 ...
}
6

@PathParam

We can bind REST-style URL parameters to method arguments using @PathParam


annotation as shown below.
1
@GET
2@Produces("application/xml")
3@Path("xml/{firstName}")
4public Contact getXML(@PathParam("firstName") String firstName) {
5 Contact contact = [Link](firstName);
6} return contact;
7
1
@GET
2@Produces("application/json")
3@Path("json/{firstName}")
4public Contact getJSON(@PathParam("firstName") String firstName) {
5 Contact contact = [Link](firstName);
6} return contact;
7

@QueryParam

Request parameters in query string can be accessed using @QueryParam annotation as shown
below.
1@GET
@Produces("application/json")
2@Path("json/companyList")
3public CompanyList getJSON(@QueryParam("start") int start,
4@QueryParam("limit") int limit) {
CompanyList list = new CompanyList([Link](start,
5limit));
6 return list;
7}
The example above returns a list of companies (with server side pagination) which can be
displayed with rich clients implemented using Ext-js or jQuery. You can read more more
about setting up ExtJS grid panel with remote sorting and pagination using Hibernate.

@POST

Annotate POST request methods with @POST.


1@POST
2@Consumes("application/json")
3@Produces("application/json")
4public RestResponse<Contact> create(Contact contact) {
5...
}
6

@Consumes

The @Consumes annotation is used to specify the MIME media types a REST resource can
consume.
1
@PUT
2@Consumes("application/json")
3@Produces("application/json")
4@Path("{contactId}")
5public RestResponse<Contact> update(Contact contact) {
6...
}
7

@FormParam

The REST resources will usually consume XML/JSON for the complete Entity Bean.
Sometimes, you may want to read parameters sent in POST requests directly and you can do
that using @FormParam annotation. GET Request query parameters can be accessed using
@QueryParam annotation.
1@POST
2public String save(@FormParam("firstName") String firstName,
3 @FormParam("lastName") String lastName) {
4 ...
}
5

@PUT

Annotate PUT request methods with @PUT.


1@PUT
@Consumes("application/json")
2@Produces("application/json")
3@Path("{contactId}")
4public RestResponse<Contact> update(Contact contact) {
5...
}
6
7

@DELETE

Annotate DELETE request methods with @DELETE.


1@DELETE
2@Produces("application/json")
3@Path("{contactId}")
public RestResponse<Contact> delete(@PathParam("contactId") int contactId)
4{
5...
6}

JAXB Annotations - Contents:


Annotation Package Detail/Import statement

@XmlRootElement import [Link];

@XmlElement import [Link];

@XmlType import [Link];

@XmlTransient import [Link];

@XmlSeeAlso import [Link];

Using JAXB and JPA Annotations in Conjunction

Using JAX-RS Annotations with JAXB and JPA Annotations

As stated earlier in Example Application, we are using JAXB to convert our Entities to XML or JSON
format, so our rich clients like Ext-js or jQuery can easily process and present the data.

@XmlRootElement

Define the root element for the XML to be produced with @XmlRootElement JAXB annotation. The
name of the root XML element is derived from the class name.

1@XmlRootElement
2public class Contact implements Serializable {

3...
}
4

You can also specify the name of the root element of the XML using its name attribute, for example
@XmlRootElement(name = "CompanyContact")

@XmlElement

Annotate all fields that needs to be included in XML/JSON output with @XMLElement.

1 @XmlElement
2 public String getName() {

3 return name;

4 }

Either annotate all fields or all getter methods in your Entity bean. A mix of both is not
supported. Add @XmlAccessorType([Link]) at the class level if you want
to annotate private fields instead of getter methods.

@XmlType

Specify the order in which XML elements or JSON output will be produced.

1@XmlRootElement

2@XmlType(propOrder = { "id", "firstName", "lastName", "email", "telephone"


})
3public class Contact implements Serializable {

4...

5}

The above @XmlType annotation will produce the following XML.

1
<contact>
2 <id>38</id>
3 <firstname>FirstName</firstname>

4 <lastname>LastName</lastname>

5 <email>dummyEmail@[Link]</email>

<telephone>1111111111</telephone>
6
</contact>
7

Similarly, it will produce the following JSON.


1{"id":"38","firstName":"FirstName","lastName":"LastName",

2"email":"dummyEmail@[Link]","telephone":"1111111111"}

@XmlTransient

Annotate fields that we do not want to be included in XML or JSON output with @XMLTransient.

1@XmlTransient

2public Date getVersion() {

3 return version;

4}

@XmlSeeAlso

Use @XmlSeeAlso annotation when we want another Entity bean included in the XML output. In our
example below, CompanyList bean refers to Company bean and the XML output should include XML
generated from Company Entity too.

1
@XmlRootElement(name = "List")
2
@XmlSeeAlso([Link])
3 public class CompanyList {

5 @XmlElement(name = "companyList")

6 public List<Company> getList() {

7 return list;

}
8
...
9
}
10

To include more than 1 classes, we can use @XmlSeeAlso JAXB annotation as:
@XmlSeeAlso({ [Link], [Link] })

Using JAXB and JPA Annotations in Conjunction

If you have reviewed both Hibernate - JPA Annotations and JAXB Annotations, the following snippet
illustrates usage of both JAXB and JPA annotations in the same entity Contact.
1 @Entity

2 @Table(name = "CONTACT")

@XmlRootElement
3
@XmlType(propOrder = { "id", "firstName", "lastName", "email",
4 "telephone" })
5 public class Contact implements Serializable {

7 @Id

8 @Column(name = "ID")

@GeneratedValue
9
private Integer id;
10

11
@Column(name = "firstName")
12
private String firstName;
13

14
@Column(name = "lastName")
15 private String lastName;
16

17 @Column(name = "EMAIL")
18 private String email;

19

20 @Column(name = "TELEPHONE")

21 private String telephone;

22
@Version
23
@Column(name = "version")
24
private Date version;
25

26
@ManyToOne
27
@JoinColumn(name = "companyId")
28 private Company company;
29

30 @OneToOne(mappedBy = "contact", cascade = [Link])


31 private ContactDetail contactDetail;
32

33 @XmlTransient

34 public Company getCompany() {

return company;
35
}
36

37
public void setCompany(Company company) {
38
[Link] = company;
39
}
40

41 @XmlTransient
42 public ContactDetail getContactDetail() {
43 return contactDetail;

44 }

45

46 public void setContactDetail(ContactDetail contactDetail) {

[Link] = contactDetail;
47
}
48

49
@XmlTransient
50
public Date getVersion() {
51
return version;
52 }
53

54 public void setVersion(Date version) {

55 [Link] = version;

56 }

57

58 @XmlElement

public Integer getId() {


59
return id;
60
}
61

62
63 public void setId(Integer id) {

64 [Link] = id;

}
65

66
@XmlElement
67
public String getFirstName() {
68
return firstName;
69
}
70

71 public void setFirstName(String firstName) {


72 [Link] = firstName;
73 }

74

75 @XmlElement

76 public String getLastName() {

return lastName;
77
}
78

79
public void setLastName(String lastName) {
80
[Link] = lastName;
81
}
82

83 @XmlElement
84 public String getEmail() {

85 return email;

86 }

87

88 public void setEmail(String email) {

[Link] = email;
89
}
90

91
@XmlElement
92
public String getTelephone() {
93
94 return telephone;

95 }

96
public void setTelephone(String telephone) {
97
[Link] = telephone;
98
}
99

100
}
101

102

103

104

105

106

107

Using JAX-RS Annotations with JAXB and JPA Annotations

This section assumes that you have reviewed RESTful JAX-RS Annotations, Hibernate - JPA
Annotations and JAXB Annotations. Also see the section above on using JAXB and JPA Annotations in
Conjunction.

Now that you have an entity bean containing both JAXB and JPA Annotations which is capable of
doing data exchange with database and coverting it to required JSON/XML format, the next step is
to send this data to rich clients using jQuery or Ext-js. In your REST based web-service methods,
return the Contact entity bean as shown below. Jersey, JAXB will take care of data conversion and
appropriate response generation.

1
@GET
2@Produces("application/xml")

3@Path("xml/{firstName}")

4public Contact getXML(@PathParam("firstName") String firstName) {

5 Contact contact = [Link](firstName);

return contact;
6
}
7
@GET
1
@Produces("application/json")
2@Path("json/{firstName}")

3public Contact getJSON(@PathParam("firstName") String firstName) {


Contact contact = [Link](firstName);
4
return contact;
5
}
6

Spring jUnit Annotations - Contents:


Annotation Package Detail/Import statement

@RunWith import [Link];

@ContextConfiguration import [Link];

@Test import [Link];

@DirtiesContext import [Link];

@Timed import [Link];

We are now ready to test our Spring based application using jUnit and Spring Unit testing
framework. The following jUnit and Spring annotations will be used to accomplish this.

@RunWith

When a class is annotated with @RunWith or extends a class annotated with @RunWith, JUnit will
invoke the class it references to run the tests in that class instead of the runner built into JUnit. Let
us configure jUnit to use Spring jUnit Class runner.
@RunWith([Link])
@ContextConfiguration(locations={"/[Link]"})
public class CompanyServiceTest {
...
}

@ContextConfiguration

Set the spring ApplicationContext for your test classes using @ContextConfiguration annotation.
@RunWith([Link])
@ContextConfiguration(locations={"/[Link]"})
public class CompanyServiceTest {
...
}

@ContextConfiguration provides support for inheriting resource locations or


configuration classes declared by superclasses by default.

@Test

Annotate all your jUnit unit tests with @Test. Also note that we can wire other spring beans in our
jUnit test classes using @Autowired annotation.
@Autowired
private CompanyService companyService;

@Test
public void testFindByName() {
Company company = [Link]("techferry");
if (company != null) {
assertEquals("prospect", [Link]().getName());
}
}

@DirtiesContext

Annotate @DirtiesContext to indicate that it dirties the ApplicationContext. This will trigger context
reloading before execution of next test.

@Timed

Indicates that the annotated test method must finish execution in a specified time period (in
milliseconds). If the text execution time exceeds the specified time period, the test fails.
@Timed(millis=1000)

Common questions

Powered by AI

JAX-RS annotations facilitate CRUD operations in RESTful Web Services by mapping HTTP methods to Java methods. The @POST annotation creates resources on the server, typically used with @Consumes to specify the request body's MIME type (e.g., JSON). @GET reads or retrieves a resource, often accompanied by @Produces to negotiate the response format like XML or JSON . The @PUT annotation updates existing resources, defined alongside @Consumes to handle input types and often paired with @Path to specify the resource endpoint . Finally, @DELETE removes a resource and is usually defined with @PathParam to delete specific resources by their identifier . These annotations align web service logic with HTTP methods, enabling clear and standardized operation definitions.

JAXB is used alongside JPA annotations to enable XML/JSON data transformation and persistence in Java applications. Entities annotated with JPA annotations are simultaneously annotated with JAXB annotations to define how they are converted to and from XML/JSON formats. Key annotations include @XmlRootElement, which marks a class as the root element, and @XmlElement, which indicates fields or methods included in the output . @XmlType specifies the order of XML elements, and @XmlTransient excludes fields from serialization . Using these annotations together, data can be efficiently retrieved and stored in databases using JPA and simultaneously exposed over REST web services in XML/JSON format using JAXB .

A shared primary key association is a one-to-one relationship where two entities share a primary key value. This is implemented using the @PrimaryKeyJoinColumn annotation. For example, entities Company and CompanyDetail share the same primary key, and are associated using @OneToOne and @PrimaryKeyJoinColumn, with CompanyDetail not using @GeneratedValue for its ID but sharing Company's ID . On the other hand, a foreign key association involves one entity having a foreign key reference to another entity's primary key. In a one-to-one foreign key association, @JoinColumn is used, as seen in the Contact to ContactDetail relationship where ContactDetail references Contact's ID with @JoinColumn and @MapsId .

Using the SINGLE_TABLE inheritance strategy results in one table for the entire class hierarchy, introducing a discriminator column to distinguish between types. This simplifies the schema and improves query performance for polymorphic queries because data from all subclass types resides in a single table. However, it can lead to many nullable columns if there are numerous subclasses with non-overlapping fields . The JOINED strategy creates one table per class, allowing normalized database design, which minimizes data redundancy. This approach produces more complex queries as it requires multiple joins to reconstruct an entity from its parts . The choice affects both schema design and performance, with SINGLE_TABLE providing faster reads but poorer write performance due to wide rows, and JOINED being more normalized but potentially incurring higher retrieval costs due to necessary joins.

The @JoinTable annotation in JPA is crucial for managing many-to-many relationships by defining a linking table to hold the associations between the two entities, which avoids direct foreign key columns in the primary tables. This annotation specifies the join table name and the respective foreign key columns, enhancing the ability to efficiently manage and query both sides of the relationship . In contrast, @JoinColumn is used for one-to-many or many-to-one associations, involving a single foreign key column and simpler relationships. While @JoinTable increases the database schema complexity by adding an additional table, it provides flexibility in managing complex many-to-many relationships, allowing additional columns for storing metadata about associations .

The @Version annotation is used to manage concurrency by maintaining a version number (or timestamp) for each entity. This version is updated whenever the entity is updated, allowing Hibernate to detect and prevent concurrent updates. If a concurrent update conflict is detected (e.g., if someone else updates the entity between the time it is read and written), it raises an OptimisticLockException, ensuring data integrity . A limitation is that it only works with detached entities and not with native SQL queries or when using direct JDBC updates, as these operations might bypass entity management functionalities .

The @ManyToOne association is preferred as the owning side in a one-to-many relationship because it maintains the foreign key, making it simpler to manage and more efficient to perform operations like updates and deletes. In Hibernate, the owning side of the relationship needs to be specified to manage the foreign key column; hence a ManyToOne association at the child entity level (e.g., Contact to Company) is used. This is managed using the @JoinColumn annotation, as demonstrated where Contact has a @ManyToOne relation to Company identified by 'companyId' . The inverse side can be managed using the mappedBy attribute to establish a bidirectional link .

A unidirectional relationship is chosen when access to one side of the relationship is unnecessary, which simplifies data management and potentially improves performance by reducing the number of joins required. For instance, the relationship between Company and CompanyDetail is unidirectional, simplifying the design and operations involving CompanyDetail by accessing it only through Company . Bidirectional relationships, however, provide navigation from both entities, facilitating queries that involve both sides, such as those needed in complex search operations. They should be carefully managed to avoid circular references and performance overheads, as seen with the Contact and ContactDetail bi-directional relationship .

The @OrderBy annotation in JPA specifies the order in which elements of a collection are retrieved from the database, directly affecting how this collection is presented in Java applications. It accepts SQL-like syntax to define the sorting criteria, such as ascending or descending order of entity attributes. For instance, `@OrderBy("firstName asc")` sorts a set of contacts by their first names in ascending order . Misuse of @OrderBy can lead to performance degradation, especially if applied to large collections without proper indexing, as it orchestrates in-memory sorting post-retrieval if not optimized, leading to increased memory usage and slower performance for large datasets .

The @MapsId annotation in Hibernate is used in a one-to-one shared primary key association to link a foreign key from one entity to the ID of another, ensuring they share the same primary key. This is particularly useful when the secondary entity's primary key should directly map to another entity’s primary key. In practice, this allows the primary key column of an entity to serve as a foreign key, promoting efficiency in database operations. An example is the association between Contact and ContactDetail where ContactDetail uses @MapsId to share Contact's primary key, thereby having a single identity space, which can be a critical requirement for seamless bidirectional navigation .

Spring Annotations: Contents: 
Annotation 
Package Detail/Import statement  
@Service   (http://www.techferry.com/articles/sp
Annotate all your DAO classes with @Repository. All your database access logic should be 
in DAO classes.  
@Repository 
publ
@Transactional 
Configure your transactions with @Transactional spring annotation.  
@Service 
public class CompanyServiceImp
Please note that the dependencies are resolved at instantiation time. For 
prototype scope, it does NOT create a new instan
You can bind request parameters to method variables using spring annotation 
@RequestParam.  
@Controller 
@RequestMapping("/
@SessionAttribute works as follows:  
 
@SessionAttribute is initialized when you put the corresponding attribute into model
Annotation 
Package Detail/Import statement  
@Entity  (http://www.techferry.com/articles/hibernate-jpa-annotations.html#Enti
2 
3 
4 
5 
@Table(name = "company") 
public class Company implements Serializable { 
... 
} 
@Column 
Specify the column map
Control versioning or concurrency using @Version annotation.  
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
@Entity 
@Table(name = "company
The database for this tutorial is designed to illustrate various association mapping concepts.  
In RDBMS implementations, en

You might also like