Custom Source presence checking method name in MapStruct - option-type

is it posible to generate a custom "presence checking" method name, being a method of the property itself rather the owning object?
I know I can use hasProperty() methods to check for presence of a value...
https://mapstruct.org/documentation/stable/reference/html/#source-presence-check
but with Optional or JsonNullable (from OpenApi nonullable) that checking method is on the property itself, not on the owning object... :-(
I can map JsonNullable or Optional easyly 'using' or extending a simple custom Mapper
#Mapper
public class JsonNullableMapper {
public <T> T fromJsonNullable(final JsonNullable<T> jsonNullable) {
return jsonNullable.orElse(null);
}
public <T> JsonNullable<T> asJsonNullable(final T nullable) {
return nullable != null ? JsonNullable.of(nullable) : JsonNullable.undefined();
}
}
what I would like to achieve is something like this as "presence check":
if(source.getProperty().isPresent()) {
target.set(customMapper.map(source.getProperty()));
}
Any one found a solution for this?
Thanks and regards

I have managed to implement custom lombok extension which generates "presence checknig" methods.
Here is an example project. In short I added #PresenceChecker annotation and implemented Lombok Javac Annotation handler.
It's possible to use it together with other Lombok annotations:
#Getter
#Setter
public class User {
private String name;
}
#Getter
#Setter
#PresenceChecker
public class UserUpdateDto {
private String name;
}
//MapStruct Mapper interface declaration
#Mapper
public interface UserMapper {
void updateUser(UserUpdateDto dto, #MappingTarget User user);
}
Generated code:
public class User {
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
public class UserUpdateDto {
private boolean hasName;
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
this.hasName = true;
}
public boolean hasName() {
return this.hasName;
}
}
//MapStruct Mapper implementation
public class UserMapperImpl implements UserMapper {
#Override
public void updateUser(UserUpdateDto dto, User user) {
if ( dto == null ) {
return;
}
if ( dto.hasName() ) {
user.setName( dto.getName() );
}
}
}

The answer is unfortunately a straight no.
It is not possible in the current version of MapStruct (1.3.1final) and its not on the shortlist for 1.4.0. You could open up an issue on the git repo of MapStruct as feature request.

Related

Fix string contraints on JPA entity attribute

I am new in JPA,
I want to set only specific fix department names to attribute in entity as a fix string as constraints.I.e default values to attributes.
How to set it?
I think the best option is to use enumerated as indicated by Dinesh Dontha, try this:
Entity
#Entity
public class MyEntity implements Serializable(){
private MyEnum attribute;
}
Enum
public enum MyEnum {
NAME1("N1")
private String shortName;
private MyEnum(String shortName) {
this.shortName = shortName;
}
public String getShortName() {
return shortName;
}
public static MyEnum fromShortName(String shortName) {
switch (shortName) {
case "N1":
return NacionalidadEnum.NAME1;
default:
throw new IllegalArgumentException("ShortName [" + shortName
+ "] not supported.");
}
}
}
Converter
#Converter(autoApply = true)
public class MyEntityEnumConverter implements AttributeConverter<MyEnum, String> {
#Override
public String convertToDatabaseColumn(MyEnum myEnum) {
return myEnum.getShortName();
}
#Override
public MyEnum convertToEntityAttribute(String dbData) {
return MyEnum.fromShortName(dbData);
}
}

Is there a way to use #PreAuthorize in Getters? (Spring Boot)

I'm trying to use different objects for different user roles.
#Component
public class TestObject {
private String name;
private String secret;
#PreAuthorize("hasRole('ADMIN')")
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Is there a way to use #PreAuthorize like this?
You can use #PreAuthorize only in a Spring Managed Bean.
If you have to create multiple instances of an object, these instances are not managed by the application context.
If you mark a class with #Component, this becomes a Spring bean and can be injected and managed by the application context. Now, if you (not Spring) create a instance of this class, then this specific instance isn't a managed by Spring.
This means, that #PreAuthorize will not work in this instance.
One workaround is to use the SecurityContextHolder.
Something like this:
Utils.java
public class Utils {
public static boolean isAdmin() {
Collection<?extends GrantedAuthority> authorities = SecurityContextHolder.getContext()
.getAuthentication().getAuthorities();
for (GrantedAuthority authority: authorities) {
if (authority.getAuthority().equalsIgnoreCase("ADMIN")) {
return true;
}
}
return false;
}
}
TestObject.java
public class TestObject {
private String name;
private String secret;
public String getSecret() {
if(Utils.isAdmin())
return secret;
return null;
}
public void setSecret(String secret) {
this.secret = secret;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

How to use Java 8 Optional with Moxy and Jersey

Is it possible to use Jersey with Moxy to/from Json and Java 8 Optionals?
How to configure it?
You can declare following class:
public class OptionalAdapter<T> extends XmlAdapter<T, Optional<T>> {
#Override
public Optional<T> unmarshal(T value) throws Exception {
return Optional.ofNullable(value);
}
#Override
public T marshal(Optional<T> value) throws Exception {
return value.orElse(null);
}
}
And use like this:
#XmlRootElement
public class SampleRequest {
#XmlElement(type = Integer.class)
#XmlJavaTypeAdapter(value = OptionalAdapter.class)
private Optional<Integer> id;
#XmlElement(type = String.class)
#XmlJavaTypeAdapter(value = OptionalAdapter.class)
private Optional<String> text;
/* ... */
}
Or declare in package-info.java and remove #XmlJavaTypeAdapter from POJOs:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlJavaTypeAdapters({
#XmlJavaTypeAdapter(type = Optional.class, value = OptionalAdapter.class)
})
But here are some drawbacks:
Adapter above can only work with simple types like Integer, String, etc. that can be parsed by MOXY by default.
You have to specify #XmlElement(type = Integer.class) explicitly to tell the parser type are working with, otherwise null values would be passed to adapter's unmarshal method.
You miss the opportunity of using adapters for custom types, e.g. custom adapter for java.util.Date class based on some date format string. To overcome this you'll need to create adapter something like class OptionalDateAdapter<String> extends XmlAdapter<String, Optional<Date>>.
Also using Optional on field is not recommended, see this discussion for details.
Taking into account all the above, I would suggest just using Optional as return type for your POJOs:
#XmlRootElement
public class SampleRequest {
#XmlElement
private Integer id;
public Optional<Integer> getId() {
return Optional.ofNullable(id);
}
public void setId(Integer id) {
this.id = id;
}
}

No composite key property found for type error in Spring JPA2

I have an error in spring JPA
org.springframework.data.mapping.PropertyReferenceException: No property CompanyId found for type CompanyUserDetail!
#Embeddable
public class CompanyUserKey implements Serializable {
public CompanyUserKey() {
}
#Column(name = "company_id")
private UUID companyId;
#Column(name = "user_name")
private String userName;
public UUID getCompanyId() {
return companyId;
}
public void setCompanyId(UUID companyId) {
this.companyId = companyId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
#Entity
#Table(name = "company_user_detail")
public class CompanyUserDetail {
#EmbeddedId
CompanyUserKey companyUserkey;
public CompanyUserKey getCompanyUserkey() {
return companyUserkey;
}
public void setCompanyUserkey(CompanyUserKey companyUserkey) {
this.companyUserkey = companyUserkey;
}
}
I am trying to access below method Service layer
#Component
public interface CompanyUserRepository extends JpaRepository<CompanyUserDetail, CompanyUserKey> {
public List<CompanyUserDetail> findByCompanyId(UUID companyId);
}
How can I achieve this ?
Thanks
Since in java model your CompanyUserKey is a property in the CompanyUserDetail class, I believe you should use full path (companyUserkey.companyId) to reach companyId:
public List<CompanyUserDetail> findByCompanyUserkeyCompanyId(UUID companyId);
Also note that you have a naming inconsistency: field in CompanyUserDetail is named companyUserkey instead of companyUserKey.
Assuming you are not using spring-data-jpa's auto generated implementations, your method contents might look something like the following:
FROM CompanyUserDetail c WHERE c.companyUserKey.companyId = :companyId
Now simply provide that query to the EntityManager
entityManager.createQuery( queryString, CompanyUserDetail.class )
.setParameter( "companyId", companyId )
.getResultList();
The key points are:
Query uses a named bind parameter called :companyId (not the leading :).
Parameter values are bound in a secondary step using setParameter method variants.
createQuery uses a second argument to influence type safety so that the return value from getResultList is a List<CompanyUserDetail> just like you requested.
Looking at spring-data-jpa's implementation however, I suspect it could look like this:
public interface CustomerUserRepository
extends JpaRepository<CompanyUserDetail, CompanyUserKey> {
#Query("select c FROM CompanyUserDetail c WHERE c.companyUserKey.companyId = :companyId")
List<CompanyUserDetail> findByCompanyId(#Param("companyId") UUID companyId);
}

Mixed Entity and Business classes - Refactor help needed

I have a project where Entity Classes and Business classes are mixed up. The entity beans are part of the business and all is used through the whole project.
How can I best refactor those classes to separate those layers. I also want to keep the changes to the implementers as minimal as possible. Preferable no changes, otherwise hundreds of references need to be updated.
How should I rename the classes and work through this?
Example of mixed code:
// Mixed business-entity class
public final class Language {
private final Long id;
private final String code;
private final String description;
//Constructor
public Language() {
}
//getters and setters
public String getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
...
//Business is a part of this class
public static Language findByUser(User user) {
Language language;
...implementation to find user language...
return language;
}
....
}
// Implementing class
public class Messenger {
public Messenger() {
}
public static void sendEmail() {
...
Language emailLanguage = Language.findByUser(user):
...
}
}
I want to separte those layers in:
// Entity Class
public final class Language {
private final Long id;
private final String code;
private final String description;
//Constructor
public Language() {
}
//getters and setters
public String getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
...
}
// Business Class
public final class LanguageImpl {
public LanguageImpl() {
}
public static Language findByUser(User user) {
Language language;
...implementation to find user language...
return language;
}
....
}
Provide minimal changes to implementation classes, preferable no changes. Otherwise a lot of work will come because of the references all over the code-base.
// Implementing class
public class Messenger {
public Messenger() {
}
public static void sendEmail() {
...
Language emailLanguage = Language.findByUser(user);
...
}
}
How do I work through this refactoring?
How should I rename my classes?
Any thoughts would be very helpful! Thanks!
This is my solution. Please review and accept this if it looks good. Thanks!
The mixed business-entity class is re-used as a wrapper class. This makes it possible to re-use this in all implementing classes where no changes are needed.
public final class Language Extends LanguageImpl{
private final LanguageEntity languageEntity;
//Constructor
public Language(LanguageEntity le) {
languageEntity = le;
}
//Wrapper method
public static Language findByUser(User user) {
LanguageEntity le = findEntityByUser(user);
Language language = new Language(le);
return language;
}
....
}
A new Entity class is created (LanguageEntity) in a new package. This avoids package and naming conflicts with the original mixed class (Language). All entity fields and methods from the mixed class are moved here.
package com.test.entity;
public final class LanguageEntity {
private final Long id;
private final String code;
private final String description;
//Constructor
public LanguageEntity() { }
//getters and setters
public String getId() { return this.id; }
public void setId(Long id) { this.id = id; }
...
}
A new business class is created (LanguageImpl) in a new package. All business methods are moved here. The original mixed class will extend this new business class.
package com.test.impl
public final class LanguageImpl {
//Constructor
public LanguageImpl() { }
//Business is a part of this class
public static LanguageEntity findEntityByUser(User user) {
LanguageEntity language;
...implementation to find user language...
return language;
}
....
}
This is an implementing class that does not need changes. Hundreds of implementation locations remain unchanged, which saves a lot of work. Hurray!
public class Messenger {
public Messenger() { }
public static void sendEmail() {
...
Language emailLanguage = Language.findByUser(user):
...
}
}
And for future development, the new combination LanguageEntity and LanguageImpl will be used. The original Language will be deprecated.
Please leave comments on this solution. Other solutions are more than welcome!

Resources