To create APIs
Annotation | Function | Vendor |
@Controller, @RestController | Define a Controller (in MVC) | Spring MVC |
@RequestMapping, @GetMapping, @PostMapping, @PutMapping, @DeleteMapping | Define APIs | Spring MVC |
@PathVariable, @RequestParam, @RequestBody | Bind to parameters on the API’s URL | Spring MVC |
@Service | Define a Spring component to be @Autowired in Controller | Spring MVC |
@Repository | Define a Spring component interacting with the database, usually be @Autowired inside @Service or @Controller | Spring MVC |
@Bean | Define a custom Spring bean, usually to be @Autowired on other components, or to override some built-in beans provided by libraries | Spring |
@Configuration | Define a Spring bean, that stores configurations for particular libraries or for the application. | Spring |
@Autowired | Create reference to another beans without manually creating constructors | Spring |
@ControllerAdvice & @ExceptionHandler | Create custom exception handlers | Spring |
@Value(“${server.port}”) Integer port; | Read values from application.properties | Spring |
To create database schema
Annotation & sample usages | Function | Vendor |
@Entity class Company {… } | Create a table with name company | JPA/Hibernate |
@Entity(name=”my_user”) class User {…} // “user” is a reserved keyword on Postgres | Create a table with name my_user | JPA/Hibernate |
@Id @GeneratedValue Long companyId; | Define primary key with autogenerated id | JPA/Hibernate |
@GeneratedValue | Create a field that value is auto generated using shared sequence table | JPA/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 type | JPA/Hibernate |
@Column(columnDefinition=”boolean default true”) Boolean active; | Define column data type and default value | JPA/Hibernate |
@Column(name=”custom_column_name”) | Specify column name | JPA/Hibernate |
@Enumerated(EnumType.STRING) | Tell hibernate to store enum value as String instead of ordinal | JPA/Hibernate |
@ManyToOne Company employeeCompany; | Define Foreign key referencing to table company | JPA/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_id | JPA/Hibernate |
@OneToMany(fetch = FetchType.LAZY), @ManyToOne(fetch = FetchType.LAZY) , … | To apply Lazy Loading technique to foreign key fields | JPA/Hibernate |
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) class ParentClass { … } class ChildClass extend ParentClass { … } | There will be separated tables created for each child classes & parent class | JPA/Hibernate |
@Inheritance(strategy = InheritanceType.SINGLE_TABLE) class ParentClass { … } | There will be only single table containing all columns of parent & child classes | JPA/Hibernate |
@Inheritance(strategy = InheritanceType.JOINED) class ParentClass { … } | Each class has its table and querying a subclass entity requires joining the tables | JPA/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 created | JPA/Hibernate |
@PreUpdate public void beforeUpdated(){…} | Method will be executed before an existing entity is updated | JPA/Hibernate |
@PreRemove() public void beforeDeleted() {…} | Method will be executed before an entity is about to removed | JPA/Hibernate |
@PostPersist public void afterCreated() {…} | Method will be executed after a new entity is created | JPA/Hibernate |
@PostUpdatted public void afterUpdated() { … } | Method will be executed after an existing entity is updated | JPA/Hibernate |
@PostRemoved public void afterDeleted() {…} | Method will be executed after an entity is about to removed | JPA/Hibernate |
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 usages | Function | Vendor |
@NoArgsConstructor class UserDTO { … } | Generate no argument constructor | Lombok |
@AllArgsConstructor class UserDTO { … } | Generate a constructor with all arguments | Lombok |
@Data class UserDTO { … } | Generate getter & setter methods | Lombok |
@Builder class UserDTO { … } | Generate builder | Lombok |
@SuperBuilder class UserDTO { … } | Generate builder , used for inheritance case | Lombok |
@Mapper interface UserMapper { public static UserMapper instance = Mappers.getClass(UserMapper.class) … } | Define a Mapper object | Mapstruct |
@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 @Mapper | Mapstruct |
Read custom configurations from application.properties
@Configuration
@ConfigurationProperties(prefix="setting")
public class SettingProperties {
String prop;
Long value;
Boolean enabled;
....// ** standard getters & setters
}
=====
@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);
}