How to load a combobox with vaadin fusion - java

Hi I'm using the vaadin starter in order to learn more about vaadin.
I just started a new project (Java+Typescript)
I am having issues to solve an issue.
I have a Users and Rol Entity, being Rol an attribute of User, the thing is when I am setting the views created with vaading start I am trying to set up a combo box to load Roles to be used to create a new user but nothing work so far.
In the tutorial in vaading web page they solve this in a way that is way different to the arch and files created by the vaadin start so I thought that maybe would be another way to do it.
My entities
User
package com.example.application.data.entity;
import com.vaadin.fusion.Nonnull;
import com.example.application.data.AbstractEntity;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
#Entity
public class Users extends AbstractEntity {
#ManyToOne
#Nonnull
private Rol rol;
public Rol getRol() {
return rol;
}
public void setRol(Rol rol) {
this.rol = rol;
}
}
Rol
package com.example.application.data.entity;
import com.vaadin.fusion.Nonnull;
import com.example.application.data.AbstractEntity;
import javax.persistence.Entity;
#Entity
public class Rol extends AbstractEntity{
#Nonnull
private String name;
#Nonnull
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
What should I do to load this with all roles in order to select one in my users-view.ts
<vaadin-combo-box label="Rol" id="rol" ${field(this.binder.model.rol)} item-label-path="name"></vaadin-combo-box>
Right now I'getting this
How the combobox shows
Thanks in advance guys.

My Solution was:
added tis lines to my typescrypt class
#state()
private roles: Rol[] = [];
#state from 'lit/decorators.js'
then in the connectedCallback function added this line
this.roles = await RolesEndpoint.listAll();
listAll() is a method that I created on my endpint class.
like this:
#Nonnull
public List<#Nonnull Rol> listAll() {
return service.listAll();
}
and in my service class
public List<Rol> listAll() {
return repository.findAll();
}
Now you can call the data in your combobox element
<vaadin-combo-box .items=${this.roles} label="Rol" id="rol" ${field(this.binder.model.rol)} item-label-path="name" item-value-path="id"></vaadin-combo-box>
I hope this can be helpful.

Related

How to get rid of automatic installation of a new table

Problem: a new table is created once when I make a post request through The bash console. The rest of the queries go to the new table.
Than he does not like those databases which are available. As I understand - they just don't know, but I don't know how to direct it in the right. Although all variables are also named.
A problem was found created due to an Entity annotation in the Message class. Please tell me how to make it added to an existing table, tried #Table(name = "ApiTable") to an existing one, and it generates a new api_table.. Also don't quite understand what needs to be added/changed to accept json post requests.
Application
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#EnableJpaRepositories("com.example.api")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
MainController
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
#RequestMapping(path="/demo") /
public class MainController {
#Autowired
private UserRepository TestApi;
#PostMapping(path="/add")
public #ResponseBody String addNewUser (#RequestParam String name
, #RequestParam String email) {
Message n = new Message();
n.setName(name);
n.setEmail(email);
TestApi.save(n);
return "Saved";
}
#GetMapping(path="/all")
public #ResponseBody Iterable<Message> getAllUsers() {
return TestApi.findAll();
}
}
Message
import javax.persistence.*;
#Entity
public class Message {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String name;
private String email;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
UserRepository
import org.springframework.data.repository.CrudRepository;
public interface UserRepository extends CrudRepository<Message, Integer> {
}
application.properties
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost/Test?useUnicode=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
The problem seems to be Spring Boot's default naming strategy which you'd have to replace.
Spring Boot's default naming strategy now seems to include converting camelCase to snake_case so you need to choose a different one (or implement your own).
Here's some more info on the topic: Hibernate naming strategy changing table names

Does SDN4 allow multiple relationship of collection type to the same Entity?

When I try to get different relationship type of collection object, the collection property will retrieve all the same entity type even if the relationship type if not the collection relationship type. Is it a bug ?
The entity Demo contains two fields which reference to User entity : user and users
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
import org.neo4j.ogm.annotation.RelationshipEntity;
#NodeEntity
public class Demo extends FormLog implements java.io.Serializable {
private String name;
#Relationship(type="MY_USER")
private User user;
#Relationship(type="DEMO_USERS")
private Set<User> users = new HashSet<User>();
public Demo(){}
public Demo(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
#Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
}
When I save the demo with 1 "MY_USER" and 2 "DEMO_USERS", it is fine.
But when I get find the Demo by group id, the "DEMO_USERS" return 3 users.
#Test
public void test_saveAndFindOne_save2KindsOfUser_NoConfliction(){
Demo demo = new Demo();
List<User> user = userService.findUserByNameLike("Hank");
demo.setUser(user.get(0));
demo.getUsers().add(user.get(1));
demo.getUsers().add(user.get(2));
demo.setName("Set Multiple");
demo = demoRepository.save(demo);
System.out.println("Users size = "+ demo.getUsers().size());
System.out.println("==========Get Demo from DB ==============");
Demo db = demoRepository.findOne(demo.getId());
System.out.println("Users size = "+ db.getUsers().size());
}
The output
Users size = 2
==========Get Demo from DB ==============
Users size = 3
This is probably what you are running into: https://github.com/neo4j/neo4j-ogm/issues/38
You should be able to work around this by annotating your setUser and setUsers methods with the appropriate #Relationship
If that does not help, please report an issue (or add onto the one above).
Update:
Confirmed that this is indeed the same issue as described in https://github.com/neo4j/neo4j-ogm/issues/38
Until this issue is fixed, you'll need to make your objects navigable in both directions. In your example, User will need to have two references to Demo each annotated with the appropriate #Relationship

How to deal with a bean containing #Id #GeneratedVaule in Vaadin?

I'm trying to make a form that will send data to the database in Vaadin.
Bean Person.java is a typical JavaBean:
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Person implements Serializable {
#Id
#GeneratedValue
private Long id;
private String firstName;
private String lastName;
public Person(Long id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public Person() {
}
-- getters and setters --
The Vaadin FieldGroup looks like this:
FieldGroup fieldGroup = new BeanFieldGroup<Person>(Person.class);
// from the tutorial: "We need an item data source before we create the fields to be able to
// find the properties, otherwise we have to specify them by hand"
fieldGroup.setItemDataSource(new BeanItem<Person>(new Person(1L,
"John", "Doe")));
for (Object propertyId : fieldGroup.getBoundPropertyIds()) {
layout.addComponent(fieldGroup.buildAndBind(propertyId));
}
There is nothing on the page. Nothing is generated, no form fields. Am I missing something? I'm completely new to Vaadin to be honest. On the second hand, I'm wondering how to deal with the ID field. It is generated automatically, so the user shall have NO impact on this vaule... I'm lost.
My advice is this:
public class MyUI extends UI {
#Override
protected void init(VaadinRequest request) {
VerticalLayout layout = new VerticalLayout();
FieldGroup fieldGroup = new BeanFieldGroup<Person>(Person.class);
fieldGroup.setItemDataSource(new BeanItem<Person>(new Person(1L, "John", "Doe")));
for (Object propertyId : fieldGroup.getUnboundPropertyIds()) {
Field<?> field = fieldGroup.buildAndBind(propertyId);
if ("id".equals(propertyId)) {
field.setReadOnly(true);
}
layout.addComponent(field);
}
setContent(layout);
}
}
You should use getUnboundPropertyIds(), because you haven't bound any propertyId to field before the iteration.

Playframework2 Ebean : Why doesn't fetch related objects?

Here's my User:
package models.user;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import play.data.validation.Constraints.MaxLength;
import play.data.validation.Constraints.MinLength;
import play.data.validation.Constraints.Required;
import play.db.ebean.Model;
#Entity
#Table(name = "T_USER")
public class User extends Model {
#Id
public Long id;
#Required
#MaxLength(30)
#MinLength(4)
public String username;
#Required
#MaxLength(30)
#MinLength(4)
public String password;
#ManyToOne(fetch = FetchType.EAGER)
#Column(nullable = false)
public Role role;
public static Finder<Long, User> find = new Finder<Long, User>(Long.class, User.class);
public User() {
}
public User(String username, String password, Role role) {
this.username = username;
this.password = password;
this.role = role;
}
#Override
public String toString() {
return "[Tying to login : ] [" + username + " - " + password + "]";
}
}
In my controller, I want to get a user's role instance, so here's what I did:
public static Result modules(Long id) {
User user = User.find.byId(id);
if ("Super User".equalsIgnoreCase(user.role.name)) {
return ok();
} else {
return forbidden();
}
}
The problem is, user.role.name is null, but user.role.id is correct here, why EBean doesn't help me to fetch role for users ?
I have experienced this problem on different occasions. You could do the following:
First, try to replace your public fields with private ones and the add the appropriate getters and setters (this is a good pattern when using Java anyway).
Second, you can write a little helper for finding/fetching the needed information. So let's say you need to get the user by Id and the do this string check. Then in your User class you can write a method like this:
public static User findById(Long id) {
return Ebean.find(User.class)
.fetch("role")
.where()
.eq("id", id)
.findUnique();
}
After that, just use the method:
public static Result modules(Long id) {
User user = User.findById(id);
if ("Super User".equalsIgnoreCase(user.getRole().getName())) {
return ok();
} else {
return forbidden();
}
}

how to make two column as a primary key in hibernate annotation class

This is my annotation class and i want userId and groupId column both as primary key.
I have found more questions (Question) about this, but didn't found relevant answer.
I have less reputation, so I am not able to comment on posts, So I am putting my question here.
This is my code..
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.NaturalId;
#Entity
#Table(name="user_group")
public class user_group {
#Column(name="serviceProvider")
private String serviceProvider;
#Column(name="enterpriseId")
private String enterpriseId;
#Column(name="department")
private String department;
#Column(name="trunkGroupName")
private String trunkGroupName;
#Id
#Column(name="userId")
private String userId;
#Column(name="groupId")
private String group;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getServiceProvider() {
return serviceProvider;
}
public void setServiceProvider(String serviceProvider) {
this.serviceProvider = serviceProvider;
}
public String getEnterpriseId() {
return enterpriseId;
}
public void setEnterpriseId(String enterpriseId) {
this.enterpriseId = enterpriseId;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getTrunkGroupName() {
return trunkGroupName;
}
public void setTrunkGroupName(String trunkGroupName) {
this.trunkGroupName = trunkGroupName;
}
}
You should create a new #Embeddable class containing the PK fields:
#Embeddable
public class user_groupId implements Serializable {
#Column(name="userId")
private String userId;
#Column(name="groupId")
private String group;
}
And use it in the #Entity as an #EmbeddedId:
#Entity
public class user_group {
#EmbeddedId
user_groupId id;
...
}
You could also use the #IdClass annotation to that effect.
This excellent answer by Pascal Thivent elaborates on the details. You can also take a look at this other answer I posted to a almost identical question some time ago.
As a side note, if you've got control over the DB structure, you might also consider avoiding composite keys. There are some reasons to do so.
you can create a composite primary key in hibernate using #UniqueConstraint annotation.
#Table(name="user_group",uniqueConstraints=#UniqueConstraint(columnNames= {"userId","groupId"}))
public class user_group
{
#Column(name="userId")
private String userId;
#Column(name="groupId")
private String group;
}
above method is not feasible if we use spring because for creating composite primary key we have to create a class is not a good thing.
in hibernate and spring you only have to create POJO classes which are available as an entity on your system.

Categories

Resources