<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sophea PHOS on Medium]]></title>
        <description><![CDATA[Stories by Sophea PHOS on Medium]]></description>
        <link>https://medium.com/@phsophea101?source=rss-abe9dc254536------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5FWvdg09xj_1LDDkNLaKoA.jpeg</url>
            <title>Stories by Sophea PHOS on Medium</title>
            <link>https://medium.com/@phsophea101?source=rss-abe9dc254536------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 06:37:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@phsophea101/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Enhancing Localization(Internationalization) from Database with a Custom Annotation in Spring Boot]]></title>
            <link>https://phsophea101.medium.com/enhancing-localization-internationalization-from-database-with-a-custom-annotation-in-spring-boot-634165aed7b0?source=rss-abe9dc254536------2</link>
            <guid isPermaLink="false">https://medium.com/p/634165aed7b0</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[transaltion]]></category>
            <category><![CDATA[java-internationalization]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Sophea PHOS]]></dc:creator>
            <pubDate>Mon, 08 Jan 2024 15:20:13 GMT</pubDate>
            <atom:updated>2024-01-09T00:42:05.535Z</atom:updated>
            <content:encoded><![CDATA[<p>Localization and internationalization are concepts related to adapting software applications to different languages, regions, and cultural preferences to make them accessible and usable by people around the world.</p><p>Internationalization (often abbreviated as “i18n”) is the process of designing and developing software applications in a way that allows for easy adaptation to different languages, regions, and cultures without requiring code changes. It involves separating the user interface (UI) text, messages, and other localizable elements from the application’s code and storing them in resource files or databases. This enables the application to be easily translated and localized for different target audiences.</p><p>Localization (often abbreviated as “l10n”) is the process of adapting a software application that has been internationalized to a specific language, region, or culture. It involves translating the text, messages, labels, and other UI elements into the target language, as well as adjusting the application’s behavior and appearance to suit the cultural norms and preferences of the target audience. This may include formatting dates, numbers, currencies, and other locale-specific information correctly, as well as considering factors such as language direction (left-to-right or right-to-left), character encoding, and localized content.</p><p>Localization typically involves working with translators and linguists who are proficient in the target language and have an understanding of the target culture. They translate the text and adapt the application’s content to ensure it is linguistically and culturally appropriate for the target audience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*40LvSkfnJMijNBHsIw6z7g.png" /></figure><p>To implement localization with a custom annotation in Spring Boot, we can follow these step-by-step instructions:</p><p>Step 1: Create a Custom Annotation<br>Create a custom annotation to mark the fields that require localization. For example, let’s create a @I18NProperty annotation:</p><pre>@Target(ElementType.FIELD)<br>@Retention(RetentionPolicy.RUNTIME)<br>public @interface I18NProperty {<br>   /**<br>    * id to find the translation<br>    */<br>   String fieldId() default &quot;id&quot;;<br>   /**<br>    * type of translate<br>    */<br>   String type();<br>   <br>   String locale() default &quot;&quot;;<br>}</pre><p>Step 2: Create a Interface<br>A provider interface specifies a set of methods that must be implemented by a service provider in order to provide a specific functionality. It defines the contract or API that the provider must adhere to, without specifying the actual implementation details.now we greate a Interface with some parameters to query from database to get message from the specific locale. For example, let’s create a I18NProvider Interface:</p><pre>public interface I18NProvider {<br>    String getMessage(String key, String type, String locale, String defaultMessage);<br>}</pre><p>Step 3: Create a extends class of StdSerializer<br>To serialize to JSON, we need to create a custom serializer using StdSerializer, and extend the class and implement the serialize() method. This method defines how Java object should be serialized to JSON. we can customize the serialization process according to our specific requirements.</p><p>Here’s an example of how you can create a custom serializer by extending StdSerializer:</p><pre>@Slf4j<br>public class I18NSerializer extends StdSerializer&lt;Object&gt; {<br>    private static final long serialVersionUID = -2391442805192997903L;<br>    private final I18NProvider provider;<br>    public I18NSerializer(I18NProvider provider) {<br>        super(Object.class);<br>        this.provider = provider;<br>    }<br>    @Override<br>    public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {<br>        String i18nValue = getI18NProperty(value, gen);<br>        if (ObjectUtils.isNotEmpty(i18nValue))<br>            gen.writeString(i18nValue);<br>        else<br>            gen.writeNull();<br>    }<br>    @Override<br>    public void serializeWithType(Object value, JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {<br>        String i18nValue = getI18NProperty(value, gen);<br>        if (ObjectUtils.isNotEmpty(i18nValue))<br>            super.serializeWithType(i18nValue, gen, serializers, typeSer);<br>        else<br>            gen.writeNull();<br>    }<br>    private String getI18NProperty(Object value, JsonGenerator gen) {<br>        try {<br>            ObjectMapper objectMapper = (ObjectMapper) gen.getCodec();<br>            PropertyNamingStrategy namingStrategy = objectMapper.getPropertyNamingStrategy();<br>            String fieldName = gen.getOutputContext().getCurrentName();<br>            if (PropertyNamingStrategies.SNAKE_CASE.equals(namingStrategy))<br>                fieldName = this.snakeCaseToCamelCase(fieldName);<br>            Object obj = gen.getCurrentValue();<br>            I18NProperty annotation = obj.getClass().getDeclaredField(fieldName).getAnnotation(I18NProperty.class);<br>            String locale = annotation.locale();<br>            locale = StringUtils.isNotEmpty(locale) ? locale : LocaleContextHolder.getLocale().getLanguage();<br>            String i18nId = (String) PropertyUtils.getProperty(obj, annotation.fieldId());<br>            return this.provider.getMessage(i18nId, annotation.type(), locale.toLowerCase(), (String) value);<br>        } catch (Exception e) {<br>            log.warn(&quot;exception occurred while serializer I18N property {} of class {} {}&quot;, gen.getOutputContext().getCurrentName(), gen.getCurrentValue().getClass().getName(), e.getMessage());<br>            return (String) value;<br>        }<br>    }<br>    private String snakeCaseToCamelCase(String string) {<br>        if (ObjectUtils.isEmpty(string)) return string;<br>        StringBuilder sb = new StringBuilder(string);<br>        for (int i = 0; i &lt; sb.length(); i++) {<br>            if (sb.charAt(i) == &#39;_&#39;) {<br>                sb.deleteCharAt(i);<br>                sb.replace(i, i + 1, String.valueOf(Character.toUpperCase(sb.charAt(i))));<br>            }<br>        }<br>        return sb.toString();<br>    }<br>}</pre><p>In this class, I18NSerialzer extends StdSerializer&lt;CustomObject&gt;, where I18nSerializer is the implemented interface that we want got message to serialize. The serialize() method is overridden to define the serialization logic of our message from the specific locale. In this case, it writes the fields of the annotated field@I18NPropertyto the JSON generator.</p><p>Step 4: Create a extends class of SimpleModule<br>SimpleModule is a part of the Jackson ObjectMapper framework. Jackson is a popular library used for JSON (JavaScript Object Notation) serialization and deserialization in Java. To register custom serializers(I18NSerialzer) and deserializers for specific types. It provides a simple way to extend the serialization and deserialization capabilities of the ObjectMapper.</p><pre>public class I18NModule extends SimpleModule {<br>    private static final long serialVersionUID = 8750960660810211977L;<br>    private final I18NSerializer i18NSerializer;<br>    public I18NModule(I18NProvider provider) {<br>        Assert.notNull(provider, &quot;I18N provider must not be null&quot;);<br>        this.i18NSerializer = new I18NSerializer(provider);<br>    }<br>    @Override<br>    public void setupModule(SetupContext context) {<br>        context.addBeanSerializerModifier(new BeanSerializerModifier() {<br>            @Override<br>            public List&lt;BeanPropertyWriter&gt; changeProperties(SerializationConfig config, BeanDescription beanDesc, List&lt;BeanPropertyWriter&gt; beanProperties) {<br>                for (BeanPropertyWriter writer : beanProperties) {<br>                    if (ObjectUtils.isNotEmpty(writer.getAnnotation(I18NProperty.class))) {<br>                        writer.assignSerializer(i18NSerializer);<br>                        writer.assignNullSerializer(i18NSerializer);<br>                    }<br>                }<br>                return beanProperties;<br>            }<br>        });<br>    }<br>}</pre><p>In this class, I18NModule is a module to be registering a custom serializer (I18NSerialzer) with the SimpleModule.</p><p>Step 5: How we creare bean for this module(I18NModule)<br>There are two ways to register this module as we can see from the below examples:</p><pre>@Bean<br>public I18NModule i18NModule(I18nServiceImpl provider) {<br>    return new I18NModule(provider);<br>}<br>// or<br>@Bean<br>public ObjectMapper mapper(I18nServiceImpl provider) {<br>    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();<br>    builder.failOnUnknownProperties(false);<br>    ObjectMapper mapper = builder.build();<br>    SerializerProvider serializerProvider = mapper.getSerializerProvider();<br>    if (ObjectUtils.isNotEmpty(serializerProvider))<br>        mapper.setSerializerProvider(new CustomDefaultSerializerProvider());<br>    mapper.setPropertyNamingStrategy(new PropertyNamingStrategies.SnakeCaseStrategy());<br>    mapper.registerModule(new I18NModule(provider));<br>    return mapper;<br>}</pre><p>The below class show how we set the default locale and supported locales and also how we create bean for this class</p><pre>public class SmartLocaleResolver extends AcceptHeaderLocaleResolver {<br>    @Override<br>    public Locale resolveLocale(HttpServletRequest request) {<br>        Locale defaultLocale = new Locale(&quot;en&quot;);<br>        List&lt;Locale&gt; supportedLocales = Arrays.asList(new Locale(&quot;km&quot;), new Locale(&quot;en&quot;), new Locale(&quot;kr&quot;));<br>        if (StringUtils.isBlank(request.getHeader(&quot;Accept-Language&quot;))) {<br>            return defaultLocale;<br>        }<br>        this.setSupportedLocales(supportedLocales);<br>        List&lt;Locale.LanguageRange&gt; list = Locale.LanguageRange.parse(request.getHeader(&quot;Accept-Language&quot;));<br>        Locale locale = Locale.lookup(list, getSupportedLocales());<br>        if (ObjectUtils.isEmpty(locale))<br>            return defaultLocale;<br>        return locale;<br>    }<br><br>}<br>@Bean<br>public LocaleResolver localeResolver() {<br>    return new SmartLocaleResolver();<br>}</pre><p>And all of these below classes, show how we store the message of locale in database and query back from the implementation of provider interface I18NProvider</p><pre>@Setter<br>@Getter<br>@Entity<br>@Table(name = I18nEntity.TABLE_NAME)<br>public class I18nEntity {<br>    public static final String TABLE_NAME = &quot;i18n&quot;;<br>    @Id<br>    @Column(nullable = false, unique = true)<br>    private String id;<br>    @Column(nullable = false)<br>    private String key;<br>    @Column(nullable = false)<br>    private String locale;<br>    @Column(nullable = false)<br>    private String type;<br>    private String message;<br>    @Column(name = &quot;created_by&quot;)<br>    protected String createdBy;<br>    @Temporal(TemporalType.TIMESTAMP)<br>    @Column(name = &quot;created_date&quot;)<br>    protected Date createdDate;<br>    @Override<br>    public int hashCode() {<br>        return Objects.hash(key, locale, type);<br>    }<br>    private String status;<br>}</pre><pre>create table public.i18n (<br> id bigserial not null,<br> &quot;type&quot; varchar(255) not null,<br> locale varchar(255) not null,<br> &quot;key&quot; varchar(255) not null,<br> created_by varchar(255) null,<br> created_date timestamp null,<br> message text null,<br> status varchar(255) null,<br> constraint i18n_pkey primary key (id)<br>);</pre><pre>@Data<br>public class I18nDTO implements Serializable {<br>    private static final long serialVersionUID = 1905122041950251207L;<br>    private String id;<br>    private String key;<br>    private String locale;<br>    private String message;<br>    private String type;<br>}</pre><pre>public interface I18nService {<br>}<br><br>@Service<br>@AllArgsConstructor<br>public class I18nServiceImpl implements I18nService, I18NProvider {<br>    private final I18nRepository repository;<br><br>    @Override<br>    public String getMessage(String key, String type, String locale, String defaultMessage) {<br>        I18nEntity entity = new I18nEntity();<br>        entity.setKey(key);<br>        entity.setType(type);<br>        entity.setLocale(locale);<br>        entity.setStatus(&quot;ACTIVE&quot;);<br>        Optional&lt;I18nEntity&gt; nEntity = this.repository.findOne(Example.of(entity));<br>        if (nEntity.isPresent())<br>           return nEntity.get().getMessage();<br>        return defaultMessage;<br>    }<br>}</pre><p>And finally here is the use case and sample</p><p>This sample will localize from header locale</p><pre>@I18NProperty(fieldId = &quot;gender&quot;, type = &quot;gender.label&quot;)<br>private String gender;</pre><pre>private String id; // product id<br>@I18NProperty(type = &quot;product.name&quot;)<br>private String productName;</pre><p>This sample will localize for “km” only</p><pre>private String id; // product id<br>@I18NProperty(type = &quot;product.name&quot;, locale = &quot;km&quot;)<br>private String productName;</pre><pre>@I18NProperty(fieldId = &quot;gender&quot;, type = &quot;gender.label&quot;, locale = &quot;km&quot;)<br>private String gender;</pre><p><a href="https://github.com/phsophea101/spring-boot-localization-with-custom-annotation-from-database">GitHub - phsophea101/spring-boot-localization-with-custom-annotation-from-database</a></p><p>To summarize; In this article, I tried to explain how to translate from any language from Database via Spring Data JPA or Hibernate and also you can use the localize from file too. I recommend to use this annotation from VO level before response to client only. You can access the source code via the github link above.</p><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Visit </em><a href="https://phsophea101.github.io/"><strong>phsophea101.github.io</strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li><li>If you like my work and would like to buy me a coffee please go this <a href="http://buymeacoffee.com/phsophea101"><strong><em>buymeacoffee link</em></strong></a>. Thank you :)</li></ul><p>Good luck!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=634165aed7b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Data Types and Default Values in RESTful APIs with Spring Boot API design]]></title>
            <link>https://phsophea101.medium.com/data-types-and-default-values-in-rest-api-spring-boot-4a994980cf91?source=rss-abe9dc254536------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a994980cf91</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[standards]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Sophea PHOS]]></dc:creator>
            <pubDate>Fri, 29 Dec 2023 16:42:02 GMT</pubDate>
            <atom:updated>2024-01-04T07:57:47.715Z</atom:updated>
            <content:encoded><![CDATA[<p>In designing REST APIs, handling data types and default values carefully is essential to creating user-friendly and robust interfaces. As developers, we can construct APIs that are intuitive, adaptable, and aligned with user expectations by understanding these concepts and their implications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wJyeDYd_F8fUhbR79l7wAg.png" /></figure><p>Data types, the fundamental building blocks of programming, wield significant influence when shaping API contracts. The purpose of the API implementation is to enable developers of web applications who wish to build APIs to manipulate the data as desired.</p><p>Assume we have an application that have some API and can make request and response.</p><p>Now I create a class and extended from DefaultSerializerProvider name CustomDefaultSerializerProvider also @Override some functions <em>createInstance</em>, <em>copy </em>and <em>findNullValueSerializer</em></p><pre>public class CustomDefaultSerializerProvider extends DefaultSerializerProvider {<br>    public CustomDefaultSerializerProvider() {<br>        super();<br>    }<br>    public CustomDefaultSerializerProvider(CustomDefaultSerializerProvider src) {<br>        super(src);<br>    }<br>    protected CustomDefaultSerializerProvider(CustomDefaultSerializerProvider provider, SerializationConfig config, SerializerFactory jsf) {<br>        super(provider, config, jsf);<br>    }<br>    @Override<br>    public CustomDefaultSerializerProvider createInstance(SerializationConfig config, SerializerFactory jsf) {<br>        return new CustomDefaultSerializerProvider(this, config, jsf);<br>    }<br>    @Override<br>    public DefaultSerializerProvider copy() {<br>        if (getClass() != CustomDefaultSerializerProvider.class)<br>            return super.copy();<br>        return new CustomDefaultSerializerProvider(this);<br>    }<br>    @Override<br>    public JsonSerializer&lt;Object&gt; findNullValueSerializer(BeanProperty property) throws JsonMappingException {<br>        if (String.class.isAssignableFrom(property.getType().getRawClass()))<br>            return new DefaultJsonSerializer(Strings.EMPTY);<br>        else if (this.isClassDecimal(property.getType().getRawClass()))<br>            return new DefaultJsonSerializer(BigDecimal.valueOf(BigDecimal.ZERO.doubleValue()));<br>        else if (Number.class.isAssignableFrom(property.getType().getRawClass()))<br>            return new DefaultJsonSerializer(BigInteger.ZERO);<br>        else if (Boolean.class.isAssignableFrom(property.getType().getRawClass()))<br>            return new DefaultJsonSerializer(Boolean.FALSE);<br>        else if (this.isClassDate(property.getType().getRawClass()))<br>            return new DefaultJsonSerializer(null);<br>        else if (Collection.class.isAssignableFrom(property.getType().getRawClass()))<br>            return new DefaultJsonSerializer(new ArrayList&lt;&gt;());<br>        else if (Object.class.isAssignableFrom(property.getType().getRawClass()))<br>            return new DefaultJsonSerializer(null);<br>        else<br>            return super.findNullValueSerializer(property);<br>    }<br>    private boolean isClassDate(Class&lt;?&gt; clazz) {<br>        return Date.class.isAssignableFrom(clazz) || LocalDate.class.isAssignableFrom(clazz) || LocalDateTime.class.isAssignableFrom(clazz);<br>    }<br>    private boolean isClassDecimal(Class&lt;?&gt; clazz) {<br>        return Float.class.isAssignableFrom(clazz) || BigDecimal.class.isAssignableFrom(clazz) || Double.class.isAssignableFrom(clazz);<br>    }<br>    private static class DefaultJsonSerializer extends JsonSerializer&lt;Object&gt; {<br>        private final Object defaultValue;<br>        public DefaultJsonSerializer(Object defaultValue) {<br>            this.defaultValue = defaultValue;<br>        }<br><br>        @Override<br>        public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {<br>            jsonGenerator.writeObject(this.defaultValue);<br>        }<br>    }<br>}</pre><p>Depending on yours, for me I made default value for:</p><p>String is empty string (“”)<br>Number is zero (0)<br>Boolean is <em>FALSE</em>(false)<br>Collection is the empty array ([])<br>and other data type keep same for null</p><p>The last just set or register it to ObjectMapper</p><pre>@Configuration<br>public class AppConfig {<br>    @Bean<br>    ObjectMapper mapper(Jackson2ObjectMapperBuilder mapperBuilder) {<br>        ObjectMapper mapper = mapperBuilder.build();<br>        SerializerProvider serializerProvider = mapper.getSerializerProvider();<br>        if (ObjectUtils.isNotEmpty(serializerProvider))<br>            mapper.setSerializerProvider(new CustomDefaultSerializerProvider());<br>        mapper.setPropertyNamingStrategy(new PropertyNamingStrategies.SnakeCaseStrategy());<br>        return mapper;<br>    }<br>}</pre><h3>The Result from:</h3><pre>{<br>    &quot;status&quot;: &quot;200&quot;,<br>    &quot;result&quot;: &quot;Succeeded&quot;,<br>    &quot;data&quot;: {<br>        &quot;id&quot;: &quot;5&quot;,<br>        &quot;name&quot;: null,<br>        &quot;gender&quot;: null,<br>        &quot;username&quot;: &quot;jonh&quot;,<br>        &quot;status&quot;: &quot;ACTIVE&quot;,<br>        &quot;is_graduated&quot;: null,<br>        &quot;skills&quot;: null,<br>        &quot;age&quot;: null<br>    }<br>}</pre><h3>To</h3><pre>{<br>    &quot;status&quot;: &quot;200&quot;,<br>    &quot;result&quot;: &quot;Succeeded&quot;,<br>    &quot;data&quot;: {<br>        &quot;id&quot;: &quot;5&quot;,<br>        &quot;name&quot;: &quot;&quot;,<br>        &quot;gender&quot;: &quot;&quot;,<br>        &quot;username&quot;: &quot;jonh&quot;,<br>        &quot;status&quot;: &quot;ACTIVE&quot;,<br>        &quot;is_graduated&quot;: false,<br>        &quot;skills&quot;: [],<br>        &quot;age&quot;: 0<br>    }<br>}</pre><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Visit </em><a href="https://phsophea101.github.io/"><em>phsophea101.github.io</em></a><em> to find out more about how we are democratizing free programming education around the world.</em></li><li>If you like my work and would like to buy me a coffee please go this <a href="http://buymeacoffee.com/phsophea101"><em>buymeacoffee link</em></a>. Thank you :)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a994980cf91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Practices for API Request and Response Handlings in Spring Boot Development]]></title>
            <link>https://phsophea101.medium.com/standard-api-request-and-response-with-spring-boot-f3a7cf7f4422?source=rss-abe9dc254536------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3a7cf7f4422</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Sophea PHOS]]></dc:creator>
            <pubDate>Fri, 29 Dec 2023 08:00:33 GMT</pubDate>
            <atom:updated>2024-01-04T07:59:25.346Z</atom:updated>
            <content:encoded><![CDATA[<p>All APIs of every Orginization. maintaining a standardized request and response format across various endpoints is not just good practice; it’s a crucial element in crafting robust and scalable APIs. One effective way to achieve this consistency is by implementing a API Requestand API Response for every endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PN15_hJk1YEpPraUQDvBHw.jpeg" /></figure><p>In this article, we’ll bring up Spring Boot applications to explore the significance of this approach and how it can streamline your development process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gK3ennYzBJAZswHC8i1EVw.png" /></figure><p>Assume we have an application that does the CRUD operations which is written in spring boot.</p><h3>Default API Response class</h3><p>In this I’ll create three classes that can build response with success and fail.</p><pre>public class ResponseErrorVo {<br>    private String code;<br>    private String message;<br>    private String description;<br>    public ResponseErrorVo(String code, String message) {<br>        this.code = code;<br>        this.message = message;<br>        this.description = message;<br>    }<br>    public ResponseErrorVo(String code, String message, String description) {<br>        this.code = code;<br>        this.message = message;<br>        this.description = description;<br>    }<br>    public String getCode() {<br>        return code;<br>    }<br>    public void setCode(String code) {<br>        this.code = code;<br>    }<br>    public String getMessage() {<br>        return message;<br>    }<br>    public void setMessage(String message) {<br>        this.message = message;<br>    }<br>    public String getDescription() {<br>        return ObjectUtils.isEmpty(description) ? message : description;<br>    }<br>    public void setDescription(String description) {<br>        this.description = description;<br>    }<br>}</pre><pre>public class ResponseVO&lt;T&gt; {<br>    private String status;<br>    private String result;<br>    private ResponseErrorVo error;<br>    private T data;<br>    public String getResult() {<br>        return result;<br>    }<br>    public void setResult(String result) {<br>        this.result = result;<br>    }<br>    public T getData() {<br>        return data;<br>    }<br>    public ResponseErrorVo getError() {<br>        return error;<br>    }<br>    public void setError(ResponseErrorVo error) {<br>        this.error = error;<br>    }<br><br>    public String getStatus() {<br>        return status;<br>    }<br>    public void setStatus(String status) {<br>        this.status = status;<br>    }<br>    public void setData(T data) {<br>        this.data = data;<br>    }<br>}</pre><pre>public class ResponseVOBuilder&lt;T&gt; {<br>    private final ResponseVO&lt;T&gt; responseVO = new ResponseVO&lt;&gt;();<br>    private ResponseVOBuilder&lt;T&gt; result(String result) {<br>        responseVO.setResult(result);<br>        return this;<br>    }<br>    private ResponseVOBuilder&lt;T&gt; status(String status) {<br>        responseVO.setStatus(status);<br>        return this;<br>    }<br>    public ResponseVOBuilder&lt;T&gt; success() {<br>        return new ResponseVOBuilder&lt;T&gt;().result(&quot;Succeed&quot;).status(&quot;200&quot;);<br>    }<br>    public ResponseVOBuilder&lt;T&gt; fail() {<br>        return new ResponseVOBuilder&lt;T&gt;().result(&quot;Failed&quot;).status(&quot;500&quot;);<br>    }<br>    public ResponseVOBuilder&lt;T&gt; error(ResponseErrorVo error) {<br>        responseVO.setError(error);<br>        responseVO.setResult(&quot;Failed&quot;);<br>        responseVO.setStatus(&quot;500&quot;);<br>        return this;<br>    }<br>    public ResponseVOBuilder&lt;T&gt; addData(final T body) {<br>        responseVO.setData(body);<br>        responseVO.setResult(&quot;Succeeded&quot;);<br>        responseVO.setStatus(&quot;200&quot;);<br>        return this;<br>    }<br>    public ResponseVO&lt;T&gt; build() {<br>        return responseVO;<br>    }<br>}</pre><p>Sample success response</p><pre>curl --location &#39;localhost:8080/api/users/5&#39;</pre><pre>{<br>    &quot;status&quot;: &quot;200&quot;,<br>    &quot;result&quot;: &quot;Succeeded&quot;,<br>    &quot;data&quot;: {<br>        &quot;id&quot;: &quot;1&quot;,<br>        &quot;username&quot;: &quot;admin&quot;,<br>        &quot;status&quot;: &quot;ACTIVE&quot;<br>    }<br>}</pre><p>Sample error response: no record exist with id 50, no URL found and error on String convert to number.</p><pre>curl --location &#39;localhost:8080/api/users/50&#39;</pre><pre>{<br>    &quot;status&quot;: &quot;500&quot;,<br>    &quot;result&quot;: &quot;Failed&quot;,<br>    &quot;error&quot;: {<br>        &quot;code&quot;: &quot;E0002&quot;,<br>        &quot;message&quot;: &quot;Record not found.&quot;,<br>        &quot;description&quot;: &quot;Record not found.&quot;<br>    }<br>}</pre><pre>curl --location &#39;localhost:8080/api/test&#39;</pre><pre>{<br>    &quot;status&quot;: &quot;404&quot;,<br>    &quot;result&quot;: &quot;Failed&quot;,<br>    &quot;error&quot;: {<br>        &quot;code&quot;: &quot;E0404&quot;,<br>        &quot;description&quot;: &quot;Not Found&quot;,<br>        &quot;message&quot;: &quot;Not Found&quot;<br>    }<br>}</pre><pre>curl --location &#39;localhost:8080/api/users/5s&#39;</pre><pre>{<br>    &quot;status&quot;: &quot;500&quot;,<br>    &quot;result&quot;: &quot;Failed&quot;,<br>    &quot;error&quot;: {<br>        &quot;code&quot;: &quot;E0001&quot;,<br>        &quot;message&quot;: &quot;General exception error.&quot;,<br>        &quot;description&quot;: &quot;For input string: \&quot;5s\&quot;&quot;<br>    }<br>}</pre><h3>Default Class for Request and Response with pagination</h3><p>In this I’ll create two classes that can build response with success and fail and contain page request.</p><pre>public class RequestPageableVO {<br>    public RequestPageableVO() {<br>    }<br>    public RequestPageableVO(Integer page, Integer rpp) {<br>        this.page = page;<br>        this.rpp = rpp;<br>    }<br>    public static final Integer DEFAULT_PAGE = NumberUtils.INTEGER_ONE;<br>    public static final Integer DEFAULT_RPP = Integer.valueOf(10);<br>    public Integer getPage() {<br>        return page;<br>    }<br>    public void setPage(Integer page) {<br>        this.page = page;<br>    }<br>    public Integer getRpp() {<br>        return rpp;<br>    }<br>    public void setRpp(Integer rpp) {<br>        this.rpp = rpp;<br>    }<br>    private Integer page = DEFAULT_PAGE;<br>    private Integer rpp = DEFAULT_RPP;<br>    public int getOffset() {<br>        return (getPage() - 1) * getRpp();<br>    }<br>    public final int getNumberOfRows() {<br>        return getRpp();<br>    }<br>}</pre><pre>public class ResponsePageableVO&lt;T&gt; {<br>    protected static final long DEFAULT_RECORDS = NumberUtils.LONG_ZERO;<br>    private Long records = DEFAULT_RECORDS;<br>    private List&lt;T&gt; items;<br>    private Integer pages;<br>    private Integer page;<br>    public List&lt;T&gt; getItems() {<br>        return items;<br>    }<br>    public void setItems(List&lt;T&gt; items) {<br>        this.items = items;<br>    }<br>    public Integer getPages() {<br>        return pages;<br>    }<br>    public void setPages(Integer pages) {<br>        this.pages = pages;<br>    }<br>    public Integer getPage() {<br>        return page;<br>    }<br>    public void setPage(Integer page) {<br>        this.page = page;<br>    }<br>    public Integer getRecordFrom() {<br>        return recordFrom;<br>    }<br>    public void setRecordFrom(Integer recordFrom) {<br>        this.recordFrom = recordFrom;<br>    }<br>    public Integer getRecordTo() {<br>        return recordTo;<br>    }<br>    public void setRecordTo(Integer recordTo) {<br>        this.recordTo = recordTo;<br>    }<br>    @JsonProperty(&quot;record_from&quot;)<br>    private Integer recordFrom;<br>    @JsonProperty(&quot;record_to&quot;)<br>    private Integer recordTo;<br>    public Long getRecords() {<br>        return records;<br>    }<br>    public void setRecords(Long records) {<br>        this.records = records;<br>    }<br>    public ResponsePageableVO(int records, List&lt;T&gt; items, RequestPageableVO pageable) {<br>        this((long) records, items, pageable);<br>    }<br>    public ResponsePageableVO(long records, List&lt;T&gt; items, RequestPageableVO pageable) {<br>        this.records = records;<br>        this.items = items;<br>        this.pages = (int) Math.ceil((double) this.records / pageable.getRpp());<br>        this.page = pageable.getPage();<br>        if (ObjectUtils.isEmpty(this.items)) {<br>            this.recordFrom = 1;<br>            this.recordTo = Math.toIntExact(this.records);<br>        } else {<br>            this.recordFrom = (this.page * pageable.getRpp()) - pageable.getRpp() + 1;<br>            this.recordTo = (int) (this.page.equals(this.pages) ? this.records : this.page * pageable.getRpp());<br>        }<br>    }<br>}</pre><p>Sample API data response with page(default value page=1 and rpp=10)</p><p>*RPP = Row Per Page</p><pre>curl --location &#39;localhost:8080/api/users</pre><pre>{<br>    &quot;status&quot;: &quot;200&quot;,<br>    &quot;result&quot;: &quot;Succeeded&quot;,<br>    &quot;data&quot;: {<br>        &quot;records&quot;: 9,<br>        &quot;items&quot;: [<br>            {<br>                &quot;id&quot;: &quot;3&quot;,<br>                &quot;username&quot;: &quot;admin&quot;,<br>                &quot;status&quot;: &quot;ACTIVE&quot;<br>            },<br>            {<br>                &quot;id&quot;: &quot;4&quot;,<br>                &quot;username&quot;: &quot;peter&quot;,<br>                &quot;status&quot;: &quot;ACTIVE&quot;<br>            },<br>            {<br>                &quot;id&quot;: &quot;5&quot;,<br>                &quot;username&quot;: &quot;jonh&quot;,<br>                &quot;status&quot;: &quot;ACTIVE&quot;<br>            },<br>            {<br>                &quot;id&quot;: &quot;6&quot;,<br>                &quot;username&quot;: &quot;janu&quot;,<br>                &quot;status&quot;: &quot;ACTIVE&quot;<br>            },<br>            {<br>                &quot;id&quot;: &quot;7&quot;,<br>                &quot;username&quot;: &quot;bopha&quot;,<br>                &quot;status&quot;: &quot;ACTIVE&quot;<br>            },<br>            {<br>                &quot;id&quot;: &quot;8&quot;,<br>                &quot;username&quot;: &quot;kolap&quot;,<br>                &quot;status&quot;: &quot;ACTIVE&quot;<br>            },<br>            {<br>                &quot;id&quot;: &quot;9&quot;,<br>                &quot;username&quot;: &quot;jat&quot;,<br>                &quot;status&quot;: &quot;ACTIVE&quot;<br>            },<br>            {<br>                &quot;id&quot;: &quot;10&quot;,<br>                &quot;username&quot;: &quot;fank&quot;,<br>                &quot;status&quot;: &quot;ACTIVE&quot;<br>            },<br>            {<br>                &quot;id&quot;: &quot;11&quot;,<br>                &quot;username&quot;: &quot;yuseph&quot;,<br>                &quot;status&quot;: &quot;ACTIVE&quot;<br>            }<br>        ],<br>        &quot;pages&quot;: 1,<br>        &quot;page&quot;: 1,<br>        &quot;record_from&quot;: 1,<br>        &quot;record_to&quot;: 9<br>    }<br>}</pre><pre>curl --location &#39;localhost:8080/api/users?rpp=5&amp;page=2&#39;</pre><pre>{<br>    &quot;status&quot;: &quot;200&quot;,<br>    &quot;result&quot;: &quot;Succeeded&quot;,<br>    &quot;data&quot;: {<br>        &quot;records&quot;: 9,<br>        &quot;items&quot;: [<br>            {<br>                &quot;id&quot;: &quot;8&quot;,<br>                &quot;username&quot;: &quot;kolap&quot;,<br>                &quot;status&quot;: &quot;ACTIVE&quot;<br>            },<br>            {<br>                &quot;id&quot;: &quot;9&quot;,<br>                &quot;username&quot;: &quot;jat&quot;,<br>                &quot;status&quot;: &quot;ACTIVE&quot;<br>            },<br>            {<br>                &quot;id&quot;: &quot;10&quot;,<br>                &quot;username&quot;: &quot;fank&quot;,<br>                &quot;status&quot;: &quot;ACTIVE&quot;<br>            },<br>            {<br>                &quot;id&quot;: &quot;11&quot;,<br>                &quot;username&quot;: &quot;yuseph&quot;,<br>                &quot;status&quot;: &quot;ACTIVE&quot;<br>            }<br>        ],<br>        &quot;pages&quot;: 2,<br>        &quot;page&quot;: 2,<br>        &quot;record_from&quot;: 6,<br>        &quot;record_to&quot;: 9<br>    }<br>}</pre><h3>From controller of these same APIs:</h3><pre>@RestController<br>@RequestMapping(&quot;api/users&quot;)<br>@AllArgsConstructor<br>public class UserController {<br>    private final UserService service;<br><br>    @GetMapping(&quot;{id}&quot;)<br>    public ResponseVO&lt;UserResponseVo&gt; getUserById(@PathVariable String id) {<br>        UserDto user = this.service.findById(id);<br>        return new ResponseVOBuilder&lt;UserResponseVo&gt;().addData(UserMapper.INSTANCE.dtoToVo(user)).build();<br>    }<br><br>    @GetMapping<br>    public ResponseVO&lt;ResponsePageableVO&lt;UserResponseVo&gt;&gt; getUsers(RequestPageableVO request) {<br>        Page&lt;UserDto&gt; page = this.service.findByUsers(request);<br>        List&lt;UserResponseVo&gt; users = UserMapper.INSTANCE.dtoToVoList(page.getContent());<br>        ResponsePageableVO&lt;UserResponseVo&gt; responseVo = new ResponsePageableVO&lt;&gt;(page.getTotalElements(), users, request);<br>        return new ResponseVOBuilder&lt;ResponsePageableVO&lt;UserResponseVo&gt;&gt;().addData(responseVo).build();<br>    }<br><br>    @PostMapping<br>    public ResponseVO&lt;UserResponseVo&gt; save(@RequestBody UserRequestVo vo) {<br>        UserDto dto = UserMapper.INSTANCE.voToDto(vo);<br>        this.service.save(dto);<br>        UserResponseVo responseVo = UserMapper.INSTANCE.dtoToVo(dto);<br>        return new ResponseVOBuilder&lt;UserResponseVo&gt;().addData(responseVo).build();<br>    }<br><br>}</pre><h3>Error handling:</h3><p>To handle all error from API I created two classes below:</p><pre>@RestControllerAdvice<br>@Slf4j<br>public class RestExceptionHandlerAdvice {<br><br>    @SneakyThrows<br>    @ExceptionHandler(Exception.class)<br>    public ResponseEntity&lt;ResponseVO&gt; responseException(Exception ex) {<br>        log.error(&quot;Exception {}&quot;, ex.getMessage(), ex);<br>        return new ResponseEntity&lt;&gt;(new ResponseVOBuilder&lt;&gt;().fail().error(new ResponseErrorVo(BizErrorCode.E0001.getValue(), BizErrorCode.E0001.getDescription(), ex.getLocalizedMessage())).build(), HttpStatus.INTERNAL_SERVER_ERROR);<br>    }<br><br>    @ExceptionHandler(BizException.class)<br>    public ResponseEntity&lt;ResponseVO&gt; responseBizException(BizException ex) {<br>        log.error(&quot;BizException {}&quot;, ex.getMessage(), ex);<br>        return new ResponseEntity&lt;&gt;(new ResponseVOBuilder&lt;&gt;().fail().error(new ResponseErrorVo(ex.getError().getValue(), ex.getError().getDescription())).build(), HttpStatus.INTERNAL_SERVER_ERROR);<br>    }<br>}</pre><pre>@Configuration<br>@Slf4j<br>public class CustomErrorAttributes extends DefaultErrorAttributes {<br><br>    @Override<br>    public Map&lt;String, Object&gt; getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {<br>        Map&lt;String, Object&gt; map = super.getErrorAttributes(webRequest, options);<br>        int status = (int) map.get(&quot;status&quot;);<br>        String message = (String) map.get(&quot;error&quot;);<br>        Map&lt;String, Object&gt; response = new HashMap&lt;&gt;();<br>        Map&lt;String, Object&gt; error = new HashMap&lt;&gt;();<br>        error.putIfAbsent(&quot;code&quot;, String.format(&quot;E0%s&quot;, status));<br>        error.putIfAbsent(&quot;message&quot;, message);<br>        error.putIfAbsent(&quot;description&quot;, message);<br>        response.putIfAbsent(&quot;status&quot;, String.valueOf(status));<br>        response.putIfAbsent(&quot;result&quot;, &quot;Failed&quot;);<br>        response.putIfAbsent(&quot;error&quot;, error);<br>        response.putIfAbsent(&quot;data&quot;, null);<br>        return response;<br>    }<br>}</pre><p>Remove null value on ObjectMapper:</p><pre>@Configuration<br>public class AppConfig {<br>    @Bean<br>    ObjectMapper mapper() {<br>        return new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);<br>    }<br>}</pre><p><a href="https://github.com/phsophea101/poc-spring/tree/Standard-API-Request-Response">GitHub - phsophea101/poc-spring at Standard-API-Request-Response</a></p><p>To summarize; In this article, I tried to explain how to create default and standard request and response for API. You can access the source code via the github link above.</p><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Visit </em><a href="https://phsophea101.github.io/"><strong><em>p</em></strong><em>hsophea101.github.io</em></a><em> to find out more about how we are democratizing free programming education around the world.</em></li><li>If you like my work and would like to buy me a coffee please go this <a href="http://buymeacoffee.com/phsophea101"><em>buymeacoffee link</em></a>. Thank you :)</li></ul><p>Good luck!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3a7cf7f4422" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Data Evolution with Change Data Capture in Spring Boot and Spring Data JPA]]></title>
            <link>https://phsophea101.medium.com/change-data-capture-or-audit-data-change-with-spring-boot-and-spring-data-jpa-67569e3d5122?source=rss-abe9dc254536------2</link>
            <guid isPermaLink="false">https://medium.com/p/67569e3d5122</guid>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[jpa]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Sophea PHOS]]></dc:creator>
            <pubDate>Wed, 27 Dec 2023 08:49:33 GMT</pubDate>
            <atom:updated>2024-01-04T07:59:36.225Z</atom:updated>
            <content:encoded><![CDATA[<p>In my previous article <a href="https://phsophea101.medium.com/change-data-capture-or-audit-data-change-with-spring-boot-and-mongodb-f5dfd34e68ef">Change Data Capture or audit data change with Spring boot and mongoDB</a> and this article is not too much different just focus on relational database instead of noSQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*98ZmMIUmr3YHXtaDKZ3v9Q.png" /></figure><p>For Hibernate or JPA we need to extens EmptyInterceptor and @Override some function to get data before or after save change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xFQyxs76g2svtuyr3H0qKA.png" /><figcaption>This is just a snapshot of class extends from EmptyInterceptor</figcaption></figure><ol><li>onSave: is Override function to get data on save record and work only when new record only.<br>org.hibernate.Interceptor Called before an object is saved. The interceptor may modify the state, which will be used for the SQL INSERT and propagated to the persistent object</li></ol><pre>@Override<br>public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {<br>    try {<br>        this.onSaveAction(entity, ActionStatus.CREATED);<br>    } catch (Exception e) {<br>        log.error(&quot;Audit onSave error occurred {}&quot;, e.getMessage(), e);<br>    }<br>    return super.onSave(entity, id, state, propertyNames, types);<br>}</pre><p>2. onDelete: is Override function to get data on delete hard record only.Called before an object is deleted. It is not recommended that the interceptor modify the state.</p><pre>@Override<br>public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {<br>    try {<br>        this.onSaveAction(entity, ActionStatus.DELETED);<br>    } catch (Exception e) {<br>        log.error(&quot;Audit onDelete error occurred {}&quot;, e.getMessage(), e);<br>    } finally {<br>        super.onDelete(entity, id, state, propertyNames, types);<br>    }<br>}</pre><p>3. onSaveAction: a function to save current thread or state for save or delete record</p><pre>private void onSaveAction(Object entity, ActionStatus action) {<br>    boolean audited = HibernateAuditTrailService.isAudited(entity.getClass());<br>    if (audited) {<br>        AuditTrailDto audit = new AuditTrailDto();<br>        String tableName = HibernateAuditTrailService.getTableName(entity.getClass());<br>        audit.setTableName(tableName);<br>        audit.setAction(String.valueOf(action));<br>        String key = HibernateAuditTrailService.getIdentityKey(entity);<br>        InheritableContextHolder.setObject(key, audit);<br>    }<br>}</pre><p>4. postFlush: is Override function work or fire after trasantional that actually ends in execution of the SQL statements required. we override this because on save or delete their is no current data.Called after a flush that actually ends in execution of the SQL statements required to synchronize in-memory state with the database.</p><pre>@Override<br>public void postFlush(Iterator entities) {<br>    try {<br>        while (entities.hasNext()) {<br>            this.postData(entities.next());<br>        }<br>    } catch (Exception e) {<br>        log.error(&quot;Audit postFlush error occurred {}&quot;, e.getMessage(), e);<br>    }<br>    super.postFlush(entities);<br>}</pre><p>5. postData: a function to produce data for save or delete…</p><pre>private void postData(Object object) {<br>    if (HibernateAuditTrailService.isAudited(object.getClass())) {<br>        String key = HibernateAuditTrailService.getIdentityKey(object);<br>        AuditTrailDto table = InheritableContextHolder.getObject(key, AuditTrailDto.class);<br>        if (ObjectUtils.isNotEmpty(table)) {<br>            String action = table.getAction();<br>            table = HibernateAuditTrailService.getCreatedData(object);<br>            if (ObjectUtils.isNotEmpty(action))<br>                table.setAction(action);<br>            if (ObjectUtils.isNotEmpty(table.getFields())) {<br>                HibernateAuditTrailService.generateLog(table);<br>                InheritableContextHolder.remove(key);<br>            }<br>        }<br>    }<br>}</pre><p>6. onFlushDirty: a Override function work or fire on something change,Called when an object is detected to be dirty, during a flush. The interceptor may modify the detected currentState, which will be propagated to both the database and the persistent object. Note that not all flushes end in actual synchronization with the database, in which case the new currentState will be propagated to the object, but not necessarily (immediately) to the database. It is strongly recommended that the interceptor not modify the previousState.</p><pre>@Override<br>public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {<br>    try {<br>        boolean audited = HibernateAuditTrailService.isAudited(entity.getClass());<br>        if (audited) {<br>            AuditTrailDto audit = HibernateAuditTrailService.makeAuditData(entity, propertyNames, currentState, previousState);<br>            if (ObjectUtils.isNotEmpty(audit.getFields())) {<br>                if (ObjectUtils.isEmpty(audit.getAction()))<br>                    audit.setAction(String.valueOf(ActionStatus.MODIFIED));<br>                HibernateAuditTrailService.generateLog(audit);<br>            }<br>        }<br>    } catch (Exception e) {<br>        log.error(&quot;Audit onFlushDirty error occurred {}&quot;, e.getMessage(), e);<br>    }<br>    return super.onFlushDirty(entity, id, currentState, previousState, propertyNames, types);<br>}</pre><p><strong>To register the extended class to bean interceptor</strong></p><pre>@Component<br>@ConditionalOnClass(value = {EntityManagerFactory.class, SessionFactory.class})<br>public class BeanHibernateAuditInterceptor implements HibernatePropertiesCustomizer {<br>    private static final String HIBERNATE_SESSION_FACTORY_INTERCEPTOR = &quot;hibernate.session_factory.interceptor&quot;;<br><br>    @Override<br>    public void customize(Map&lt;String, Object&gt; hibernateProperties) {<br>        hibernateProperties.put(HIBERNATE_SESSION_FACTORY_INTERCEPTOR, new HibernateAuditInterceptor());<br>    }<br>}</pre><p>To test this I used a same simple api to create and update and the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*bIbEAWj0-BEchm-DR6gCjw.png" /><figcaption>Sample Audit log for create record</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*uVajb97XeYTJrJcqChToBg.png" /><figcaption>Sample Audit log for update record</figcaption></figure><p><a href="https://github.com/phsophea101/poc-spring/tree/poc-hibernate-audit">GitHub - phsophea101/poc-spring at poc-hibernate-audit</a></p><p>To summarize; In this article, I tried to explain how to save the answers to questions of not only <strong>Who? </strong>and <strong>When? </strong>via Spring Data JPA or Hibernate but you can get all Change Data Capture(CDC) of each record and . You can access the source code via the github link above.</p><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Visit </em><a href="https://phsophea101.github.io/"><strong><em>p</em></strong><em>hsophea101.github.io</em></a><em> to find out more about how we are democratizing free programming education around the world.</em></li><li>If you like my work and would like to buy me a coffee please go this <a href="http://buymeacoffee.com/phsophea101"><em>buymeacoffee link</em></a>. Thank you :)</li></ul><p>Good luck!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67569e3d5122" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Deep Dive into Change Data Capture and Auditing with MongoDB in Spring Boot.]]></title>
            <link>https://phsophea101.medium.com/change-data-capture-or-audit-data-change-with-spring-boot-and-mongodb-f5dfd34e68ef?source=rss-abe9dc254536------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5dfd34e68ef</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Sophea PHOS]]></dc:creator>
            <pubDate>Wed, 27 Dec 2023 05:58:09 GMT</pubDate>
            <atom:updated>2024-01-04T07:58:58.652Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article not just use @EnableAuditing. and get when or who create and update but I will show you all about how to change data capture between old and new data change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*yx06kClk2KM1gnA_I2qlpg.png" /></figure><h3>First I want you to know what’s Change data capture and why we need this</h3><p>Change data capture is short know as CDC, A process of tracking the changes in the data of a particular Database and logging those changes.</p><p>We need CDC for audit purposes to track. the Audit might help us to understand the changes like who, when, and what were made change on the specific record. we can use this log to recover or triage the flow of edits made to the data.</p><p>There are several ways to achieve CDC. like in the application layer which is writing the records or capturing the changes directly on the database layer like <a href="https://debezium.io/">Debezium</a></p><p>We are taking the approach to track changes made to the documents directly on the database. with the help of the change stream provided by the Mongo DB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VV1OTe1p-d9bSgoe95ppYw.png" /></figure><p>Assume we have an application that does the CRUD operations which is written in spring boot.</p><p>Or in existing spring boot application which writes data, You can capture Mongo Events before saving . below example snippet i am updating the trace id to track horizontal and vertical changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*nxwaJ8PpG1Bm86Kpfmncpw.png" /><figcaption>This is just a snapshot of class @EventListener</figcaption></figure><p>To capture data before make change for update or delete:</p><pre>@EventListener<br>public void onAfterConvert(AfterConvertEvent&lt;T&gt; event) {<br>    try {<br>        Document source = event.getDocument();<br>        if (Boolean.TRUE.equals(MongoAuditTrailService.isAudited(event.getSource().getClass())) &amp;&amp; Objects.nonNull(source)) {<br>            String identityKey = MongoAuditTrailService.getIdentityKey(event.getSource());<br>            InheritableContextHolder.setObject(identityKey, source);<br>        }<br>    } catch (Exception e) {<br>        log.error(ERROR_MESSAGE, e.getMessage(), e);<br>    }<br>}</pre><p>Note: class MongoAuditTrailService and InheritableContextHolder will provide or detail later…</p><p>To get data after save change:</p><pre>@EventListener<br>public void onAfterSave(AfterSaveEvent&lt;T&gt; event) {<br>    try {<br>        Document newSource = event.getDocument();<br>        if (Objects.nonNull(newSource)) {<br>            String identityKey = MongoAuditTrailService.getIdentityKey(event.getSource());<br>            Document oldSource = InheritableContextHolder.getObject(identityKey, Document.class);<br>            doAudit(oldSource, event);<br>            InheritableContextHolder.remove(identityKey);<br>        }<br>    } catch (Exception e) {<br>        log.error(ERROR_MESSAGE, e.getMessage(), e);<br>    }<br>}</pre><p>doAudit function to make logic and check what ever data has been change or not in each fields</p><pre>private void doAudit(Document oldSource, AfterSaveEvent&lt;T&gt; event) {<br>    Document newSource = event.getDocument();<br>    T source = event.getSource();<br>    try {<br>        if (Boolean.TRUE.equals(MongoAuditTrailService.isAudited(source.getClass())) &amp;&amp; Objects.nonNull(newSource)) {<br>            AuditTrailDto auditTableDto = MongoAuditTrailService.getCreatedData(source);<br>            if (&quot;NA&quot;.equalsIgnoreCase(auditTableDto.getTableName()))<br>                auditTableDto.setTableName(event.getCollectionName());<br>            if (Objects.nonNull(oldSource)) {<br>                List&lt;AuditTrailFieldDto&gt; changedFields = MongoAuditTrailService.getChangedFields(source.getClass(), oldSource, newSource);<br>                if (ObjectUtils.isNotEmpty(changedFields)) {<br>                    auditTableDto.setFields(changedFields);<br>                    if (!String.valueOf(ActionStatus.DELETED).equalsIgnoreCase(auditTableDto.getAction()))<br>                        auditTableDto.setAction(String.valueOf(ActionStatus.MODIFIED));<br>                    MongoAuditTrailService.generateLog(auditTableDto);<br>                }<br>            } else {<br>                MongoAuditTrailService.generateLog(auditTableDto);<br>            }<br>        }<br>    } catch (Exception e) {<br>        log.error(ERROR_MESSAGE, e.getMessage(), e);<br>    }<br>}</pre><p>Here is my DTO classes:</p><pre>@Data<br>@ToString<br>@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)<br>public class AuditTrailDto {<br>    private String tableName;<br>    private String action;<br>    private List&lt;AuditTrailFieldDto&gt; fields;<br>    private List&lt;AuditTrailPrimaryKeyDto&gt; primaryKeys;<br>}</pre><pre>@Data<br>@AllArgsConstructor<br>@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)<br>public class AuditTrailFieldDto {<br>    private String fieldName;<br>    private String currentValue;<br>    private String previousValue;<br>}</pre><pre>@Data<br>@AllArgsConstructor<br>@NoArgsConstructor<br>@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)<br>public class AuditTrailPrimaryKeyDto {<br>    private String fieldName;<br>    private String fieldValue;<br>}</pre><pre>@Getter<br>@Setter<br>@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)<br>public class AuditTrailTableDto {<br>    private String traceId;<br>    private String tableName;<br>    private List&lt;AuditTrailPrimaryKeyDto&gt; primaryKeys;<br>}</pre><p>And here is my MongoAuditTrailService class and I will explain each function detail:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eJhBXjGJ-ZCknJ0q1Wa9jg.png" /><figcaption>This is just a snapshot of class</figcaption></figure><ol><li>getTableName: a static function to get collection name of each entity.</li></ol><pre>public static String getTableName(Class&lt;?&gt; clazz) {<br>    Optional&lt;org.springframework.data.mongodb.core.mapping.Document&gt; optionalDocument = Optional.ofNullable(clazz.getAnnotation(org.springframework.data.mongodb.core.mapping.Document.class));<br>    return optionalDocument.map(document -&gt; ObjectUtils.isNotEmpty(document.collection()) ? document.collection() : document.value()).orElse(&quot;NA&quot;).replace(&quot;`&quot;, &quot;&quot;);<br>}</pre><p>2. generateLog: a static function to generate log and you also can doing produce a messaging(kafka) or save in database.</p><pre>@SneakyThrows<br>public static void generateLog(AuditTrailDto dto) {<br>    log.info(&quot;here is data log\n {}&quot;, new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(dto));<br>}</pre><p>3. isAudited: a static method to check the entity or collection need to capture or make audit or not.</p><pre>public static boolean isAudited(Class&lt;?&gt; clazz) {<br>    String tableName = getTableName(clazz);<br>    if (TABLE_IGNORES.contains(tableName))<br>        return Boolean.FALSE;<br>    String[] tables = {&quot;*&quot;};<br>    for (String table : tables) {<br>        if (tableName.equalsIgnoreCase(table) || ALL.equals(table))<br>            return Boolean.TRUE;<br>    }<br>    return Boolean.FALSE;<br>}</pre><p>4. getIdentityKey: a static function to get the identity of each request.</p><pre>public static String getIdentityKey(Object object) {<br>    return String.format(&quot;%s_(%s)&quot;, getTableName(object.getClass()).toUpperCase(), org.springframework.util.ObjectUtils.getIdentityHexString(object));<br>}</pre><p>5. isModified: a static function to each field has been modified or not.</p><pre>static boolean isModified(Object currentValue, Object previousValue) {<br>    return Objects.isNull(currentValue) ? !Objects.isNull(previousValue) : ClassUtil.isJavaLangType(previousValue) &amp;&amp; !currentValue.equals(previousValue);<br>}</pre><p>6. getPrimaryKeyValues: a static function to get list of primary key dto of each collection or entity.</p><pre>public static List&lt;AuditTrailPrimaryKeyDto&gt; getPrimaryKeyValues(Object object) {<br>    List&lt;Field&gt; primaryKeyFields = getPrimaryKeyFields(object);<br>    List&lt;AuditTrailPrimaryKeyDto&gt; primaryKeyValues = new ArrayList&lt;&gt;();<br>    for (Object propNameObject : new BeanMap(object).keySet()) {<br>        String fieldName = (String) propNameObject;<br>        Object value = new BeanMap(object).get(fieldName);<br>        primaryKeyFields.forEach(item -&gt; {<br>            if (item.getName().equalsIgnoreCase(fieldName))<br>                primaryKeyValues.add(new AuditTrailPrimaryKeyDto(caseFieldName(fieldName), String.valueOf(value)));<br>        });<br>    }<br>    return primaryKeyValues;<br>}</pre><p>7. getPrimaryKeyFields: a static function to get list of primary key of each collection or entity.</p><pre>public static List&lt;Field&gt; getPrimaryKeyFields(Object entity) {<br>    List&lt;Field&gt; primaryFields = new ArrayList&lt;&gt;();<br>    Class&lt;?&gt; current = entity.getClass();<br>    while (current != null &amp;&amp; current != Object.class) {<br>        List&lt;Field&gt; ids = Arrays.stream(current.getDeclaredFields()).filter(field -&gt; Objects.nonNull(field.getAnnotation(org.springframework.data.annotation.Id.class))).collect(Collectors.toList());<br>        primaryFields.addAll(ids);<br>        current = current.getSuperclass();<br>    }<br>    return primaryFields;<br>}</pre><p>8. getAllFields: a static function to get all fields from collection or entity.</p><pre>public static List&lt;Field&gt; getAllFields(Class&lt;?&gt; clazz) {<br>    Set&lt;Field&gt; fields = new HashSet&lt;&gt;();<br>    Class&lt;?&gt; current = clazz;<br>    while (ObjectUtils.isNotEmpty(current) &amp;&amp; !(&quot;java.lang.Object&quot;.equalsIgnoreCase(current.getName()))) {<br>        List&lt;Field&gt; auditFields = Arrays.stream(current.getDeclaredFields()).collect(Collectors.toList());<br>        if (!auditFields.isEmpty()) {<br>            fields.addAll(auditFields);<br>        } else {<br>            fields.addAll(Arrays.asList(current.getDeclaredFields()));<br>        }<br>        current = current.getSuperclass();<br>    }<br>    return new ArrayList&lt;&gt;(fields);<br>}</pre><p>9. getChangedFields: a static function to get all fields changed after save change.</p><pre>public static List&lt;AuditTrailFieldDto&gt; getChangedFields(Class&lt;?&gt; entity, Document oldSource, Document newSource) {<br>    List&lt;AuditTrailFieldDto&gt; changedFields = new ArrayList&lt;&gt;();<br>    List&lt;Field&gt; fields = getAllFields(entity);<br>    for (Field field : fields) {<br>        org.springframework.data.mongodb.core.mapping.Field col = field.getAnnotation(org.springframework.data.mongodb.core.mapping.Field.class);<br>        String fieldName = Objects.nonNull(col) &amp;&amp; StringUtils.isNoneBlank(col.value()) ? col.value() : caseFieldName(field.getName());<br>        if (!FIELD_IGNORES.contains(fieldName)) {<br>            if (Objects.nonNull(oldSource)) {<br>                Object oldValue = oldSource.get(fieldName);<br>                Object newValue = newSource.get(fieldName);<br>                boolean modified = isModified(newValue, oldValue);<br>                if (modified)<br>                    changedFields.add(new AuditTrailFieldDto(caseFieldName(fieldName), String.valueOf(newValue), String.valueOf(oldValue)));<br>            } else {<br>                Object newValue = newSource.get(fieldName);<br>                changedFields.add(new AuditTrailFieldDto(fieldName, String.valueOf(newValue), StringUtils.EMPTY));<br>            }<br>        }<br>    }<br>    return changedFields;<br>}</pre><p>10. caseFieldName: case to snake case</p><pre>private static String caseFieldName(String fieldName) {<br>    return StringUtil.camelCaseToSnakeCase(fieldName);<br>}</pre><p>11. isDeleted: a static function to check soft delete.</p><pre>public static boolean isDeleted(Object object) {<br>    List&lt;Field&gt; fields = getAllFields(object.getClass());<br>    for (Field field : fields) {<br>        String fieldName = field.getName();<br>        if (fieldName.equalsIgnoreCase(&quot;status&quot;) &amp;&amp; List.of(String.valueOf(ActionStatus.DELETED), &quot;DELETE&quot;).contains(String.valueOf(new BeanMap(object).get(fieldName)))) {<br>            return Boolean.TRUE;<br>        }<br>    }<br>    return Boolean.FALSE;<br>}</pre><p>12. getCreatedData: a static function to generate data of audit.</p><pre>public static AuditTrailDto getCreatedData(Object object) {<br>    AuditTrailDto table = new AuditTrailDto();<br>    List&lt;AuditTrailFieldDto&gt; fields = new ArrayList&lt;&gt;();<br>    List&lt;AuditTrailPrimaryKeyDto&gt; primaryKeyValues = getPrimaryKeyValues(object);<br>    List&lt;String&gt; primaryKeyFields = primaryKeyValues.stream().map(AuditTrailPrimaryKeyDto::getFieldName).collect(Collectors.toList());<br>    AtomicReference&lt;BeanMap&gt; map = new AtomicReference&lt;&gt;(new BeanMap(object));<br>    map.get().keySet().stream().map(String.class::cast).forEach(fieldName -&gt; {<br>        Object currentValue = map.get().get(fieldName);<br>        if (!FIELD_IGNORES.contains(fieldName) &amp;&amp; ObjectUtils.isNotEmpty(currentValue) &amp;&amp; ClassUtil.isJavaLangType(currentValue.getClass()) &amp;&amp; !primaryKeyFields.contains(caseFieldName(fieldName)))<br>            fields.add(new AuditTrailFieldDto(caseFieldName(fieldName), String.valueOf(currentValue), StringUtils.EMPTY));<br>    });<br>    table.setTableName(getTableName(object.getClass()));<br>    table.setFields(fields);<br>    table.setPrimaryKeys(primaryKeyValues);<br>    if (isDeleted(object))<br>        table.setAction(String.valueOf(ActionStatus.DELETED));<br>    else<br>        table.setAction(String.valueOf(ActionStatus.CREATED));<br>    return table;<br>}</pre><h3>InheritableContextHolder</h3><pre>public final class InheritableContextHolder {<br>    private static final InheritableThreadLocal&lt;Map&lt;String, Object&gt;&gt; THREAD_LOCAL = new InheritableThreadLocal() {<br>        @Override<br>        protected Map&lt;String, Object&gt; initialValue() {<br>            return new ConcurrentHashMap&lt;&gt;();<br>        }<br>    };<br><br>    private InheritableContextHolder() {<br>    }<br><br>    public static void setObject(final String key, final Object value) {<br>        if (StringUtils.isEmpty(key) || Objects.isNull(value)) {<br>            log.debug(&quot;Key {} or value {} is empty cannot put into inheritable thread local&quot;, key, value);<br>            return;<br>        }<br>        THREAD_LOCAL.get().put(key, value);<br>    }<br>    public static &lt;T&gt; T getObject(final String key, final Class&lt;T&gt; _class) {<br>        return ObjectUtils.cast(getObject(key), _class);<br>    }<br><br>    public static Object getObject(final String key) {<br>        return THREAD_LOCAL.get().get(key);<br>    }<br><br>    public static Object remove(final String key) {<br>        return THREAD_LOCAL.get().remove(key);<br>    }<br>}</pre><p>To test this I made a simple api to create and update and the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yiEkU5FZuDY4X-PXLptt5A.png" /><figcaption>Sample Audit log for create record</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0I7vJSpF8JS8zCmFEDmmTg.png" /><figcaption>Sample Audit log for update record</figcaption></figure><p><a href="https://github.com/phsophea101/poc-spring/tree/poc-mongodb-audit">GitHub - phsophea101/poc-spring at poc-mongodb-audit</a></p><p>To summarize; In this article, I tried to explain how to save the answers to questions of not only <strong>Who? </strong>and <strong>When? </strong>via Spring Data MongoDB but you can get all Change Data Capture(CDC) of each record and . You can access the source code via the github link above.</p><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Visit </em><a href="https://phsophea101.github.io/"><strong><em>p</em></strong><em>hsophea101.github.io</em></a><em> to find out more about how we are democratizing free programming education around the world.</em></li><li>If you like my work and would like to buy me a coffee please go this <a href="http://buymeacoffee.com/phsophea101"><em>buymeacoffee link</em></a>. Thank you :)</li></ul><p>Good luck!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5dfd34e68ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>