Spring Annotation Cheatsheet

To create APIs

@Controller, @RestControllerDefine a Controller (in MVC)Spring MVC
@RequestMapping, @GetMapping, @PostMapping, @PutMapping, @DeleteMappingDefine APIsSpring MVC
@PathVariable, @RequestParam, @RequestBodyBind to parameters on the API’s URLSpring MVC
@ServiceDefine a Spring component to be @Autowired in ControllerSpring MVC
@RepositoryDefine a Spring component interacting with the database, usually be @Autowired inside @Service or @ControllerSpring MVC
@BeanDefine a custom Spring bean, usually to be @Autowired on other components, or to override some built-in beans provided by librariesSpring
@ConfigurationDefine a Spring bean, that stores configurations for particular libraries or for the application.Spring
@AutowiredCreate reference to another beans without manually creating constructorsSpring
@ControllerAdvice & @ExceptionHandlerCreate custom exception handlersSpring
Integer port;
Read values from application.propertiesSpring
Spring Web cheatsheet

To create database schema

Annotation & sample usagesFunctionVendor
class Company {… }
Create a table with name companyJPA/Hibernate
class User {…}
// “user” is a reserved keyword on Postgres
Create a table with name my_userJPA/Hibernate
@Id @GeneratedValue
Long companyId;
Define primary key with autogenerated idJPA/Hibernate
@GeneratedValueCreate a field that value is auto generated using shared sequence tableJPA/Hibernate
@GeneratedValue(strategy = GenerationType.IDENTITY)Create a field that value is auto generated using sequence table per [entity+column]JPA/Hibernate
String companyDescription;
Define column data typeJPA/Hibernate
@Column(columnDefinition=”boolean default true”)
Boolean active;
Define column data type and default valueJPA/Hibernate
@Column(name=”custom_column_name”)Specify column nameJPA/Hibernate
@Enumerated(EnumType.STRING)Tell hibernate to store enum value as String instead of ordinalJPA/Hibernate
Company employeeCompany;
Define Foreign key referencing to table companyJPA/Hibernate
UserProfile sampleUseProfile;
Foreign key field with 1:1 constraint. JPA/Hibernate
List<Address> sampleListAddress;
There will be a temporary table with 2 columns : company_id & address_idJPA/Hibernate
@OneToMany(fetch = FetchType.LAZY), @ManyToOne(fetch = FetchType.LAZY) , …To apply Lazy Loading technique to foreign key fieldsJPA/Hibernate
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
class ParentClass { … }

class ChildClass extend ParentClass { … }
There will be separated tables created for each child classes & parent classJPA/Hibernate
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
class ParentClass { … }
There will be only single table containing all columns of parent & child classesJPA/Hibernate
@Inheritance(strategy = InheritanceType.JOINED)
class ParentClass { … }
Each class has its table and querying a subclass entity requires joining the tablesJPA/Hibernate
List<String> sampleStringListField;
To store a List type field. There will be a temporary table created.JPA/Hibernate
public void beforeCreated() {…}
Method will be executed before a new entity is createdJPA/Hibernate
public void beforeUpdated(){…}
Method will be executed before an existing entity is updatedJPA/Hibernate
public void beforeDeleted() {…}
Method will be executed before an entity is about to removedJPA/Hibernate
public void afterCreated() {…}
Method will be executed after a new entity is createdJPA/Hibernate
public void afterUpdated() { … }
Method will be executed after an existing entity is updatedJPA/Hibernate
public void afterDeleted() {…}
Method will be executed after an entity is about to removedJPA/Hibernate
JPA/Hibernate Cheatsheet

To create Query

public interface UserRepository extends PagingAndSortingJpaRepository<User, Long> {
// Using Hibernate Query Language (HQL)
// auto generate query using method names
Optional<List<User>> findAllByActiveIsAndUsernameIs(Boolean active, String username);

// Using custom query
@Query("select c from Customer c where lower(concat(c.firstName, ' ', c.lastName)) like lower(concat(:q, '%') ) or lower(concat(c.firstName, ' ', c.middleName, ' ', c.lastName)) like lower(concat(:q, '%') )")
Optional<List<User>> search(@QueryParam String q);

// Join tables
@Query("select u,h from User u inner join House h on h.user_id = u.id where h.address like lower(concat(:q, '%') )")
Optional<List<User>> searchByAddress(@QueryParam String q);


Annotation & sample usagesFunctionVendor
class UserDTO { … }
Generate no argument constructorLombok
class UserDTO { … }
Generate a constructor with all argumentsLombok
class UserDTO { … }
Generate getter & setter methodsLombok
class UserDTO { … }
Generate builderLombok
class UserDTO { … }
Generate builder , used for inheritance caseLombok
interface UserMapper {
public static UserMapper instance = Mappers.getClass(UserMapper.class)

Define a Mapper objectMapstruct
@Mapping(target=”field_a”, source=”field_b”, formatter=”formatterBeanName”)
@Mapping(source=”password”, ignore=true)
UserDTO fromUser(User user);

User fromDTO(UserDTO dto);
Configure Mapping of methods inside @MapperMapstruct
POJO code generating

Read custom configurations from application.properties

public class SettingProperties {
 String prop; 
 Long value;
 Boolean enabled;
public class SettingConfig {
 SettingProperties settingProperties;
 public SettingConfig(SettingProperties props) {...}
setting.prop="Some text"

Async methods

public class SomeService {
 SomeRepository someRepository;
 public void someAsyncMethod(String param) {
 /// ... 


// to invoke

Cron job

@EnableScheduling // enable cron job support
public class CronJobConfig {
@Scheduled(fixedDelay = 1000)
public void scheduleFixedDelayTask() {
      "Fixed delay task - " + System.currentTimeMillis() / 1000);
public class ScheduledFixedRateExample {
    @Scheduled(fixedRate = 1000)
    public void scheduleFixedRateTaskAsync() throws InterruptedException {
          "Fixed rate task async - " + System.currentTimeMillis() / 1000);

@Scheduled(cron = "0 15 10 15 * ?")
public void scheduleTaskUsingCronExpression() {

    long now = System.currentTimeMillis() / 1000;
      "schedule tasks using cron jobs - " + now);