JAVA Spring : Service returning a null - java

For some reason, my service is returning a null. The autowires are correct, the service annotation is there, the getters and setters .. But this returns a null :
public PlatformService getPlatformService() {
return platformService;
}
public void setPlatformService(PlatformService platformService) {
this.platformService = platformService;
}
on Debug, it returns platformService = null
Here is my PlatformService :
package empsuite.service;
import java.util.List;
import empsuite.model.Platform;
public interface PlatformService {
public void addPlatform(Platform platform);
public void updatePlatform(Platform platform);
public Platform getPlatformById(int id);
public List<Platform> getPlatform();
}
PlatformServiceImpl :
#Service
#Transactional
public class PlatformServiceImpl implements PlatformService {
#Autowired
PlatformDAO platformDAO;
#Transactional(readOnly = false)
public void addPlatform(Platform platform) {
getPlatformDAO().addPlatform(platform);
}
#Transactional(readOnly = false)
public void updatePlatform(Platform platform) {
getPlatformDAO().updatePlatform(platform);
}
private PlatformDAO getPlatformDAO() {
return platformDAO; }
public void setPlatformDAO(PlatformDAO platformDAO) {
this.platformDAO = platformDAO;
}
public Platform getPlatformById(int id) {
return getPlatformDAO().getPlatformById(id);
}
public List<Platform> getPlatform() {
return getPlatformDAO().getPlatform();
}
}
The DAOImpl function (with sessionfactory autowired) as it is the builder of the HQL :
public List<Platform> getPlatform() {
List list = getSessionFactory().getCurrentSession().createQuery("from Platform").list();
return list;
}

#ManagedProperty is the cause of the problem, so I overriden it and it works with this constructor :
public PlatformManagedBean() {
super();
if(platformService == null){
WebApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
platformService = ctx.getBean(PlatformService.class);
}
}

Related

Springboot posgresql reposity bean can't be autowired

I have simple Sprinngboot app where actual database is PostgreSQL.
My model:-
#Table("carrier")
#Entity
public class MyCarrier {
#Id
#Column("id")
private UUID id;
#Size(
max = 100
)
#Column("carrier_name")
private String carrierName;
#Size(
max = 3
)
#Column("smdg_code")
private String smdgCode;
#Size(
max = 4
)
#Column("nmfta_code")
private String nmftaCode;
public MyCarrier() {
}
public UUID getId() {
return this.id;
}
public String getCarrierName() {
return this.carrierName;
}
public String getSmdgCode() {
return this.smdgCode;
}
public String getNmftaCode() {
return this.nmftaCode;
}
public void setId(final UUID id) {
this.id = id;
}
public void setCarrierName(final String carrierName) {
this.carrierName = carrierName;
}
public void setSmdgCode(final String smdgCode) {
this.smdgCode = smdgCode;
}
public void setNmftaCode(final String nmftaCode) {
this.nmftaCode = nmftaCode;
}
protected boolean canEqual(final Object other) {
return other instanceof Carrier;
}
}
Repository:-
#Repository
public interface MyCarrierRepository extends JpaRepository<MyCarrier, Long> {
}
Controller:-
#RestController
#RequestMapping(path = "/upload")
public class ReactiveUploadResource {
Logger LOGGER = LoggerFactory.getLogger(ReactiveUploadResource.class);
private final SqlRequestHandler sqlRequestHandler;
#Autowired
private MyCarrierRepository myCarrierRepository;
public ReactiveUploadResource(SqlRequestHandler sqlRequestHandler) {
this.sqlRequestHandler = sqlRequestHandler;
}
}
I got this error:-
Description:
Field myCarrierRepository in com.consumer.controller.ReactiveUploadResource required a bean of type 'com.consumer.repository.MyCarrierRepository' that could not be found.
What is missing? Why Springboot doesn't find this repository?
You have to put the repository inside the package at the same level as Application class the packages to allow Spring boot to scan it

A NullPointerException is caught when I try to add a new client in a CRUD Spring boot Application

I am doing a CRUD web application using Spring boot, spring mvc and Spring Data JPA. I wanted to test my code in the main class with adding a new client. It returns me a NullPointerException. I already check my code with a debug mode. Honestly I don't see where is exactly the issue, so, if it's possible to help it will be a pleasure.
Entity class :
#Entity
#Table(name="cliente")
public class Cliente implements Serializable{
#Id #GeneratedValue
private Integer idCliente;
private String iceCliente;
private String nombreCliente;
private String apellidoCliente;
private String direccionCliente;
private String telefonoCliente;
private String emailCliente;
private TipoCliente tipoCliente;
private String cuidadCliente;
public Cliente() {
super();
}
public Cliente(String iceCliente, String nombreCliente, String apellidoCliente, String direccionCliente,
String telefonoCliente, String emailCliente, TipoCliente tipoCliente, String cuidadCliente) {
super();
this.iceCliente = iceCliente;
this.nombreCliente = nombreCliente;
this.apellidoCliente = apellidoCliente;
this.direccionCliente = direccionCliente;
this.telefonoCliente = telefonoCliente;
this.emailCliente = emailCliente;
this.tipoCliente = tipoCliente;
this.cuidadCliente = cuidadCliente;
}
public Integer getIdCliente() {
return idCliente;
}
public void setIdCliente(int idCliente) {
this.idCliente = idCliente;
}
public String getIceCliente() {
return iceCliente;
}
public void setIceCliente(String iceCliente) {
this.iceCliente = iceCliente;
}
public String getNombreCliente() {
return nombreCliente;
}
public void setNombreCliente(String nombreCliente) {
this.nombreCliente = nombreCliente;
}
public String getApellidoCliente() {
return apellidoCliente;
}
public void setApellidoCliente(String apellidoCliente) {
this.apellidoCliente = apellidoCliente;
}
public String getDireccionCliente() {
return direccionCliente;
}
public void setDireccionCliente(String direccionCliente) {
this.direccionCliente = direccionCliente;
}
public String getTelefonoCliente() {
return telefonoCliente;
}
public void setTelefonoCliente(String telefonoCliente) {
this.telefonoCliente = telefonoCliente;
}
public String getEmailCliente() {
return emailCliente;
}
public void setEmailCliente(String emailCliente) {
this.emailCliente = emailCliente;
}
public TipoCliente getTipoCliente() {
return tipoCliente;
}
public void setTipoCliente(TipoCliente tipoCliente) {
this.tipoCliente = tipoCliente;
}
public String getCuidadCliente() {
return cuidadCliente;
}
public void setCuidadCliente(String cuidadCliente) {
this.cuidadCliente = cuidadCliente;
}
ClienteService :
#Service
#Transactional
public class ClienteServiceImpl implements ClienteService {
#Autowired
ClienteRepository clienteRepository;
#Override
public Cliente agregarCliente(Cliente cliente) {
return clienteRepository.save(cliente);
}
#Override
public Cliente editarCliente(Cliente cliente) {
Optional<Cliente> clienteDB = this.clienteRepository.findById(cliente.getIdCliente());
if (clienteDB.isPresent()) {
Cliente clienteUpdate = clienteDB.get();
clienteUpdate.setIdCliente(cliente.getIdCliente());
clienteUpdate.setIceCliente(cliente.getIceCliente());
clienteUpdate.setNombreCliente(cliente.getNombreCliente());
clienteUpdate.setApellidoCliente(cliente.getApellidoCliente());
clienteUpdate.setDireccionCliente(cliente.getDireccionCliente());
clienteUpdate.setCuidadCliente(cliente.getCuidadCliente());
clienteUpdate.setTelefonoCliente(cliente.getTelefonoCliente());
clienteUpdate.setEmailCliente(cliente.getEmailCliente());
clienteRepository.save(clienteUpdate);
return clienteUpdate;
} else {
throw new RessourceNotFoundException(
"Cliente no encontrado con nombre de usuario : " + cliente.getIdCliente());
}
}
#Override
public List<Cliente> obtenerCliente() {
return this.clienteRepository.findAll();
}
#Override
public void removeCliente(Integer idCliente) {
Optional<Cliente> clienteDB = this.clienteRepository.findById(idCliente);
if (clienteDB.isPresent()) {
this.clienteRepository.delete(clienteDB.get());
} else {
throw new RessourceNotFoundException("Cliente no encontrado con nombre de usuario : " + idCliente);
}
}
#Override
public Cliente obtenerClientePorId(Integer idCliente) {
Optional<Cliente> clienteDB = this.clienteRepository.findById(idCliente);
if (clienteDB.isPresent()) {
return clienteDB.get();
} else {
throw new RessourceNotFoundException("Cliente no encontrado con nombre de usuario : " + idCliente);
}
}
ClienteRepository :
#Repository
public interface ClienteRepository extends JpaRepository<Cliente, Integer> {
}
ClienteController :
#RestController
//#RequestMapping("/index")
public class ClienteController {
#Autowired
private ClienteService clienteService;
#GetMapping("/clientes")
public ResponseEntity<List<Cliente>> obtenerCliente() {
return ResponseEntity.ok().body(clienteService.obtenerCliente());
}
#GetMapping("/clientes/{id}")
public ResponseEntity<Cliente> obtenerClientePorId(#PathVariable Integer idCliente) {
return ResponseEntity.ok().body(clienteService.obtenerClientePorId(idCliente));
}
#PostMapping("/clientes")
public ResponseEntity<Cliente> agregarCliente(#RequestBody Cliente cliente) {
return ResponseEntity.ok().body(this.clienteService.agregarCliente(cliente));
}
#PutMapping("/clientes/{id}")
public ResponseEntity<Cliente> editarCliente(#PathVariable Integer idCliente, #RequestBody Cliente cliente) {
cliente.setIdCliente(idCliente);
return ResponseEntity.ok().body(this.clienteService.editarCliente(cliente));
}
#DeleteMapping("/clientes/{id}")
public HttpStatus removeCliente(#PathVariable Integer idCliente) {
this.clienteService.removeCliente(idCliente);
return HttpStatus.OK;
}
Main class :
#SpringBootApplication
//#EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class NestideasFacturasApplication {
#Autowired
public static ClienteService clienteService = new ClienteServiceImpl();
public static void main(String[] args) {
SpringApplication.run(NestideasFacturasApplication.class, args);
System.out.println("Application démarrée");
System.out.println(clienteService);
clienteService.agregarCliente(new Cliente("16565465", "Hassan", "JROUNDI", "Said Hajji", "0662165537",
"hassan.jroundi#outlook.fr", TipoCliente.EMPREZA, "Salé"));
System.out.println(clienteService);
}
Stacktrace :
Stacktrace
First, for your test scenario, it's better to use ApplicationRunner.
NestideasFacturasApplication must implement ApplicationRunner, and override run method. Then you can write your test scenario in run.
Code :
#SpringBootApplication
public class NestideasFacturasApplication implements ApplicationRunner {
public static void main(String[] args) {
SpringApplication.run(NestideasFacturasApplication.class, args);
}
#Override
public void run(ApplicationArguments args) {
//Your test scenario ...
}
}
Second, Change injection of ClienteService like below
#Autowired
private ClienteService clienteService;
So we have (Entire code)
#SpringBootApplication
public class NestideasFacturasApplication implements ApplicationRunner {
#Autowired
private ClienteService clienteService;
public static void main(String[] args) {
SpringApplication.run(NestideasFacturasApplication.class, args);
}
#Override
public void run(ApplicationArguments args) {
//Your test scenario
System.out.println("Application démarrée");
System.out.println(clienteService);
clienteService.agregarCliente(new Cliente("16565465", "Hassan", "JROUNDI", "Said Hajji", "0662165537", "hassan.jroundi#outlook.fr", TipoCliente.EMPREZA, "Salé"));
}
}

Generic DAO cause stack overflow

Hello I Have a problem with my Spring/Hibernate project. I was trying to implement generic classes for DAOs and Services and use one concrete implementation to show something on screen. Everything starts without error, but if i wanna create a new project, after form submisions it throws Stack Overflow error (see image below). I rly cant find out where the problem is. I hope someone here can help me. Below you can see all my code, potentialy can add jsp or config files if necessary. Thanks for your time.
GenericDaoImpl
#SuppressWarnings("unchecked")
#Repository
public abstract class GenericDaoImpl<T, PK extends Serializable> implements IGenericDao<T, PK> {
#Autowired
private SessionFactory sessionFactory;
protected Class<? extends T> entityClass;
public GenericDaoImpl() {
Type t = getClass().getGenericSuperclass();
ParameterizedType pt = (ParameterizedType) t;
entityClass = (Class<? extends T>) pt.getActualTypeArguments()[0];
}
protected Session currentSession() {
return sessionFactory.getCurrentSession();
}
#Override
public PK create(T t) {
return (PK) currentSession().save(t);
}
#Override
public T read(PK id) {
return (T) currentSession().get(entityClass, id);
}
#Override
public void update(T t) {
currentSession().saveOrUpdate(t);
}
#Override
public void delete(T t) {
currentSession().delete(t);
}
#Override
public List<T> getAll() {
return currentSession().createCriteria(entityClass).list();
}
#Override
public void createOrUpdate(T t) {
currentSession().saveOrUpdate(t);
}
GenericServiceImpl
#Service
public abstract class GenericServiceImpl<T, PK extends Serializable> implements IGenericService<T, PK>{
private IGenericDao<T, PK> genericDao;
public GenericServiceImpl(IGenericDao<T,PK> genericDao) {
this.genericDao=genericDao;
}
public GenericServiceImpl() {
}
#Override
#Transactional(propagation = Propagation.REQUIRED)
public PK create(T t) {
return create(t);
}
#Override
#Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public T read(PK id) {
return genericDao.read(id);
}
#Override
#Transactional(propagation = Propagation.REQUIRED)
public void update(T t) {
genericDao.update(t);
}
#Override
#Transactional(propagation = Propagation.REQUIRED)
public void delete(T t) {
genericDao.delete(t);
}
#Override
#Transactional(propagation = Propagation.REQUIRED)
public void createOrUpdate(T t) {
genericDao.createOrUpdate(t);
}
#Override
#Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public List<T> getAll() {
return genericDao.getAll();
}
}
ProjectDaoImpl
#Repository
public class ProjectDaoImpl extends GenericDaoImpl<Project, Integer> implements IProjectDao{
}
ProjectServiceImpl
#Service
public class ProjectServiceImpl extends GenericServiceImpl<Project, Integer> implements IProjectService {
#Autowired
public ProjectServiceImpl(#Qualifier("projectDaoImpl") IGenericDao<Project, Integer> genericDao) {
super(genericDao);
}
}
ProjectController
public class ProjectController {
#Autowired(required = true)
private IProjectService projectService;
#RequestMapping(value = "/projects", method = RequestMethod.GET)
public String listProjects(Model model){
model.addAttribute("project", new Project());
model.addAttribute("listProjects", projectService.getAll());
return "project";
}
//for add and update role both
#RequestMapping(value = "/project/add", method = RequestMethod.POST)
public String addProject(#ModelAttribute("project") Project p){
if( p.getId() == 0){
//new role, add it
projectService.create(p);
} else {
//existing role, call update
projectService.update(p);
}
return "redirect:/projects";
}
#RequestMapping("/remove/{id}")
public String deleteProject(#PathVariable("id") int id){
projectService.delete(projectService.read(id));
return "redirect:/projects";
}
#RequestMapping("edit/{id}")
public String editProject(#PathVariable("id") int id, Model model){
model.addAttribute("project", projectService.read(id));
model.addAttribute("listProjects", projectService.getAll());
return "project";
}
}
#Override
#Transactional(propagation = Propagation.REQUIRED)
public PK create(T t) {
return create(t);
}
This method is calling itself unconditionally. This can only result in a StackOverflowError.
Did you mean to do this?
#Override
#Transactional(propagation = Propagation.REQUIRED)
public PK create(T t) {
return genericDao.create(t);
}

Cannot resolve reference Local ejb-ref

I have an issue in programming an EJB application. I search a solution but I still have the same problem in intelliJ with Glassfish4 :
" Cannot resolve reference [Local ejb-ref name=EJB.AdminEJB,Local 3.x interface =Interface.AdminInterface,ejb-link=null,lookup=,mappedName=,jndi-name=,refType=Session] because there are [2] ejbs in the application with interface Interface.AdminInterface."
And excuse-me for my english, I'm french.
AdminInterface in a package Interface
#Local
public interface AdminInterface {
public void creerParieur(Parieur parieur);
public void supprimerParieur (String login);
public void creerBookmaker(Bookmaker bookmaker);
public void supprimerBookmaker (String login);
public void modifParieur (Parieur parieur);
public void modifBookmaker (Bookmaker bookmaker);
public void ajouterCote(Cote cote);
public void ajouterMatch (Match match);
public List<Cote> listeCote(String log);
public List<Match> listeMatch();
public List<Parieur> listeParieur();
public List<Bookmaker> listeBookmaker();
public Parieur rechercheParieur(String id);
public Bookmaker rechercheBookmaker (String id);
public void setLogin(String login);
public String getLogin();
}
AdminEJB in a package EJB
#Stateless
public class AdminEJB implements AdminInterface{
String login;
String mdp;
#PersistenceContext(unitName = "NewPersistenceUnit")
EntityManager em;
public AdminEJB(){}
public String getLogin(){
return login;
}
public void setLogin(String login){
this.login=login;
}
public String getMdp(){
return mdp;
}
public void setMdp(String mdp){
this.mdp=mdp;
}
public void creerParieur(Parieur parieur){
em.persist(parieur);
}
public void supprimerParieur(String login){
Parieur parieur=new Parieur ();
Query req=em.createQuery("select OBJECT(P) from Parieur P where P.login=:login");
req.setParameter("login", login);
parieur=(Parieur)req.getSingleResult();
em.remove(parieur);
}
public void modifParieur(Parieur parieur){
em.merge(parieur);
}
public List<Parieur> listeParieur(){
Query req=em.createQuery("select OBJECT(P) from Parieur P");
return req.getResultList();
}
public void creerBookmaker(Bookmaker bookmaker){
em.persist(bookmaker);
}
public void supprimerBookmaker(String login){
Bookmaker bookmaker;
Query req=em.createQuery("select OBJECT(B) from Bookmaker B where B.pseudo=:login");
req.setParameter("login", login);
bookmaker=(Bookmaker)req.getSingleResult();
em.remove(bookmaker);
}
public void modifBookmaker(Bookmaker bookmaker){
em.merge(bookmaker);
}
public List<Bookmaker> listeBookmaker(){
Query req=em.createQuery("select OBJECT(B) from Bookmaker B");
return req.getResultList();
}
public List<Match> listeMatch(){
Query req=em.createQuery("select OBJECT(M) from Match M");
return req.getResultList();
}
public Bookmaker rechercheBookmaker(String id){
return em.find(Bookmaker.class,id);
}
public Parieur rechercheParieur(String id){
return em.find(Parieur.class,id);
}
public void ajouterCote (Cote cote){
em.persist(cote);
}
public void ajouterMatch (Match match){
em.persist(match);
}
public List<Cote> listeCote(String log){
Bookmaker bookmaker = new Bookmaker();
bookmaker = this.rechercheBookmaker(log);
Query req = em.createQuery("select OBJECT(C) from Cote C where C.bookmaker=:bookmaker");
req.setParameter("bookmaker", bookmaker);
return req.getResultList();
}
}
ControlerBean in a package ManagedBean
#ManagedBean
#RequestScoped
public class ControlerBean implements Serializable{
Bookmaker bookmaker;
Pari pari;
Parieur parieur;
Match match;
Cote cote;
String nomObjetP;
String nomEnP;
String pseudoUser;
String pwdUser;
#EJB
private AdminInterface admin;
public ControlerBean(){
bookmaker = new Bookmaker();
parieur = new Parieur();
cote = new Cote();
match= new Match();
pari= new Pari();
}
public String getNomObjetP() {
return nomObjetP;
}
public void setNomObjetP(String nomObjetP) {
this.nomObjetP = nomObjetP;
}
public String getNomEnP() {
return nomEnP;
}
public void setNomEnP(String nomEnP) {
this.nomEnP = nomEnP;
}
public Pari getPari() {
return pari;
}
public void setPari(Pari pari){
this.pari=pari;
}
public Bookmaker getBookmaker() {
return bookmaker;
}
public void setBookmaker(Bookmaker bookmaker) {
this.bookmaker = bookmaker;
}
public Parieur getParieur() {
return parieur;
}
public void setParieur(Parieur parieur) {
this.parieur = parieur;
}
public Cote getCote() {
return cote;
}
public void setCote(Cote cote) {
this.cote = cote;
}
public Match getMatch(){
return match;
}
public void setMatch(Match match){
this.match=match;
}
public AdminInterface getAdmin() {
return admin;
}
public void setAdmin(AdminInterface admin) {
this.admin = admin;
}
public String getPseudoUser() { return pseudoUser; }
public void setPseudoUser(String pseudoUser) {
this.pseudoUser = pseudoUser;
}
public String getPwdUser() {
return pwdUser;
}
public void setPwdUser(String pwdUser) {
this.pwdUser = pwdUser;
}
public String addParieur(){
parieur.setArgent(1000);
admin.creerParieur(parieur);
return "OK";
}
public String modifParieur(){
admin.modifParieur(parieur);
return "OK";
}
public String supprParieur(){
admin.supprimerParieur(parieur.getLogin());
return "OK";
}
public String addBookmaker(){
admin.creerBookmaker(bookmaker);
return "OK";
}
public String modifBookmaker(){
admin.modifBookmaker(bookmaker);
return "OK";
}
public String supprBookmaker(){
admin.supprimerBookmaker(bookmaker.getPseudo());
return "OK";
}
public List<Bookmaker> listeBookmaker(){
return admin.listeBookmaker();
}
public List<Parieur> listeParieur(){
return admin.listeParieur();
}
public List<Match> listeMatch(){ return admin.listeMatch(); }
public String addCote(){
pseudoUser = admin.getLogin();
cote.setBookmaker(admin.rechercheBookmaker(pseudoUser));
admin.ajouterCote(cote);
return "OK";
}
public String addMatch(){
admin.ajouterMatch(getMatch());
return "OK";
}
}
Thank's very much for any help
When you have two EJBs implementing the same interface they need to be differentiated so that the container knows which one to inject.
Add the name parameter in the #Stateless annotation to all beans implementing the same interface. In the #EJB annotation, use the beanName parameter to inject the appropriate session bean implementation.
#Stateless(name="AdminEJB1")
public class AdminEJB implements AdminInterface { .... }
#EJB(beanName = "AdminEJB1")
private AdminInterface myAdminEjb;
You can also skip the name parameter in the #Stateless annotation and then use the name of the implementing class as the beanName parameter in the #EJB annotation.
#Stateless
public class AdminEJB implements AdminInterface { .... }
#EJB(beanName = "AdminEJB")
private AdminInterface myAdminEjb;
I had same error, but I didn't work with one interface for different EJBs (generated local Session Beans from entity classes). So I am putting this answer if somebody had same problem as me, as I didn't found one here. My framework generated "ejb-local-ref" tag in pom.xml on its own. After deleting it, all works perfectly.
Another cause for this problem, although uncommon, may be the delay in communicating with the JMX port. To get around this it is possible to put the key -Dhk2.parser.timeout = 300

DynamoDB mapping List of Enum

Mapping an enum class in to DynamoDB object is really simple by using Custom Marshall. But how to map a List of Enum?
Enum class
public enum Transport {
SMS,EMAIL,ALL;
}
DynamoDB mapper
public class Campaign{
private List<Transport> transport;
#DynamoDBAttribute(attributeName = "transport")
public List<Transport> getTransport() {
return transport;
}
public void setTransport(List<Transport> transport) {
this.transport = transport;
}
}
DynamoDBMarshaller is deprecated.
Use DynamoDBTypeConverter instead.
Example:
Enum class
public static enum ValidationFailure {
FRAUD, GENERAL_ERROR
}
DynamoDBTable class
#DynamoDBTable(tableName = "receipt")
public class Receipt {
private Long id;
private List<ValidationFailure> validation;
#DynamoDBHashKey(attributeName = "id")
public Long getId() {
return id;
}
#DynamoDBTypeConverted(converter = ValidationConverter.class)
public List<ValidationFailure> getValidation() {
return validation;
}
public void setId(Long id) {
this.id = id;
}
public void setValidation(List<ValidationFailure> validation) {
this.validation = validation;
}
}
Convertor:
public class ValidationConverter implements DynamoDBTypeConverter<List<String>, List<ValidationFailure>> {
#Override
public List<String> convert(List<ValidationFailure> object) {
List<String> result = new ArrayList<String>();
if (object != null) {
object.stream().forEach(e -> result.add(e.name()));
}
return result;
}
#Override
public List<ValidationFailure> unconvert(List<String> object) {
List<ValidationFailure> result = new ArrayList<ValidationFailure>();
if (object != null) {
object.stream().forEach(e -> result.add(ValidationFailure.valueOf(e)));
}
return result;
}
}
It's working for me, I have used the Set
#DynamoDBTyped(DynamoDBMapperFieldModel.DynamoDBAttributeType.SS)
var roles: MutableSet<Employee.Role>? = null
I think the same approach would work for List with DynamoDBAttributeType.L
I found the answer myself. I create a custom marshall like below.
public class TransportMarshaller implements DynamoDBMarshaller<List<Transport>> {
#Override
public String marshall(List<Transport> transports) {
List<String>transportMap=new ArrayList<>();
for(Transport transport:transports){
transportMap.add(transport.name());
}
return transportMap.toString().replaceAll("\\[|\\]", "");//Save as comma separate value for the purpose of easiness to unmarshall
}
#Override
public List<Transport> unmarshall(Class<List<Transport>> aClass, String s) {
List<String>map= Arrays.asList(s.split("\\s*,\\s*")); //split from comma and parse to List
List<Transport>transports=new ArrayList<>();
for (String st:map){
transports.add(Transport.valueOf(st));
}
return transports;
}
}

Categories