Spring Annotation Cheatsheet

To create APIs

AnnotationFunctionVendor
@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
@Value(“${server.port}”)
Integer port;
Read values from application.propertiesSpring
Spring Web cheatsheet

To create database schema

Annotation & sample usagesFunctionVendor
@Entity
class Company {… }
Create a table with name companyJPA/Hibernate
@Entity(name=”my_user”)
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
@Column(columnDefinition=”TEXT”)
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
@ManyToOne
Company employeeCompany;
Define Foreign key referencing to table companyJPA/Hibernate
@OneToOne
UserProfile sampleUseProfile;
Foreign key field with 1:1 constraint. JPA/Hibernate
@OneToMany
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
@ElementCollection(targetClass=String.class)
List<String> sampleStringListField;
To store a List type field. There will be a temporary table created.JPA/Hibernate
@PrePersist
public void beforeCreated() {…}
Method will be executed before a new entity is createdJPA/Hibernate
@PreUpdate
public void beforeUpdated(){…}
Method will be executed before an existing entity is updatedJPA/Hibernate
@PreRemove()
public void beforeDeleted() {…}
Method will be executed before an entity is about to removedJPA/Hibernate
@PostPersist
public void afterCreated() {…}
Method will be executed after a new entity is createdJPA/Hibernate
@PostUpdatted
public void afterUpdated() { … }
Method will be executed after an existing entity is updatedJPA/Hibernate
@PostRemoved
public void afterDeleted() {…}
Method will be executed after an entity is about to removedJPA/Hibernate
JPA/Hibernate Cheatsheet

To create Query

@Repository
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);
}

POJO

Annotation & sample usagesFunctionVendor
@NoArgsConstructor
class UserDTO { … }
Generate no argument constructorLombok
@AllArgsConstructor
class UserDTO { … }
Generate a constructor with all argumentsLombok
@Data
class UserDTO { … }
Generate getter & setter methodsLombok
@Builder
class UserDTO { … }
Generate builderLombok
@SuperBuilder
class UserDTO { … }
Generate builder , used for inheritance caseLombok
@Mapper
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

@ConfigurationProperties(prefix="setting")
public class SettingProperties {
 String prop; 
 Long value;
 Boolean enabled;
 ....
}
=====
@Configuration
@EnableConfigurationProperties(SettingProperties.class)
public class SettingConfig {
 SettingProperties settingProperties;
 public SettingConfig(SettingProperties props) {...}
}
====
//application.properties
setting.prop="Some text"
setting.value=3
setting.enabled=true

Async methods

@Service
public class SomeService {
 @Autowired
 SomeRepository someRepository;
 
 @Asyn
 public void someAsyncMethod(String param) {
 someRepository.findAll();
 /// ... 
 }

}

// to invoke
someService.someAsyncMethod("...");

Cron job

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

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

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