Friday, February 9, 2018

Implement a JPA attribute converter

Greetings!

Using JPA we can easily map our column values to Java variable and so forth. What if we want our column to have some value and mapped variable has another? One way to achieve this is to have a another method to convert the values.

JPA comes with a another handy way to fulfill this. That is AttributeConverter.
Only thing we want to do is to implement AttributeConverter and add our logic.

Here is an example using Enums.

Thymeleaf hidden field value

Greetings!

Thymeleaf gives us almost everything we need. But there are some cases that thymeleaf does not work properly.
When we have a hidden field and we want to assign it a value, strangely thymeleaf will ignore the value property.

Solution:
Use th:attr
th:attr="name='

<tr th:each="user, stat : ${users}">    <input type="hidden"           th:attr="name='userDtos[' + ${stat.index} + '].userId'"           th:value="${user.id}" />    <!--some other inputs-->    <td>        <input type="checkbox" th:field="*{userDtos[__${stat.index}__].active}" />    </td></tr>

Spring PathVariable with dots

Greetings!

Spring helps us in many ways. But in sometimes it do more than we want.
If we want to have dots like xx.yy.zz in our path Spring will remove last part probably thinking it as a file type.
xx.yy.zz will become xx.yy
@GetMapping(value = "/{myvar}")
public String someMethod(@PathVariable String myvar) {
    // myvar is xx.yy here    // do something with myvar    // return}

Solution:
Use regex to allow dots
@GetMapping(value = "/{myvar:.+}")
public String someMethod(@PathVariable String myvar) {
    // myvar is xx.yy.zz here    // do something with myvar    // return}

for more information check this stackoverflow answer.