I want to assign role to a new user, the role is called ROLE_USER in database and has an id of 3. but I dont know how to pass that value in method save(). At the bottom, I throw the most important classes and save method.
User model class
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(nullable = false)
private String firstName;
#Column(nullable = false)
private String lastName;
#Column(nullable = false, unique = true)
private String email;
#Column(nullable = false)
private String password;
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(
name = "user_role",
joinColumns = {#JoinColumn(name = "USER_ID", referencedColumnName = "ID")},
inverseJoinColumns = {#JoinColumn(name = "ROLE_ID", referencedColumnName = "ID")})
private List<Role> roles;
public User(String firstName, String lastName, String email, String password, List<Role> roles) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.password = password;
this.roles = roles;
}
Getters and setters ...
Role model class
#Entity
#Data
#Table(name = "roles")
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(unique = true)
#NotNull
private String name;
#ManyToMany(mappedBy="roles")
private List<Role> users;
}
UserRegistrationDto class
public class UserRegistrationDto {
private String firstName;
private String lastName;
private String email;
private String password;
private List<Role> roles;
}
method for save in UserService class
public User save(UserRegistrationDto registrationDto) {
User user = new User(registrationDto.getFirstName(),
registrationDto.getLastName(),
registrationDto.getEmail(),
passwordEncoder.encode(registrationDto.getPassword()),
ROLE ???);
return userRepository.save(user);
}
Related
How to get emailId From User table in the OrderServiceImpl.java class so that it can be sent
as a String while calling sendTextEmail(String email) in
OrderServiceImpl.java class?
User.java Class
#Setter
#Getter
#EqualsAndHashCode
#ToString
#NoArgsConstructor
//#AllArgsConstructor
#Entity
#Table(name = "`user`", uniqueConstraints = {#UniqueConstraint(columnNames = "email")})
public class User {
public User(String email, String name, String password, String address) {
this.email = email;
this.name = name;
this.password = password;
this.address = address;
}
#Id
#Column(name = "userId")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Size(max = 50)
#Email
private String email;
#Size(max = 50)
#NotBlank
private String name;
#Size(max = 100)
#NotBlank
private String password;
#Size(max = 50)
#NotBlank
private String address;
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(name = "cart", joinColumns = #JoinColumn(name = "userId"),
inverseJoinColumns = #JoinColumn(name = "foodId"))
private List<Food> cart = new ArrayList<Food>();
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(name = "user_roles", joinColumns = #JoinColumn(name = "userId"),
inverseJoinColumns = #JoinColumn(name = "roleId"))
private Set<Role> roles = new HashSet<Role>();
}
Order.java Class
#Setter
#Getter
#EqualsAndHashCode
#ToString
#NoArgsConstructor
//#AllArgsConstructor
#Entity
#Table(name = "orders", uniqueConstraints = {#UniqueConstraint(columnNames = "orderTransaction")})
public class Order {
#Id
#Column(name = "orderId")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Size(max = 50)
#NotBlank
private String orderTime;
#Size(max = 50)
#NotBlank
private String orderTransaction;
#OneToMany(fetch = FetchType.LAZY)
#JoinTable(name = "users_orders", joinColumns = #JoinColumn(name = "orderId"),
inverseJoinColumns = #JoinColumn(name = "userId"))
private List<Order> orders = new ArrayList<Order>();
}
EmailServiceImpl.java Class
#Service
public class EmailServiceImpl implements EmailService {
private static final Logger logger = LoggerFactory
.getLogger(EmailServiceImpl.class);
#Autowired
private JavaMailSender javaMailSender;
#Override
//Sending User Object
public void sendTextEmail(String email) {
logger.info("Simple Email sending start");
SimpleMailMessage simpleMessage = new SimpleMailMessage();
simpleMessage.setTo(email); //Enter customer email
simpleMessage.setSubject("Spring Boot=> Sending simple email");
simpleMessage.setText("Dear hunger buddy customer Hope you are doing well.");
javaMailSender.send(simpleMessage);
logger.info("Simple Email sent");
}
}
OrderServiceImpl.java Class
#Service
public class OrderServiceImpl implements OrderService{
private static final String String = null;
#Autowired
private EmailService emailService;
#Autowired
private OrderRepo orderRepo;
/*#Autowired
private User register;*/
#Override
public Order addOrder(Order order) throws AlreadyExistsException {
if(orderRepo.existsById(order.getId())) {
throw new AlreadyExistsException("This record already exists");
}
else
{
//long temp=order.getId();
//Optional<User> optional = userRepo.findById(temp);
String email = null;
emailService.sendTextEmail(email);
return orderRepo.save(order);
}
}
#Override
public Optional<List<Order>> getAllOrder() {
return Optional.ofNullable(orderRepo.findAll());
}
#Override
public Optional<Order> getOrderById(Long id) throws IdNotFoundException {
Optional<Order> optional = orderRepo.findById(id);
if (!optional.isPresent()) {
throw new IdNotFoundException("Sorry Order Not Found");
}
return optional;
}
}
I have removed all the import statement to save the time of reader.
ThankYou
I think you have a logical issue in Order entity definition. Order does not contain another list of Orders. But it should contain the User who placed the order. Hence, the definition should be corrected as follows:
#Setter
#Getter
#EqualsAndHashCode
#ToString
#NoArgsConstructor
#Entity
#Table(name = "orders", uniqueConstraints = {#UniqueConstraint(columnNames = "orderTransaction")})
public class Order {
#Id
#Column(name = "orderId")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Size(max = 50)
#NotBlank
private String orderTime;
#Size(max = 50)
#NotBlank
private String orderTransaction;
#OneToOne(fetch = FetchType.LAZY)
#JoinTable(name = "users_orders", joinColumns = #JoinColumn(name = "orderId"),
inverseJoinColumns = #JoinColumn(name = "userId"))
private User user;
}
Then in OrderServiceImpl you could access user information with following:
User user = order.getUser();
String emailId = user.getEmail();
I am working on a Spring Boot project using Spring Data JPA trying to adopt the "query by method name" style in order to define my queries into repositories.
I am finding some difficulties trying to implement a select query retrieving the list of objects based on two different "where condition". I will try to explain what I have to do.
First of all this is my main entity class named Wallet:
#Entity
#Table(name = "wallet")
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Wallet implements Serializable {
private static final long serialVersionUID = 6956974379644960088L;
#Id
#Column(name = "id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#Column(name = "address")
private String address;
#Column(name = "notes")
private String notes;
#ManyToOne
#EqualsAndHashCode.Exclude // Needed by Lombock in "Many To One" relathionship to avoid error
#JoinColumn(name = "fk_user_id", referencedColumnName = "id")
#JsonBackReference(value = "user-wallets")
private User user;
#ManyToOne
#EqualsAndHashCode.Exclude // Needed by Lombock in "Many To One" relathionship to avoid error
#JoinColumn(name = "fk_coin_id", referencedColumnName = "id")
private Coin coin;
#ManyToOne
#JoinColumn(name = "type", referencedColumnName = "id")
private WalletType walletType;
public Wallet(String address, String notes, User user, Coin coin, WalletType walletType) {
super();
this.address = address;
this.notes = notes;
this.user = user;
this.coin = coin;
this.walletType = walletType;
}
}
As you can see a wallet is directly binded to a specific User object and to a specific Coin object.
For completeness this is the code of my User entity class:
#Entity
#Table(name = "portal_user")
#Getter
#Setter
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class User implements Serializable {
private static final long serialVersionUID = 5062673109048808267L;
#Id
#Column(name = "id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
#Column(name = "first_name")
#NotNull(message = "{NotNull.User.firstName.Validation}")
private String firstName;
#Column(name = "middle_name")
private String middleName;
#Column(name = "surname")
#NotNull(message = "{NotNull.User.surname.Validation}")
private String surname;
#Column(name = "sex")
#NotNull(message = "{NotNull.User.sex.Validation}")
private char sex;
#Column(name = "birthdate")
#NotNull(message = "{NotNull.User.birthdate.Validation}")
private Date birthdate;
#Column(name = "tax_code")
#NotNull(message = "{NotNull.User.taxCode.Validation}")
private String taxCode;
#Column(name = "e_mail")
#NotNull(message = "{NotNull.User.email.Validation}")
private String email;
#Column(name = "pswd")
#NotNull(message = "{NotNull.User.pswd.Validation}")
private String pswd;
#Column(name = "contact_number")
#NotNull(message = "{NotNull.User.contactNumber.Validation}")
private String contactNumber;
#Temporal(TemporalType.DATE)
#Column(name = "created_at")
private Date createdAt;
#Column(name = "is_active")
private boolean is_active;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "user", orphanRemoval = true)
#JsonManagedReference(value = "address")
private Set<Address> addressesList = new HashSet<>();
#ManyToMany(cascade = { CascadeType.MERGE })
#JoinTable(
name = "portal_user_user_type",
joinColumns = { #JoinColumn(name = "portal_user_id_fk") },
inverseJoinColumns = { #JoinColumn(name = "user_type_id_fk") }
)
private Set<UserType> userTypes;
#ManyToOne(fetch = FetchType.LAZY)
#JsonProperty("subagent")
private User parent;
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "user", orphanRemoval = true)
#JsonManagedReference(value = "user-wallets")
private Set<Wallet> wallets = new HashSet<>();
public User() {
super();
// TODO Auto-generated constructor stub
}
public User(String firstName, String middleName, String surname, char sex, Date birthdate, String taxCode,
String email, String pswd, String contactNumber, Date createdAt, boolean is_active) {
super();
this.firstName = firstName;
this.middleName = middleName;
this.surname = surname;
this.sex = sex;
this.birthdate = birthdate;
this.taxCode = taxCode;
this.email = email;
this.pswd = pswd;
this.contactNumber = contactNumber;
this.createdAt = createdAt;
this.is_active = is_active;
}
}
and this is the code of my Coin entity class:
#Entity
#Table(name = "coin")
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Coin implements Serializable {
private static final long serialVersionUID = 6956974379644960088L;
#Id
#Column(name = "id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#Column(name = "name")
#NotNull(message = "{NotNull.Coin.name.Validation}")
private String name;
#Column(name = "description")
private String description;
#Column(name = "code", unique = true)
#NotNull(message = "{NotNull.Coin.code.Validation}")
private String code;
#Type(type="org.hibernate.type.BinaryType")
#Column(name = "logo")
private byte[] logo;
}
Then I have this WalletRepository interface:
public interface WalletRepository extends JpaRepository<Wallet, Integer> {
}
Here I need to define a query by name method that retrieve a specific wallet of a specific User (I think that I can query by the id field of the User) and based and related to a specific Coin (I think that I can query by the id fied of the Coin).
How can I implement a behavior like this?
The following should work:
public interface WalletRepository extends JpaRepository<Wallet, Integer> {
List<Wallet> findByUserIdAndCoinId();
}
You can read more about this at:
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.query-creation
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repository-query-keywords
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.
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!
I have following entity classes:
#MappedSuperclass
public class AbstractEntity implements Serializable, Comparable<AbstractEntity> {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
protected Integer id;
#Override
public int compareTo(AbstractEntity o) {
return this.toString().compareTo(o.toString());
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
#Entity
#Table(name = "ticket")
#NamedQueries({
#NamedQuery(name = "Ticket.findAll", query = "SELECT t FROM Ticket t")})
public class Ticket extends AbstractEntity {
#Column(name = "title")
private String title;
#Column(name = "description")
private String description;
#Enumerated(EnumType.STRING)
#Column(name = "status")
private TicketStatus status;
#Enumerated(EnumType.STRING)
#Column(name = "priority")
private TicketPriority priority;
#Column(name = "categories")
private String categories;
#Column(name = "views")
private Integer views;
#Column(name = "date_time_created")
#Temporal(TemporalType.TIMESTAMP)
private Date dateTimeCreated;
#Column(name = "date_time_modified")
#Temporal(TemporalType.TIMESTAMP)
private Date dateTimeModified;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "ticketId")
private List<TicketFollower> ticketFollowerList;
#JoinColumn(name = "project_id", referencedColumnName = "id")
#ManyToOne(optional = false)
private Project projectId;
#JoinColumn(name = "ticket_attachment_id", referencedColumnName = "id")
#ManyToOne
private TicketAttachment ticketAttachmentId;
#JoinColumn(name = "user_id", referencedColumnName = "id")
#ManyToOne(optional = false)
private User userId;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "ticketId")
private List<TicketComment> ticketCommentList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "ticketId")
private List<TicketAttachment> ticketAttachmentList;
#Inject
public Ticket() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
...
#Override
public String toString() {
return getTitle();
}
}
#Entity
#Table(name = "user")
#NamedQueries({
#NamedQuery(name = "User.findAll", query = "SELECT u FROM User u")})
public class User extends AbstractEntity {
#Enumerated(EnumType.STRING)
#Column(name = "role")
private Role role;
#Column(name = "username")
private String username;
#Column(name = "password")
private String password;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "email")
private String email;
#Column(name = "avatar_path")
private String avatarPath;
#Column(name = "date_time_registered")
#Temporal(TemporalType.TIMESTAMP)
private Date dateTimeRegistered;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userId")
private List<TicketFollower> ticketFollowerList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userId")
private List<Ticket> ticketList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userId")
private List<TicketComment> ticketCommentList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userId")
private List<ProjectFollower> projectFollowerList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userId")
private List<TicketAttachment> ticketAttachmentList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userId")
private List<Project> projectList;
#Inject
public User() {}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
I get this exception from creating a hibernate Criteria. In my TicketDao class I have a method which search ticket by username, and when I invoke code below
Criteria criteria = session.createCriteria(Ticket.class);
criteria.add(Restrictions.eq("userId.username", username));
it throws exception:
could not resolve property: userId.username of: com.entities.Ticket
However, when I write criteria like:
criteria.add(Restrictions.eq("userId.id", userId));
it does not show any exception and returns me result. Any idea why my syntax for criteria.add(Restrictions.eq("userId.username", username)); and other properties like firstname, last name is wrong ?
Criteria does not work like EL or Java methods or attributes, you cannot refer to inner objects with a dot ..
You have to create a restriction in Ticket, right? What does Ticket has? An User. Then... you have to create a new User, set the username to this User and then set the created User to Ticket's criteria:
Criteria criteria = session.createCriteria(Ticket.class);
User user = new User();
user.setUsername(username);
criteria.add(Restrictions.eq("user", user));