How to map 2 classes using model mapper, Entity to Dto - java

I want to convert two objects with same attributes using model mapper. How ever I cant because of many to many relationship.
private User fromEntity(UserEntity userEntity) {
LOGGER.info("Converting userEntity to user model with Id" +
userEntity.getUserId());
User user = modelMapper.map(userEntity,User.class);
LOGGER.info("Converted userEntity to user model with Id" +
userEntity.getUserId());
return user;
}
I have User and UserEntity classes. They are mapped with Role and RoleEntity classess:
Here is my User class:
public class User {
private Long userId;
private String userUsername;
private String userName;
private String userSurname;
private String password;
private String addres;
private String eMail;
private boolean active = false;
private String key;
//#JsonBackReference
private Set<Role> role ;
public User(){
role = new HashSet<>();
}
Role Class:
public class Role {
private Long roleId;
private String role;
private Set<User> user;
public Role(){
user = new HashSet<>();
}
//#JsonManagedReference
public Set<User> getUser() {
return user;
}
}
UserEntity Class:
#Entity
#Table( name="users" )
public class UserEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "userId")
private Long userId;
private String userUsername;
private String userName;
private String userSurname;
private String password;
private String addres;
private String eMail;
private boolean active;
private String key;
#JsonManagedReference
#ManyToMany( cascade = CascadeType.ALL, fetch = FetchType.EAGER )
#JoinTable(
name = "users_roles",
joinColumns = {#JoinColumn(name="userId")},
inverseJoinColumns = {#JoinColumn(name="roleId")}
)
private Set<RoleEntity> roleEntities;
public UserEntity(){
active=false;
roleEntities = new HashSet<>();
}
and RoleEntity class:
#Entity
#Table(name="roles")
public class RoleEntity {
#Id
#GeneratedValue
private Long roleId;
private String role;
#ManyToMany //( mappedBy = "roleEntities") //Bunu kaldırdım
private Set<UserEntity> userEntities ;
public RoleEntity(){
userEntities = new HashSet<>();
}
It gives me error when I login correctly:
ModelMapper mapping errors: 1) Converter org.modelmapper.internal.converter.CollectionConverter#735060fc failed to convert java.util.Set to java.util.Set. 1 error

I have changed my RoleEntity class attribute from:
#ManyToMany //( mappedBy = "roleEntities")
private Set<UserEntity> userEntities ;
to this:
#ManyToMany (mappedBy = "roleEntities", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Set<UserEntity> userEntities ;
That is how I resolved the problem.

Related

SQL Query returns Null Values

I have a User entity with role types Marketer, Managing Director and General Manager . When the UserRole Managing Director logs In, I want the userrole Managing Director to only see customers assigned to Usertype Marketers with the same Branch ID as the Managing Director.
I have a custom Query in the customer repository that returns a null result.
#Query("SELECT customer from Customer customer join customer.marketer marketer "
+ "where marketer.branch = :director")
List<Customer> findByUserBranch(User director);
This is the User entity
#Entity
#JsonIgnoreProperties({"hibernateLazyInitializer","handler"})
public class User {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String firstName ;
private String lastName;
#Column(name="user_name", unique=true)
private String userName;
private String password;
private String Gender;
private String phoneNumber;
private String email;
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
#ManyToOne(targetEntity = Branch.class,
fetch = FetchType.LAZY )
#JoinColumn(name="branch_id")
private Branch branch;
#DateTimeFormat(pattern = "yyyy-MM-dd")
private Date createdDate;
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(
name = "users_roles",
joinColumns = #JoinColumn(name = "user_id"),
inverseJoinColumns = #JoinColumn(name = "role_id")
)
private Set<UserRole> userRole = new HashSet<>();
#Enumerated(EnumType.STRING)
private UserStatus status;
#JsonBackReference
#OneToMany(mappedBy="marketer",cascade = CascadeType.ALL, targetEntity=Customer.class)
private List <Customer> customer;
This is the controller class
#GetMapping(value="branch/customers")
public List<Customer> getListByBranch()
{ Authentication authentication =
SecurityContextHolder.getContext().getAuthentication();
User loggedInUser = userRepo.findByUserName(authentication.getName()); return customerRepo.findByBranch(loggedInUser);
}
UPDATED :
This is the Customer class
#Entity
#JsonIgnoreProperties({"hibernateLazyInitializer","handler"})
public class Customer implements Serializable {
/**
*
*/
private static final long serialVersionUID = 8348682056500740593L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String userName;
private String password;
private String firstName ;
private String lastName;
private String gender;
private String Address;
private String maritalStatus;
private String category;
private String motherMaidenName;
private String idType;
private String idNumber;
private String phoneNumber;
private String email;
#Column(nullable = true, length = 64)
private String photos;
#DateTimeFormat(pattern = "yyyy-MM-dd")
private Date dateOfBirth;
#DateTimeFormat(pattern = "yyyy-MM-dd")
private Date registrationDate;
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
#ManyToOne(targetEntity = User.class,
fetch = FetchType.LAZY )
#JoinColumn(name="marketer_id")
private User marketer ;
#JsonBackReference
#OneToMany(mappedBy="customer_id",cascade = CascadeType.ALL, targetEntity=Investment.class)
private List<Investment> investment;
I can't make a comment, so i would ask to also give us the customer.class .
Got it resolved . I changed the User object to branch object.
#Query("SELECT customer from Customer customer join "
+ "customer.marketer marketer "
+ "where marketer.branch = :branch")
List<Customer> findByUserBranch(Branch branch);
Then refactored the controller class
#GetMapping(value="branch/customers")
public List<Customer> getListByBranch(Principal principal)
{
User loggedInUser = userRepo.findByUserName(principal.getName());
Branch branchId = loggedInUser.getBranch();
return customerRepo.findByBranch(branchId);
}

Creating association between entity to-many JPA

I want to make association to some many-to-many relation entity
#Entity
#Table(name = "users")
#Data
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_id")
private String userId;
private String name;
#OneToMany(mappedBy = "user")
private List<UserGroups> userGroups;
#Table(name = "groups")
#Data
public class Group {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "group_id")
private String groupId;
private String category;
private String name;
private String description;
#OneToMany(mappedBy = "group")
private List<UserGroups> userGroups;
public void addUser(User user){
UserGroup newUserGroup = new UserGroup();
newUserGroup.setName(user.getName())
userGroups.add(newUserGroup);
user.getUserGroups().add(newUserGroup)
}
#Entity
#Data
#Table(name = "user_groups")
public class UserGroups {
#EmbeddedId
UserGroupsCompositeKey id;
#ManyToOne
#MapsId("userId")
#JoinColumn(name = "user_id")
private Users user;
#ManyToOne
#MapsId("featureId")
#JoinColumn(name = "group_id")
private Group group;
private Date created;
I trying to add POST method to service where I should get group_id from endpoint url and assosiate user_id in request body. My Service method looks like this.
#Override
public ResponseEntity<String> createUsersGroup(String groupId,
String userId) {
Optional<Group> group = groupRepository.findById(groupId).get();
Optional<User> user = userRepository.findById(userId).get();
group.addUser(user);
return ResponseEntity.ok(userId);
};
}
Is there some more proper way to do this or when I will add more users in request body I will have to pull out every user from the database and add it like that ?

Hibernate modelmapper null value inserted

I'm starting to use Spring and Hibernate.
I have this Entity :
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(nullable = false, unique = true)
private String username;
#NotEmpty
private String password;
#NotEmpty
private String firstname;
#NotEmpty
private String lastname;
#NotEmpty
private String email;
#ManyToMany (cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(name = "user_role",
joinColumns = { #JoinColumn(name = "user_id") },
inverseJoinColumns = { #JoinColumn(name = "role_id") })
private Set<Role> roles = new HashSet<>();
}
and this DTO :
public class UserDTO {
private String username;
private String password;
private String firstname;
private String lastname;
private String email;
private List<String> roles;
}
Role is like that (RoleType being an enum) :
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Enumerated(EnumType.STRING)
#Column(unique = true)
private RoleType name;
public Role() {}
public Role(RoleType name) {
this.name = name;
}
}
Now, in my controller, I want to create a new user :
public void createNewUser(UserDTO user){
ModelMapper _modelMapper=new ModelMapper();
User _newUser=_modelMapper.map(user, User.class);
//SECOND PART
Set<Role> _roles=new HashSet<>();
for (String _item : user.getRoles()) {
RoleType _roleType=RoleType.valueOf(_item);
Role _role=_roleRepository.findByName(_roleType);
_roles.add(_role);
}
_newUser.setRoles(_roles);
_userRepository.save(_newUser);
}
My concern is the second part (It does the trick but I'm not sure in term of good practices). I have 2 questions :
-is it the right way to fill the roles, being said that my UserDTO accepts a List<String> ?
-is it possible to map everything with the ModelMapper ? (I have tried but it fills my sql table only with the id, the name is null and it adds a line for each new user).
Thanks.

Identifier Generation Exception

I have some problems with identifier generation. I use MySQL database. So, I have two entities:
#Entity
#Table(name = "users", catalog = "test1")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="id", unique=true, nullable=false, updatable=false)
private Long id;
private String username;
private String password;
private boolean enabled;
#JsonBackReference
private Set<UserRole> userRole = new HashSet<UserRole>(0);
#OneToOne(cascade={CascadeType.ALL}, fetch = FetchType.LAZY, targetEntity = Utilisateur.class)
#JoinColumn(name="userUtilisateur")
#JsonManagedReference
private Utilisateur userUtilisateur;
/*.. getters and setters..*/ }
and
#Entity
#Table(name="utilisateur")
public class Utilisateur {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "firstName")
private String firstName;
#Column(name = "lastName")
private String lastName;
private String fullName;
#Column(name = "age")
private int age;
#OneToMany(mappedBy="utilisateur", targetEntity = Ticket.class, cascade=CascadeType.ALL, fetch=FetchType.EAGER)
#JsonBackReference
private Set<Ticket> tickets = new HashSet<Ticket>(0);
#OneToMany(mappedBy="utilisateur", targetEntity=UserAssignProject.class, cascade=CascadeType.ALL, fetch=FetchType.EAGER)
#JsonBackReference
private Set<UserAssignProject> userAssignProjects = new HashSet<UserAssignProject>(0);
#OneToMany(mappedBy="utilisateur", targetEntity=Message.class, cascade=CascadeType.ALL, fetch=FetchType.EAGER)
#JsonBackReference
private Set<Message> messages = new HashSet<Message>(0);
/*.. getters and setters..*/ }
I have this method in UserDaoImpl:
public void save(User user) {
Utilisateur utilisateur = new Utilisateur();
user.setId(user.getId());
user.setUsername(user.getUsername());
user.setPassword(user.getPassword());
user.setEnabled(true);
user.setUserUtilisateur(utilisateur);
getCurrentSession().save(user);
}
Results:
Exception here
I've tried to use sequence, GenerationType.AUTO..., but it's not working.
Any solutions?
Thanks for your attention!

Why Hibernate ManyToOne is not persisted correctly?

I have two entities User and Wish :
#Entity
#Table(name = "T_USER")
public class User implements Serializable {
#Column(length = 50)
private String lastname;
#Column(length = 50)
private String firstname;
#OneToMany(mappedBy = "user",cascade = CascadeType.ALL,fetch = FetchType.EAGER)
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Wish> wishes = new HashSet<Wish>();
// getters and setters
}
#Entity
#Table(name = "T_WISH")
public class Wish implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "title")
private String title;
#Column(name = "description")
private String description;
#ManyToOne
private User user;
// getters and setters
}
When i save the user, recruiter_id is null why. I've tried :
Wish wish = wishRepository.save(wish);
user.getWishes.add(wish);
User userSaved = userRepository.save(user);
Why the recruiter_id is not set.
Your user class does not have #Id anottated field.

Categories