Vaadin8 grid with List<~> in property - vaadin-grid

I am trying to create a grid using Vaadin and having trouble in showing data which is inside the data source. The Datasource definition is like below
public class Customer {
private String name;
private List<Contacts> contacts;
}
public class Contacts {
private String phonecontact;
private String emailcontact;
}
Now when I write the code to show data using Vaadin
private Grid<Customer> grid=new Grid<>(Customer.class);
grid.setItems(createCutromers());
...............
..............
private List<Customer> createCutromers(){
List<Customer> customerList=new ArrayList<>();
Customer cust=new Customer();
cust.setName("Rocky");
Contacts cont=new Contacts();
List<Contacts> contactsList=new ArrayList();
cont.setEmailcontact("wwww");cont.setPhonecontact("212");
contactsList.add(cont);
cust.setContacts(contactsList);
customerList.add(cust);
return customerList;
}
Now I am trying to show Name and contacts in Grid , how should I go about it? The issue is List is shown as Object. What could be the easiest way to do it.
The output should be like
name | phonecontact | emailcontacts
-----------------------------------------
Rocky | 212 | www

Related

Filter data in spring boot

Dont know if this is possible but I want to call my data and filter it , so for example notification type will be for example 1 or 2 and then give me everything with a 1 and a 2
My Model
public class Notifications {
#Id
private String id;
private String notificationMsg;
private String notificationType;
private Date createdDate = new Date();
//Get all Notification by type
#RequestMapping(value = "/all/{notificationType}", method = RequestMethod.GET)
public List<Notifications> getAllByNotificationType(#PathVariable("notificationType") String notificationType) {
List<Notifications> notifications= this.notificationRepository.findByNotificationType(notificationType);
return user;
}
Or should I add to the model and create a interface like this
List<Notifications> findByNumber1ORNumber2ORNumber3(String Number1,String Number2,String Number3);
You can use in clause :
https://javadeveloperzone.com/spring/spring-jpa-query-in-clause-example/
List<Employee> findByEmployeeNameIn(List<String> names);

spring-data-jdbc: query entity containing 1-n relation with JOOQ

I am trying to load entities containing a reference to another entity (1-n) with the help of JOOQ (based on spring-data-jdbc).
I'm started extending the spring-data-jdbc-jooq-example.
The adjusted model with the 1-n relation:
#Data
public class Category {
private #Id Long id;
private String name, description;
private AgeGroup ageGroup;
private Set<SubCategory> subCategories;
public Category() {}
public Category(Long id, String name, String description, AgeGroup ageGroup) {
this(id, name, description, ageGroup, new HashSet<>());
}
public Category(Long id, String name, String description, AgeGroup ageGroup, Set<SubCategory> subCategories) {
this.id = id;
this.name = name;
this.description = description;
this.ageGroup = ageGroup;
this.subCategories = subCategories;
}
}
#Data
#AllArgsConstructor
#NoArgsConstructor
public class SubCategory {
private #Id Long id;
private String title;
}
I wrote two queries, one via the #Query-Annotation in the CrudRepository and one with the help of JOOQ in the JooqRepository.
interface CategoryRepository extends CrudRepository<Category, Long>, JooqRepository {
#Query("SELECT * FROM category")
List<Category> findAllWithQuery();
}
public interface JooqRepository {
List<Category> findAllWithJooq();
}
public class JooqRepositoryImpl implements JooqRepository {
private final DSLContext dslContext;
public JooqRepositoryImpl(DSLContext dslContext) {
this.dslContext = dslContext;
}
#Override
public List<Category> findAllWithJooq() {
return dslContext.select()
.from(CATEGORY)
.fetchInto(Category.class);
}
}
(for me both methods should return the same result-set b/c they execute the same query?!)
But my unit-test fails:
#Test
public void exerciseRepositoryForSimpleEntity() {
// create some categories
SubCategory sub0 = new SubCategory(null, "sub0");
SubCategory sub1 = new SubCategory(null, "sub1");
Category cars = new Category(null, "Cars", "Anything that has approximately 4 wheels", AgeGroup._3to8, Sets.newLinkedHashSet(sub0, sub1));
// save category
repository.saveAll(asList(cars));
// execute
List<Category> actual = repository.findAllWithJooq();
List<Category> compare = repository.findAllWithQuery();
Output.list(actual, "JOOQ");
Output.list(compare, "Query");
// verify
assertThat(actual).as("same size of categories").hasSize(compare.size());
assertThat(actual.get(0).getSubCategories()).as("same size of sub-categories").hasSize(compare.get(0).getSubCategories().size());
}
with
java.lang.AssertionError: [same size of sub-categories]
Expecting actual not to be null
As you can see in the following output the sub-categories queried by JOOQ will not be loaded:
2019-11-26 16:28:00.749 INFO 18882 --- [ main] example.springdata.jdbc.jooq.Output : ==== JOOQ ====
Category(id=1,
name=Cars,
description=Anything that has approximately 4 wheels,
ageGroup=_3to8,
subCategories=null)
2019-11-26 16:28:00.749 INFO 18882 --- [ main] example.springdata.jdbc.jooq.Output : ==== Query ====
Category(id=1,
name=Cars,
description=Anything that has approximately 4 wheels,
ageGroup=_3to8,
subCategories=[SubCategory(id=1,
title=sub0),
SubCategory(id=2,
title=sub1)])
This is the used database-shema:
CREATE TABLE IF NOT EXISTS category (
id INTEGER IDENTITY PRIMARY KEY,
name VARCHAR(100),
description VARCHAR(2000),
age_group VARCHAR(20)
);
CREATE TABLE IF NOT EXISTS sub_category (
id INTEGER IDENTITY PRIMARY KEY,
title VARCHAR(100),
category INTEGER
)
In the JOOQ variant, JOOQ does the conversion from ResultSet to object instances. Since JOOQ doesn't know about the interpretation of aggregates as it is done by Spring Data JDBC it only hydrates the Category itself, not the contained Set of SubCategory.
Spring Data JDBC on the other hand interprets the structure of the Category and based on that executes another statement to load the subcategories.

Spring MongoRepository custom query

Hi I am new to using Spring with MongoRepository and I'm working on creating a custom query for MongoDB using Spring's MongoRepository.
What I would like to do is return a custom query for another variable in my model instead of the Object id.
for my model I have:
#Document(collection = "useraccount")
public class UserAccounts {
#Id
private String id;
private String accountNumber;
private String firstName;
private String lastName;
// getters and setters
}
inside of my repository I just extend the generic MongoRepository:
#Repository
public interface UserAccountsRepository extends MongoRepository<UserAccounts, String> {
}
I am trying to create a custom query that returns the accountNumber inside of my UserAccountsService:
#Service
public class UserAccountsService {
private final UserAccountsRepository userAccountsRepository;
public UserAccountsService(UserAccountsRepository userAccountsRepository) {
this.userAccountsRepository = userAccountsRepository;
}
// generic find by Object id
public UserAccounts findOne(String id) {
Optional<UserAccounts> userAccountsOptional =
userAccountsRepository.findById(id);
if(!userAccountsOptional.isPresent()) {
throw new RuntimeException("User Account Not Found");
}
return userAccountsOptional.get();
}
// would like to implement custom query to return UserAccount if
// found by accountNumber variable
public UserAccounts findOneByUserAccountNumber(String accountNumber) {
return dormantAccountsRepository.findOne(*need query here*);;
}
}
How would I go about creating a custom query to find a User Account by the accountNumber instead of the object id?
Any help would be great thanks!

How to define an entity with translations using DDD

I have a small application using Domain Driven Design and now I would like to have an entity with translations.
I have read on the internet that the best practices in Domain Driven Design is to separate the translations from the model but I don't know how to do it.
Here an example of what I have:
#Entity
class Product {
#Id
private String id;
private String name;
private String description;
private BigDecimal price;
private BigDecimal originalPrice;
...
}
#Service
class ProductService {
#Autowired
private ProductRepository productRepository;
public List<Product> getAll() {
return productRepository.findAll();
}
public List<Product> getById(String id) {
return productRepository.findById(id);
}
public List<Product> create(ProductDto productDto) {
Product product = new Product(
productDto.getName(),
productDto.getDescription(),
productDto.getPrice(),
productDto.getOriginalPrice()
);
return productRepository.save(product);
}
}
Then my questions are:
Imagine I am receiving the translations in the product DTO and I would like to know how to do it.
Thanks and appreciate your help.
This isn't something your core domain would really be interested in and you should need to model it. You are probably going to have some translation sub-domain where you would be interested in these things but that design would be focused on mapping a key/language pair to a translation.
Your core domain would be using some default language for your location and that would be the well known and required entry in the core domain. For example, your Product may have a ProductID (or SKU or the like) as well as a Description. That description will be in the default language.
Your translation would be on the integration layer as more of an infrastructure service and would provide the translated description if there is one available; else the default one which should be required in your domain.
update:
another answer I gave: DDD: DTO usage with different logic
For example (broadly):
public Translation
{
string Locale { get; set; }
string Value { get; set; }
}
public interface ILocalisationQuery
{
Translation For(string locale, string key);
IEnumerable<Translation> For(string key);
}
public class LocalisationQuery : ILocalisationQuery
{
public Translation For(string locale, string key)
{
// lookup from localisation data store
}
public IEnumerable<Translation> For(string key)
{
// lookup from localisation data store
}
}
You'd implement a strategy that makes sense to you and is applicable to your use case. Say you want to get the Fench description for the spoon product and you have used product-spoon as the convention for the key: localisation.For('fr', 'product-spoon');.
For my JavaScript front-ends I use i18next.
I would recommend to differ your domain model from your data model. While in your domain model you really will not care about any translations and it will look like as what you've proposed, your data model may look different:
#Entity
class Product {
#Id
private String id;
private BigDecimal price;
private BigDecimal originalPrice;
private List<ProductTranslation> translations;
...
}
#Entity
class ProductTranslation{
#Id
private String id;
private String name;
private String description;
private Int languageId;
...
}
Then inside of your repository youl will map from your domain model to your data model, while you will take languageId from some application settings.

AutoMapper mapping model list

I am trying to use AutoMapper for the first time and have some problems with it.
My code is below and I get error below. Maybe someone could show how to map the list of models?
cannot convert from 'System.Linq.IQueryable<AnonymousType#1>' to 'Entity.Product' C:\Users\Administrator\Projects\PC\trunk\PC\Controllers\AdminController.cs 37 100 PC
public class ProductViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public int UsersCount { get; set; }
}
var products = _repository.GetProducts(true).Select(p=> new
{
p.Id,
p.Name,
UsersCount = 0
});
Mapper.CreateMap<Product, ProductViewModel>();
ViewData["Products"] = Mapper.Map<IEnumerable<Product>, IEnumerable<ProductViewModel>>(products); //Error appears on products object
//Product domain model(linq2sql generated model)
public partial class Product : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private int _Id;
private bool _Active;
private System.Nullable<int> _Sort;
private System.Nullable<int> _Category;
private string _Name;
private int _ProductTypeId;
private decimal _Price;
private System.Nullable<int> _Months;
private System.Nullable<int> _Credits;
private string _Features;
private string _BlockReason;
private string _BuyUrl1;
private string _BuyUrl2;
private bool _UsersManager;
}
In your LINQ query you select an anonymous object. Make sure you select a Product which is your source type (or more specifically IEnumerable<Product>):
IEnumerable<Product> products = _repository.GetProducts(true);
IEnumerable<ProductViewModel> productsViewModel = Mapper.Map<IEnumerable<Product>, IEnumerable<ProductViewModel>>(products);
return View(productsViewModel);
Also do not call Mapper.CreateMap<TSource, TDest> inside your controller action. This must be called only once in the lifetime of the AppDomain, ideally in your Application_Start.
Also notice that I have gotten rid of ViewData which is a great thing. You don't need ViewData. You are working with view models. That's what they are supposed to do. Contain information that will be needed by your view in a strongly typed manner.

Resources