Related
I am trying to test my code in spring boot but I catch
java.lang.NullPointerException
exception when I run my code.
here are my Models:
package com.Loyalty.OpenLoyalty.Models.User;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import javax.swing.text.StyledEditorKit;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.Set;
#Entity
#Table(name = "ol__user")
#DynamicUpdate
#EntityListeners(AuditingEntityListener.class)
public class ol__user {
public ol__user() {
}
public ol__user(String first_name, String last_name, String Email, String username, String password, String dtype, Boolean is_active,ol__roles role,String salt,Timestamp create_at){
super();
this.first_name=first_name;
this.last_name=last_name;
this.password=password;
this.email=Email;
this.is_active=is_active;
this.username=username;
this.dtype=dtype;
this.role=role;
this.salt=salt;
this.create_at=create_at;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "system-uuid")
#GenericGenerator(name = "system-uuid", strategy = "uuid")
#Column(name = "id", unique = true, nullable = false)
private String id;
#Column(name = "username", nullable = true)
private String username;
#Column(name = "password", nullable = false)
private String password;
#Column(name = "salt", nullable = true)
private String salt;
#Column(name = "is_active", nullable = false)
private Boolean is_active;
#Column(name = "create_at", nullable = true)
private Timestamp create_at;
#Column(name = "email", nullable = false)
private String email;
#Column(name = "password_requested_at", nullable = true)
private Timestamp password_requested_at;
#Column(name = "confirmation_token", nullable = true)
private String confirmation_token;
#Column(name = "deleted_at", nullable = true)
private Timestamp deleted_at;
#Column(name = "last_login_at", nullable = true)
private Timestamp last_login_at;
#Column(name = "dtype", nullable = false)
private String dtype;
#Column(name = "temporary_password_set_at", nullable = true)
private Timestamp temporary_password_set_at;
#Column(name = "action_token", nullable = true)
private String action_token;
#Column(name = "referral_customer_email", nullable = true)
private String referral_customer_email;
#Column(name = "newsletter_used_flag", nullable = true)
private Boolean newsletter_used_flag;
#Column(name = "phone", nullable = true)
private String phone;
#Column(name = "status_type", nullable = true)
private String status_type;
#Column(name = "status_state", nullable = true)
private String status_state;
#Column(name = "first_name", nullable = true)
private String first_name;
#Column(name = "last_name", nullable = true)
private String last_name;
#Column(name = "external", nullable = true)
private Boolean external;
#Column(name = "api_key", nullable = true)
private String api_key;
#Column(name = "allow_point_transfer", nullable = true)
private Boolean allow_point_transfer;
#ManyToOne(cascade = {CascadeType.ALL})
#JoinTable(name="ol__users_roles",
joinColumns={#JoinColumn(name="user_id")},
inverseJoinColumns={#JoinColumn(name="role_id")})
private ol__roles role;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
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 getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
public Boolean getIs_active() {
return is_active;
}
public void setIs_active(Boolean is_active) {
this.is_active = is_active;
}
public Timestamp getCreate_at() {
return create_at;
}
public void setCreate_at(Timestamp create_at) {
this.create_at = create_at;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Timestamp getPassword_requested_at() {
return password_requested_at;
}
public void setPassword_requested_at(Timestamp password_requested_at) {
this.password_requested_at = password_requested_at;
}
public String getConfirmation_token() {
return confirmation_token;
}
public void setConfirmation_token(String confirmation_token) {
this.confirmation_token = confirmation_token;
}
public Timestamp getDeleted_at() {
return deleted_at;
}
public void setDeleted_at(Timestamp deleted_at) {
this.deleted_at = deleted_at;
}
public Timestamp getLast_login_at() {
return last_login_at;
}
public void setLast_login_at(Timestamp last_login_at) {
this.last_login_at = last_login_at;
}
public String getDtype() {
return dtype;
}
public void setDtype(String dtype) {
this.dtype = dtype;
}
public Timestamp getTemporary_password_set_at() {
return temporary_password_set_at;
}
public void setTemporary_password_set_at(Timestamp temporary_password_set_at) {
this.temporary_password_set_at = temporary_password_set_at;
}
public String getAction_token() {
return action_token;
}
public void setAction_token(String action_token) {
this.action_token = action_token;
}
public String getReferral_customer_email() {
return referral_customer_email;
}
public void setReferral_customer_email(String referral_customer_email) {
this.referral_customer_email = referral_customer_email;
}
public Boolean getNewsletter_used_flag() {
return newsletter_used_flag;
}
public void setNewsletter_used_flag(Boolean newsletter_used_flag) {
this.newsletter_used_flag = newsletter_used_flag;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getStatus_type() {
return status_type;
}
public void setStatus_type(String status_type) {
this.status_type = status_type;
}
public String getStatus_state() {
return status_state;
}
public void setStatus_state(String status_state) {
this.status_state = status_state;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public Boolean getExternal() {
return external;
}
public void setExternal(Boolean external) {
this.external = external;
}
public String getApi_key() {
return api_key;
}
public void setApi_key(String api_key) {
this.api_key = api_key;
}
public Boolean getAllow_point_transfer() {
return allow_point_transfer;
}
public void setAllow_point_transfer(Boolean allow_point_transfer) {
this.allow_point_transfer = allow_point_transfer;
}
public ol__roles getRoles() {
return role;
}
public void setRoles(ol__roles role) {
this.role = role;
}
}
and
package com.Loyalty.OpenLoyalty.Models.User.Projections;
import com.Loyalty.OpenLoyalty.Models.User.ol__user;
import java.util.ArrayList;
import java.util.List;
public class ol__users {
private List<ol__user> usersList;
public List<ol__user> getUsersList(){
if (usersList== null){
usersList=new ArrayList<>();
}
return usersList;
}
public void setUsersList(List<ol__user> usersList){
this.usersList= usersList;
}
}
my controller:
#GetMapping("/admin")
public ol__users getAllAdminUsers( ){
return userService.getAllAdminUsers();
}
My Service:
#Service
public class userService {
#Autowired
private userRepository userRepository;
public ol__users getAllAdminUsers( ){
ol__users response = new ol__users();
ArrayList<ol__user> list=new ArrayList<>();
userRepository.find
Bydtype("admin").forEach(e ->list.add(e));
response.setUsersList(list);
return response;
}
}
and my repository:
#Repository
public interface userRepository extends JpaRepository<ol__user, String> {
List<ol__user> findBydtype(String dtype);
Optional<ol__user> findById(String id);
Boolean existsByUsername(String username);
ol__user findByUsername(String username);
ol__user findByEmail(String username);
ol__user findByEmailIgnoreCase(String email);
// #Query(value = "select count(*) as count from ol__user",nativeQuery = true)
}
and finally here is my test code:
ExtendWith(MockitoExtension.class)
#RunWith(MockitoJUnitRunner.class)
public class Ol_userControllerTest {
#InjectMocks
Ol__userController Ol__userController;
#Mock
userRepository userRepository;
#Mock
userService userService;
#Test
#Transactional
public void testFindAll(){
ol__roles role=new ol__roles();
role.setName("tests");
role.setRole("Admin");
role.setIs_master(true);
Timestamp currentSqlTimestamp = new Timestamp(System.currentTimeMillis());
ol__user user1=new ol__user("anteaaa","nejatiaan","anteeaaaa#yahoo.com","anteaaaaa","12345","admin",true,role,"123",currentSqlTimestamp);
ol__user user2=new ol__user("Nooria","Rajaee","Nooriaaaa#yahoo.com","Nooriaa","12345","admin",true,role,"123",currentSqlTimestamp);
List<ol__user> list = new ArrayList<ol__user>();
list.addAll(Arrays.asList(user1,user2));
Mockito.when(userRepository.findBydtype(any())).thenReturn(list);
//when
ol__users result = userService.getAllAdminUsers();
//then
assertThat(result.getUsersList().size()).isEqualTo(2);
assertThat(result.getUsersList().get(0).getFirst_name())
.isEqualTo(user1.getFirst_name());
}
}
I have debuted my code and I understood that
Mockito.when(userRepository.findBydtype(any())).thenReturn(list);
stores list in it but then in the next line my result object returns null and then the exception happens.
I wonder where my problem is?
Yes because you are testing the controller and injected mock to the controller, so the service in the controller is mocked and getAllAdminUsers() returns null.
you should write a test for the controller and another for service
ExtendWith(MockitoExtension.class)
#RunWith(MockitoJUnitRunner.class)
public class ControllerTest {
#InjectMocks
private Ol__userController Ol__userController;
#Mock
private userRepository userRepository;
#Mock
private userService userService;
#Test
public void testFindAll(){
// Arrange
ol__roles role=new ol__roles();
role.setName("tests");
role.setRole("Admin");
role.setIs_master(true);
Timestamp currentSqlTimestamp = new Timestamp(System.currentTimeMillis());
ol__user user1=new ol__user("anteaaa","nejatiaan","anteeaaaa#yahoo.com","anteaaaaa","12345","admin",true,role,"123",currentSqlTimestamp);
ol__user user2=new ol__user("Nooria","Rajaee","Nooriaaaa#yahoo.com","Nooriaa","12345","admin",true,role,"123",currentSqlTimestamp);
List<ol__user> list = new ArrayList<ol__user>();
list.addAll(Arrays.asList(user1,user2));
Mockito.when(ol__users result = userService.getAllAdminUsers()
).thenReturn(list);
// Act
List<ol__user> actual = Ol__userController.getAllAdminUsers();
// Assert
assertThat(actual.getUsersList().size()).isEqualTo(2);
assertThat(actual.getUsersList().get(0).getFirst_name())
.isEqualTo(user1.getFirst_name());
}
}
, Service test
ExtendWith(MockitoExtension.class)
#RunWith(MockitoJUnitRunner.class)
public class ServiceTest {
#InjectMocks
private userService userService;
#Mock
private userRepository userRepository;
#Test
public void testFindAll(){
// Arrange
ol__roles role=new ol__roles();
role.setName("tests");
role.setRole("Admin");
role.setIs_master(true);
Timestamp currentSqlTimestamp = new Timestamp(System.currentTimeMillis());
ol__user user1=new ol__user("anteaaa","nejatiaan","anteeaaaa#yahoo.com","anteaaaaa","12345","admin",true,role,"123",currentSqlTimestamp);
ol__user user2=new ol__user("Nooria","Rajaee","Nooriaaaa#yahoo.com","Nooriaa","12345","admin",true,role,"123",currentSqlTimestamp);
List<ol__user> list = new ArrayList<ol__user>();
list.addAll(Arrays.asList(user1,user2));
when(userRepository.findBydtype(any())).thenReturn(list);
// Act
ol__users result = userService.getAllAdminUsers();
//Assert
assertThat(result.getUsersList().size()).isEqualTo(2);
assertThat(result.getUsersList().get(0).getFirst_name())
.isEqualTo(user1.getFirst_name());
}
}
i'm new in spring.I have a project that name is SampleStore. some entities created in my projects, such as User, UserRole, Product, Orders, CartItem and .... but i have a problem. when i try add new user app does it without error and new record inserted in databse. but when i try to insert new order i'll get error.
User.java
#Entity
#Table(name = "users")
public class User implements Serializable, UserDetails {
private static final long serialVersionUID = -8245107356306518473L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false)
private Long id;
#Column(name = "username", nullable = false, unique = true, length = 50)
private String username;
#Column(name = "password", nullable = false, length = 60)
private String password;
#Column(name = "enabled", nullable = true, columnDefinition = "tinyint(1) default 1")
private boolean enabled;
#Column(name = "expired", nullable = true, columnDefinition = "tinyint(1) default 1")
private boolean accountNonExpired;
#Column(name = "locked", nullable = true, columnDefinition = "tinyint(1) default 1")
private boolean accountNonLocked;
#Column(name = "credential", nullable = true, columnDefinition = "tinyint(1) default 1")
private boolean credentialsNonExpired;
#Column(name = "gender", nullable = true)
private char gender;
#Column(name = "address", nullable = true)
private String address;
#Column(name = "phonenumber", nullable = true)
private String phoneNumber;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user")
private Set<UserRole> userRoles = new HashSet<UserRole>(0);
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user")
private List<Comment> comments = new ArrayList<Comment>();
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user")
private List<Orders> orders = new ArrayList<Orders>();
public User() {
}
public User(String username, String password, boolean enabled) {
this.username = username;
this.password = password;
this.enabled = enabled;
}
public User(String username, String password, boolean enabled, Set<UserRole> userRoles) {
this.username = username;
this.password = password;
this.enabled = enabled;
this.userRoles = userRoles;
}
public User(String username, String password, boolean enabled, boolean accountNonExpired,
boolean credentialsNonExpired, boolean accountNonLocked, Set<UserRole> authorities) {
this.username = username;
this.password = password;
this.enabled = enabled;
this.accountNonExpired = accountNonExpired;
this.credentialsNonExpired = credentialsNonExpired;
this.accountNonLocked = accountNonLocked;
this.userRoles = authorities;
}
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 boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public Set<UserRole> getUserRoles() {
return userRoles;
}
public void setUserRoles(Set<UserRole> userRoles) {
this.userRoles = userRoles;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public List<Comment> getComments() {
return comments;
}
public void setComments(List<Comment> comments) {
this.comments = comments;
}
public List<Orders> getOrders() {
return orders;
}
public void setOrders(List<Orders> orders) {
this.orders = orders;
}
#Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + ", enabled=" + enabled
+ ", gender=" + gender + ", address=" + address + ", phoneNumber=" + phoneNumber + ", userRoles="
+ userRoles + "]";
}
public Collection<? extends GrantedAuthority> getAuthorities() {
Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
for (UserRole userRole : userRoles) {
setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
}
List<GrantedAuthority> result = new ArrayList<GrantedAuthority>(setAuths);
return result;
}
public boolean isAccountNonExpired() {
return accountNonExpired;
}
public boolean isAccountNonLocked() {
return accountNonLocked;
}
public boolean isCredentialsNonExpired() {
return credentialsNonExpired;
}
public void setAccountNonExpired(boolean accountNonExpired) {
this.accountNonExpired = accountNonExpired;
}
public void setAccountNonLocked(boolean accountNonLocked) {
this.accountNonLocked = accountNonLocked;
}
public void setCredentialsNonExpired(boolean credentialsNonExpired) {
this.credentialsNonExpired = credentialsNonExpired;
}
}
UserRole.java
#Entity
#Table(name = "user_roles", uniqueConstraints = #UniqueConstraint(columnNames = { "username", "role" }))
public class UserRole {
private Integer userRoleId;
private User user;
private String role;
public UserRole() {
}
public UserRole(User user, String role) {
this.user = user;
this.role = role;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_role_id", unique = true, nullable = false)
public Integer getUserRoleId() {
return this.userRoleId;
}
public void setUserRoleId(Integer userRoleId) {
this.userRoleId = userRoleId;
}
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "username", nullable = false)
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
#Column(name = "role", nullable = false, length = 45)
public String getRole() {
return this.role;
}
public void setRole(String role) {
this.role = role;
}
}
Orders.java
#Entity
#Table(name = "orders")
public class Orders implements Serializable {
private static final long serialVersionUID = -3672662224925418969L;
#Id
#Column(name = "ord_id", nullable = false)
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#DateTimeFormat(pattern = "yyyy-mm-dd")
#Column(name = "orderDate", nullable = false)
private Date orderDate;
#DateTimeFormat(pattern = "yyyy-mm-dd")
#Column(name = "delivery", nullable = false)
private Date deliveryDate;
#Column(name = "success", nullable = true, columnDefinition = "tinyint(1) default 0")
private boolean success;
#Column(name = "cancel", nullable = true, columnDefinition = "tinyint(1) default 0")
private boolean canceled;
#Column(name = "cause", nullable = true)
private String cancelCause;
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "order")
private List<CartItem> items = new ArrayList<CartItem>();
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name="username",nullable=false)
private User user;
public Orders() {
}
public Orders(Date deliveryDate, List<CartItem> items, User user) {
this.orderDate = new Date();
this.deliveryDate = deliveryDate;
this.items = items;
this.user = user;
}
public Orders(List<CartItem> items, User user) {
this.orderDate = new Date();
this.items = items;
this.user = user;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public Date getDeliveryDate() {
return deliveryDate;
}
public void setDeliveryDate(Date deliveryDate) {
this.deliveryDate = deliveryDate;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public boolean isCanceled() {
return canceled;
}
public void setCanceled(boolean canceled) {
this.canceled = canceled;
}
public String getCancelCause() {
return cancelCause;
}
public void setCancelCause(String cancelCause) {
this.cancelCause = cancelCause;
}
public List<CartItem> getItems() {
return items;
}
public void setItems(List<CartItem> items) {
this.items = items;
}
}
CartItem.java
#Entity
#Table(name = "saleitems", uniqueConstraints = {})
public class CartItem implements Serializable {
private static final long serialVersionUID = 7968604053015663078L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(nullable = false)
private Long id;
#Column(name = "prd_id", nullable = false)
private Product product;
#Column(name = "quantity", nullable = false, columnDefinition = "int(11) default 1")
private Integer quantity;
#Column(name = "totalprice", nullable = false)
private BigDecimal totalprice;
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "orderid", nullable = false)
private Orders order;
public CartItem(Product product, Integer quantity) {
this.product = product;
this.quantity = quantity;
setTotalprice();
}
public CartItem() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public BigDecimal getTotalprice() {
return totalprice;
}
public void setTotalprice() {
this.totalprice = getProduct().getPrice().multiply(new BigDecimal(getQuantity()));
}
public Orders getOrder() {
return order;
}
public void setOrder(Orders order) {
this.order = order;
}
}
here one part of my controller code that user to save new user and save new order.
#RequestMapping(value = "/saveuser", method = RequestMethod.POST)
public ModelAndView saveNewUser(#ModelAttribute User user) {
ModelAndView model = new ModelAndView();
user.setEnabled(true);
user.setAccountNonExpired(true);
user.setAccountNonLocked(true);
user.setCredentialsNonExpired(true);
UserRole role = new UserRole(user, "ROLE_USER");
Set<UserRole> roles = new HashSet<UserRole>();
roles.add(role);
user.setUserRoles(roles);
String result = userService.addUser(user);
if (!result.toLowerCase().startsWith("error")) {
model.setViewName("loginForm");
} else {
model.setViewName("newuser");
model.addObject("error", result);
}
return model;
}
#SuppressWarnings("unchecked")
#RequestMapping(value = "/store/addorder", method = RequestMethod.GET)
public ModelAndView addOrder(HttpSession session) {
ModelAndView model = new ModelAndView();
// create list of products that we have to add in orders
System.err.println("item get to retrieving---------------");
List<CartItem> items = (List<CartItem>) session.getAttribute("cart");
for (CartItem cartItem : items) {
System.err.println(cartItem.getProduct());
}
// find user by username to set orders userinfo
System.err.println("user information get to retriving---------------");
String username = SecurityContextHolder.getContext().getAuthentication().getName();
User user = userService.findByUsername(username);
System.err.println(user);
// new order generated and setter methods invoke
System.err.println("new order generated-------------------");
Orders order = new Orders(items, user);
Date d = new Date();
Date delivery = StoreUtils.deliveryDate(d, 3);
order.setOrderDate(d);
order.setDeliveryDate(delivery);
order.setUser(user);
order.setItems(items);
String addOrders = orderService.addOrders(order);
System.err.println("new order add status " + addOrders + "-------------");
System.err.println(order);
// change product quantity after adding new order
for (int i = 0; i < items.size(); i++) {
Integer qSale = items.get(i).getQuantity() * (-1);
productService.rechargeProduct(items.get(i).getProduct(), qSale);
}
if (!addOrders.toLowerCase().contains("error")) {
model.setViewName("successorder");
model.addObject("order", order);
model.addObject("message", addOrders);
session.setAttribute("cart", null);
} else {
session.setAttribute("error", addOrders);
model.setViewName("redirect:/addtocartlist");
}
return model;
}
finally, here my code in dao class that save user and order.
UserDaoImpl.java
public String addUser(User user) {
String result = "";
String pass = encoder.encode(user.getPassword());
user.setPassword(pass);
try {
session().save(user);
session().flush();
result = "success";
} catch (Exception e) {
if (e.getCause().getMessage().toLowerCase().contains("duplicate"))
result = "error :user is already joined to store!";
else
result = "error :" + e.getCause().getMessage();
}
return result;
}
OrderDaoImpl.java
public String addOrders(Orders orders) {
String result = "";
try {
session().save(orders);
result = "success";
} catch (Exception e) {
if (e.getCause() != null)
if (e.getCause().getMessage().toLowerCase().contains("duplicate"))
result = "error this order already was exist";
else
result = "error " + e.getCause().getMessage();
else {
result = "error " + e.getMessage();
}
System.err.println(result);
} finally {
session().clear();
}
return result;
}
All codes are similar, but results are diffrent. when try to add new order I get this exception:
not-null property references a null or transient value:com.softup.store.entity.CartItem.order
Set both sides of relation. On every item call setOrder(). On user setOrder() also.
I'm running a query via Hibernate and it´s returning a list. But the list contains objects instead of my Entities... I'm not a pro in Hibernate, but my other queries work well. I have got no idea what is my mistake right now.
List getAllUsersBasedOnMandant(Long id) {
List users = null;
try {
startOperation(false);
Query query = getSession().createQuery(" from UserEntity where mandant = '" + id + "'");
users = query.list();
} catch (HibernateException e) {
handleException(e);
} finally {
getSession().close();
}
return users;
}
My output looks like this:
[int_plan.entity.UserEntity#4b82b237, int_plan.entity.UserEntity#7141a0bb, int_plan.entity.UserEntity#65b0a12c]
My entity looks like that:
#Entity
#Table(name = "user", schema = "entw_pares")
public class UserEntity {
#Expose() private Long userId;
#Expose() private String gender;
#Expose() private String firstname;
#Expose() private String lastname;
#Expose() private String username;
#Expose() private String email;
private String password;
private String secQuestion;
private String secAnswer;
private String saltAnswer;
private String salt;
private String emailValidationCode;
private Long expireTime;
private Boolean emailEnable = false;
#Expose() private Timestamp dateCreated;
#Expose() private Timestamp dateUpdated;
private Boolean admin = false;
private MandantEntity mandantEntity;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_id", nullable = false)
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
#Basic
#Column(name = "gender", nullable = false)
public String getGender() { return gender; }
public void setGender(String gender){
this.gender = gender;
}
#Basic
#Column(name = "firstname", nullable = false)
public String getFirstname() { return firstname; }
public void setFirstname(String firstnme) { this.firstname = firstnme; }
#Basic
#Column(name = "lastname", nullable = false)
public String getLastname() { return lastname; }
public void setLastname(String lastname) { this.lastname = lastname; }
#Basic
#Column(name = "username")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Basic
#Column(name = "email", nullable = false)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Basic
#Column(name = "password", nullable = false)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Basic
#Column(name = "sec_question")
public String getSecQuestion() { return secQuestion; }
public void setSecQuestion(String sec_question) { this.secQuestion =
sec_question; }
#Basic
#Column(name = "sec_answer")
public String getSecAnswer() { return secAnswer; }
public void setSecAnswer(String secAnswer) { this.secAnswer = secAnswer; }
#Basic
#Column(name = "salt_answer")
public String getSaltAnswer() { return saltAnswer; }
public void setSaltAnswer(String saltAnswer) { this.saltAnswer = saltAnswer;
}
#Basic
#Column(name = "salt")
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
#Basic
#Column(name = "email_validation_code")
public String getEmailValidationCode() {
return emailValidationCode;
}
public void setEmailValidationCode(String emailValidationCode) {
this.emailValidationCode = emailValidationCode;
}
#Basic
#Column(name = "expire_time", nullable = false)
public Long getExpireTime() {
return expireTime;
}
public void setExpireTime(Long expireTime) {
this.expireTime = expireTime;
}
#Basic
#Column(name = "email_enable")
public Boolean getEmailEnable() {
return emailEnable;
}
public void setEmailEnable(Boolean emailEnable) {
this.emailEnable = emailEnable;
}
#Basic
#CreationTimestamp
#Column(name = "date_created")
public Timestamp getDateCreated() {
return dateCreated;
}
public void setDateCreated(Timestamp dateCreated) {
this.dateCreated = dateCreated;
}
#Basic
#UpdateTimestamp
#Column(name = "date_updated")
public Timestamp getDateUpdated() {
return dateUpdated;
}
public void setDateUpdated(Timestamp dateUpdated) {
this.dateUpdated = dateUpdated;
}
#Basic
#Column(name = "admin")
public Boolean getAdmin() {
return admin;
}
public void setAdmin(Boolean admin) {
this.admin = admin;
}
public void applyValue(Field field, Object value) throws
IllegalAccessException {
field.set(this, value);
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserEntity that = (UserEntity) o;
return userId == that.userId &&
Objects.equals(gender, that.gender)&&
Objects.equals(firstname,that.firstname)&&
Objects.equals(lastname,that.lastname)&&
Objects.equals(username, that.username) &&
Objects.equals(email, that.email) &&
Objects.equals(password, that.password) &&
Objects.equals(secQuestion,that.secQuestion) &&
Objects.equals(secAnswer, that.secAnswer) &&
Objects.equals(salt, that.salt) &&
Objects.equals(emailValidationCode, that.emailValidationCode) &&
Objects.equals(emailEnable, that.emailEnable) &&
Objects.equals(dateCreated, that.dateCreated) &&
Objects.equals(dateUpdated, that.dateUpdated) &&
Objects.equals(admin, that.admin);
}
#Override
public int hashCode() {
return Objects.hash(userId, gender, firstname, lastname, username, email,
password, secQuestion, secAnswer,
salt,
emailValidationCode,
emailEnable,
dateCreated, dateUpdated, admin);
}
#ManyToOne
#JoinColumn(name = "mandant_id", referencedColumnName = "mandant_id")
public MandantEntity getMandant() {
return mandantEntity;
}
public void setMandant(MandantEntity mandant) {
this.mandantEntity = mandant;
}
Any ideas what im doing wrong?
I hope I understood the question correctly and that my answer will help you.
Please use query.setParameter([name of parameter], [value]) it will help you with the concationation. more details on that link: https://www.mkyong.com/hibernate/hibernate-parameter-binding-examples/
Your Entitys are now Objects in the users List. you can define your List already to the Objecttype of your desire, for example List<UserEntity> users = q.getResultList()
2.a now you can adress the single elements in your list like
if(!users.isEmpty()) {
for(UserEntity uEntity : users){
uEntity.doSomething()
}
return users.get(0)}
I hope this was helpful for you
I'm trying to login with users from database, but I have this error. I think the problem appears in class "UserDetailsServiceImpl". What I have to do to fix this error? I will be grateful for any hint or idea...........................................................................
2018-03-16 11:13:40.389 ERROR 6520 --- [nio-8080-exec-5]
w.a.UsernamePasswordAuthenticationFilter : An internal error occurred while trying to authenticate the user.org.springframework.security.authentication.InternalAuthenticationServiceException: failed to lazily initialize a collection of role: com.continental.qtools.fingerprints.models.User.roles, could not initialize proxy - no Session
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:126) ~[spring-security-core-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:144) ~[spring-security-core-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174) ~[spring-security-core-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:199) ~[spring-security-core-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
This is entity "User"
#Entity
#Table(name = "users")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "user_id")
#GeneratedValue(strategy = GenerationType.AUTO)
private int userId;
#Column(name = "username")
#NotEmpty(message = "*Please provide your username")
private String username;
#Column(name = "password")
#Length(min = 5, message = "*Your password must have at least 5 characters")
#NotEmpty(message = "*Please provide your password")
private String password;
#Column(name = "email")
#Email(message = "*Please provide a valid Email")
#NotEmpty(message = "*Please provide an email")
private String email;
#Transient
private String passwordConfirm;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "users_roles", joinColumns = #JoinColumn(name = "user_id"), inverseJoinColumns = #JoinColumn(name = "role_id"))
private Set<Role> roles;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "users_projects", joinColumns = #JoinColumn)
private List<Project> projects;
public User(String username, String password, String email, String passwordConfirm, Set<Role> roles,
List<Project> projects) {
super();
this.username = username;
this.password = password;
this.email = email;
this.passwordConfirm = passwordConfirm;
this.roles = roles;
this.projects = projects;
}
public User() {
// TODO Auto-generated constructor stub
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getUserId() {
return userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPasswordConfirm() {
return passwordConfirm;
}
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<Project> getProjects() {
return projects;
}
public void setProjects(List<Project> projects) {
this.projects = projects;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
#Override
public String toString() {
return "User [username=" + username + ", password=" + password + ", email=" + email + ", passwordConfirm="
+ passwordConfirm + ", roles=" + roles + ", projects=" + projects + "]";
}
}
This is entity "Role"
#Entity
#Table(name = "roles")
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "role_id")
private int id;
#Column(name = "role")
private String role;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
UserDetailsServiceImp
#Service
public class UserDetailsServiceImpl implements UserDetailsService {
#Autowired
private UserRepository userRepository;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
System.out.println("User: " + user.getUsername());
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
for (Role role : user.getRoles()) {
grantedAuthorities.add(new SimpleGrantedAuthority(role.getRole()));
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
grantedAuthorities);
}
}
Try adding a FetchType.EAGER to the roles property on the user object.
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(name = "users_roles",
joinColumns = #JoinColumn(name = "user_id"),
inverseJoinColumns = #JoinColumn(name = "role_id")
)
private Set<Role> roles;
Update: Alternative refactor with Privileges included
Authority Class instead of Role Class
#Entity
#Table(name = "authority")
#JsonInclude(JsonInclude.Include.NON_NULL)
public class Authority implements GrantedAuthority {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
#ManyToMany
#JoinTable(
name = "authorities_privileges",
joinColumns = #JoinColumn(
name = "authority_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(
name = "privilege_id", referencedColumnName = "id"))
private Collection<Privilege> privileges;
public Authority() {
super();
}
public Authority(final String name) {
super();
this.name = name;
}
public Authority(String name,
Collection<Privilege> privileges) {
this.name = name;
this.privileges = privileges;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Collection<Privilege> getPrivileges() {
return privileges;
}
public void setPrivileges(Collection<Privilege> privileges) {
this.privileges = privileges;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (obj.toString().equals(this.name)) {
return true;
}
if (getClass() != obj.getClass()) {
return false;
}
final Authority auth = (Authority) obj;
if (this.name != null && this.name.equals(auth.name)) {
return true;
}
return false;
}
#Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Role [name=").append(name).append("]").append("[id=").append(id).append("]");
return builder.toString();
}
#Override
#JsonIgnore
public String getAuthority() {
return name;
}
}
Privilege Class (Optional)
#Entity
#JsonInclude(JsonInclude.Include.NON_NULL)
public class Privilege {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
private String name;
public Privilege() {
super();
}
public Privilege(final String name) {
super();
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
User Class
#Entity
#Table(name = "user_account")
public class User implements UserDetails {
#Id
#Column(unique = true, nullable = false)
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "username")
private String username;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "email")
private String email;
#JsonIgnore
#Column(name = "password", length = 60)
private String password;
#Column(name = "enabled")
private boolean enabled;
#Column(name = "last_password_reset_date")
private Timestamp lastPasswordResetDate;
#Column(name = "is_using_2FA")
private boolean isUsing2FA;
#JsonIgnore
#Column(name = "secret", length = 60)
private String secret;
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(name = "user_authority",
joinColumns = #JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "authority_id", referencedColumnName = "id"))
private Collection<Authority> authorities;
public User() {
this.secret = UUID.randomUUID().toString();
this.enabled = false;
}
public User(Long id,
String username, String firstName, String lastName,
String email, String password,
boolean enabled, Timestamp lastPasswordResetDate,
boolean isUsing2FA, String secret,
Collection<Authority> authorities) {
this.id = id;
this.username = username;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.password = password;
this.enabled = enabled;
this.lastPasswordResetDate = lastPasswordResetDate;
this.isUsing2FA = isUsing2FA;
this.secret = secret;
this.authorities = authorities;
}
public Long getId() {
return id;
}
public void setId(final Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(final String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(final String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(final String username) {
this.email = username;
}
public String getPassword() {
return password;
}
public void setPassword(final String password) {
Date date = new Date();
this.lastPasswordResetDate = new Timestamp(date.getTime());
this.password = password;
}
#Override
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public boolean isUsing2FA() {
return isUsing2FA;
}
public void setUsing2FA(boolean isUsing2FA) {
this.isUsing2FA = isUsing2FA;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.authorities;
}
#Override
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Timestamp getLastPasswordResetDate() {
return lastPasswordResetDate;
}
public void setLastPasswordResetDate(Timestamp lastPasswordResetDate) {
this.lastPasswordResetDate = lastPasswordResetDate;
}
#JsonIgnore
#Override
public boolean isAccountNonExpired() {
return true;
}
#JsonIgnore
#Override
public boolean isAccountNonLocked() {
return true;
}
#JsonIgnore
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = (prime * result) + ((username == null) ? 0 : username.hashCode());
return result;
}
#Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final User user = (User) obj;
if (!username.equals(user.username)) {
return false;
}
return true;
}
#Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("User [id=").append(id).append(", firstName=").append(firstName).append(", lastName=").append(lastName).append(", email=").append(email).append(", password=").append(password).append(", enabled=").append(enabled).append(", isUsing2FA=")
.append(isUsing2FA).append(", secret=").append(secret).append(", roles=").append(authorities).append("]");
return builder.toString();
}
}
UserBuilder Class
public class UserBuilder {
private Long bId;
private String bUsername;
private String bFirstName;
private String bLastName;
private String bEmail;
private String bPassword;
private boolean bEnabled;
private Timestamp bLastPasswordResetDate;
private boolean bIsUsing2FA;
private String bSecret;
private Collection<Authority> bAuthorities;
public UserBuilder() {
}
public UserBuilder(Long bId,
String bUsername, String bFirstName, String bLastName,
String bEmail, String bPassword, boolean bEnabled,
Timestamp bLastPasswordResetDate, boolean bIsUsing2FA, String bSecret,
Collection<Authority> authorities) {
this.bId = bId;
this.bUsername = bUsername;
this.bFirstName = bFirstName;
this.bLastName = bLastName;
this.bEmail = bEmail;
this.bPassword = bPassword;
this.bEnabled = bEnabled;
this.bLastPasswordResetDate = bLastPasswordResetDate;
this.bIsUsing2FA = bIsUsing2FA;
this.bSecret = bSecret;
this.bAuthorities = bAuthorities;
}
public UserBuilder(User user) {
this.bId = user.getId();
this.bUsername = user.getUsername();
this.bFirstName = user.getFirstName();
this.bLastName = user.getLastName();
this.bEmail = user.getEmail();
this.bPassword = user.getPassword();
this.bEnabled = user.isEnabled();
this.bLastPasswordResetDate = user.getLastPasswordResetDate();
this.bIsUsing2FA = user.isUsing2FA();
this.bSecret = user.getSecret();
}
public User createUser() {
return new User(bId,
bUsername,
bFirstName,
bLastName,
bEmail,
bPassword,
bEnabled,
bLastPasswordResetDate,
bIsUsing2FA,
bSecret,
bAuthorities
);
}
public UserBuilder bId(Long bId) {
this.bId = bId;
return this;
}
public UserBuilder bUsername(String bUsername) {
this.bUsername = bUsername;
return this;
}
public UserBuilder bFirstName(String bFirstName) {
this.bFirstName = bFirstName;
return this;
}
public UserBuilder bLastName(String bLastName) {
this.bLastName = bLastName;
return this;
}
public UserBuilder bEmail(String bEmail) {
this.bEmail = bEmail;
return this;
}
public UserBuilder bPassword(String bPassword) {
Date date = new Date();
this.bLastPasswordResetDate = new Timestamp(date.getTime());
this.bPassword = bPassword;
return this;
}
public UserBuilder bEnabled(boolean bEnabled) {
this.bEnabled = bEnabled;
return this;
}
public UserBuilder bLastPasswordResetDate(Timestamp bLastPasswordResetDate) {
this.bLastPasswordResetDate = bLastPasswordResetDate;
return this;
}
public UserBuilder bIsUsing2FA(boolean bIsUsing2FA) {
this.bIsUsing2FA = bIsUsing2FA;
return this;
}
public UserBuilder bSecret(String bSecret) {
this.bSecret = bSecret;
return this;
}
public UserBuilder bAuthorities(Collection<Authority> bAuthorities) {
this.bAuthorities = bAuthorities;
return this;
}
}
CustomUserDetailsService Class
#Service("userDetailsService")
#Transactional
public class CustomUserDetailsService implements UserDetailsService {
#Autowired
private UserRepository userRepository;
#SuppressWarnings("unchecked")
#Override
public UserDetails loadUserByUsername(final String identity) throws UsernameNotFoundException {
try {
final User user = Optional.ofNullable(userRepository.findByEmail(identity)).orElseGet(() -> userRepository.findByUsername(identity));
if (user == null) {
throw new UsernameNotFoundException("No user found with username: " + identity);
}
//Collection<Authority> authorities = getAuthorities((Collection<Authority>) user.getAuthorities());
Collection<Authority> authorities = getAuthorities((Collection<Authority>) user.getAuthorities());
return new UserBuilder(user).bAuthorities(authorities).createUser();
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
private final Collection<Authority> getAuthorities(final Collection<Authority> authorityList) {
return getGrantedAuthorities(getAuthorityList(authorityList));
}
private final List<String> getAuthorityList(final Collection<Authority> authorityList) {
final List<String> authorities = new ArrayList<String>();
for (final Authority authority : authorityList) {
authorities.add(authority.getName());
if (authority.getPrivileges() == null || authority.getPrivileges().isEmpty()) continue;
// Add all Privileges as Authorities
for (final Privilege item : authority.getPrivileges()) {
authorities.add(item.getName());
}
}
return authorities;
}
private final Collection<Authority> getGrantedAuthorities(final List<String> authorityList) {
final List<Authority> grantedAuthorities = new ArrayList<Authority>();
for (final String authority : authorityList) {
grantedAuthorities.add(new Authority(authority));
}
return grantedAuthorities;
}
}
Repos
public interface PrivilegeRepository extends JpaRepository<Privilege, Long> {
Privilege findByName(String name);
#Override
void delete(Privilege privilege);
}
public interface RoleRepository extends JpaRepository<Authority, Long> {
Authority findByName(String name);
#Override
void delete(Authority role);
}
public interface UserRepository extends JpaRepository<User, Long> {
User findByEmail(String email);
User findByUsername(String username);
#Override
void delete(User user);
}
SetupDataLoader Class (Optional)
#Component
public class SetupDataLoader implements ApplicationListener<ContextRefreshedEvent> {
private boolean alreadySetup = false;
#Autowired
private UserRepository userRepository;
#Autowired
private RoleRepository roleRepository;
#Autowired
private PrivilegeRepository privilegeRepository;
#Autowired
private PasswordEncoder passwordEncoder;
#Autowired
BeerRepository beerRepository;
#Override
#Transactional
public void onApplicationEvent(final ContextRefreshedEvent event) {
if (alreadySetup) {
return;
}
// == create initial privileges
final Privilege userReadPrivilege = createPrivilegeIfNotFound("USER_READ_PRIVILEGE");
final Privilege userWritePrivilege = createPrivilegeIfNotFound("USER_WRITE_PRIVILEGE");
final Privilege beerReadPrivilege = createPrivilegeIfNotFound("BEER_READ_PRIVILEGE");
final Privilege beerWritePrivilege = createPrivilegeIfNotFound("BEER_WRITE_PRIVILEGE");
final Privilege passwordPrivilege = createPrivilegeIfNotFound("CHANGE_PASSWORD_PRIVILEGE");
// == create initial roles
final List<Privilege> adminPrivileges = new ArrayList<Privilege>(Arrays.asList(beerReadPrivilege, beerWritePrivilege, userReadPrivilege, userWritePrivilege, passwordPrivilege));
final List<Privilege> userPrivileges = new ArrayList<Privilege>(Arrays.asList(beerReadPrivilege, beerWritePrivilege));
final Authority adminAuthority = createRoleIfNotFound("ROLE_ADMIN", adminPrivileges);
createRoleIfNotFound("ROLE_USER", userPrivileges);
// == create initial user
createUserIfNotFound("rdurden",
"rdurden#example.com",
"Rupert",
"Durden",
"ILikeBeer2!",
new ArrayList<Authority>(Arrays.asList(adminAuthority)));
alreadySetup = true;
}
#Transactional
Privilege createPrivilegeIfNotFound(final String name) {
Privilege privilege = privilegeRepository.findByName(name);
if (privilege == null) {
privilege = new Privilege(name);
privilege = privilegeRepository.save(privilege);
}
return privilege;
}
#Transactional
Authority createRoleIfNotFound(final String name, final Collection<Privilege> privileges) {
Authority authority = roleRepository.findByName(name);
if (authority == null) {
authority = new Authority(name);
}
authority.setPrivileges(privileges);
authority = roleRepository.save(authority);
return authority;
}
#Transactional
User createUserIfNotFound(final String username, final String email, final String firstName, final String lastName, final String password, final Collection<Authority> authorities) {
User user = Optional.ofNullable(userRepository.findByEmail(email)).orElseGet(() -> userRepository.findByUsername(username));
if (user != null) return user;
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
Date lastMonthDate = cal.getTime();
Timestamp lastMonthTimestamp = new Timestamp(lastMonthDate.getTime());
user = new UserBuilder()
.bAuthorities(authorities)
.bUsername(username)
.bFirstName(firstName)
.bLastName(lastName)
.bEmail(email)
.bPassword(passwordEncoder.encode(password))
.bIsUsing2FA(false)
.bEnabled(true)
.bLastPasswordResetDate(lastMonthTimestamp)
.createUser();
user = userRepository.save(user);
return user;
}
}
Try adding #Transactional to method loadUserByUsername.
I am using Hibernate with Spring in my project, I want to write a HQL query to get and update the role of user. How can I do that
This is my ERD:
this is my java classes:
User
#Entity
#Table(name = "users")
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "userId")
private int userId;
#Column(name = "userIdCardNo")
private String useridcardno;
#Column(name = "userFname")
private String fname;
#Column(name = "userMname")
private String mname;
#Column(name = "userLname")
private String lname;
#Column(name = "userPhone")
private int phone;
#Column(name = "userPhone2")
private String phone2;
#Column(name = "userAddress")
private String address;
#Column(name = "userAddress2")
private String address2;
#Column(name = "userName")
private String username;
#Column(name = "userPass")
private String password;
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(name = "users_roles", joinColumns = #JoinColumn(name = "userId", nullable = false) , inverseJoinColumns = #JoinColumn(name = "roleId", nullable = false) )
private List<Role> roles;
#Enumerated(EnumType.STRING)
#Column(name = "userStatus")
private UserStatus status;
//CREATE MD5 from String
public static String md5(String input) {
String md5 = null;
if (null == input)
return null;
try {
// Create MessageDigest object for MD5
MessageDigest digest = MessageDigest.getInstance("MD5");
// Update input string in message digest
digest.update(input.getBytes(), 0, input.length());
// Converts message digest value in base 16 (hex)
md5 = new BigInteger(1, digest.digest()).toString(16);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return md5;
}
//CONTRUSCTORS
public User() {
}
public User(int userId, String useridcardno, String fname, String mname, String lname, int phone, String phone2,
String address, String address2, String username, String password, List<Role> roles, UserStatus status) {
super();
this.userId = userId;
this.useridcardno = useridcardno;
this.fname = fname;
this.mname = mname;
this.lname = lname;
this.phone = phone;
this.phone2 = phone2;
this.address = address;
this.address2 = address2;
this.username = username;
this.password = BCrypt.hashpw(password, BCrypt.gensalt());
this.roles = roles;
this.status = status;
}
//GETTERS and SETTERS
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUseridcardno() {
return useridcardno;
}
public void setUseridcardno(String useridcardno) {
this.useridcardno = useridcardno;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getMname() {
return mname;
}
public void setMname(String mname) {
this.mname = mname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public int getPhone() {
return phone;
}
public void setPhone(int phone) {
this.phone = phone;
}
public String getPhone2() {
return phone2;
}
public void setPhone2(String phone2) {
this.phone2 = phone2;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
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 List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public UserStatus getStatus() {
return status;
}
public void setStatus(UserStatus status) {
this.status = status;
}
}
Role
#Entity
#Table(name = "roles")
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "roleId")
private int id;
#Column(name = "roleName")
private String roleName;
#ManyToMany(fetch = FetchType.EAGER, mappedBy = "roles")
private List<User> users;
public Role() {
}
public Role(int id, String roleName, List<User> users) {
super();
this.id = id;
this.roleName = roleName;
this.users = users;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
And UsersRoles
#Entity
#Table(name="users_roles")
public class UsersRoles {
#Id
#Column(name="userId")
private int userId;
#Id
#Column(name="roleId")
private int roleId;
public UsersRoles() {
}
public UsersRoles(int userId, int roleId) {
super();
this.userId = userId;
this.roleId = roleId;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getRoleId() {
return roleId;
}
public void setRoleId(int roleId) {
this.roleId = roleId;
}
}
I'm quite new to database queries since I have tried with for only a few times. I can get the data in one table, but for joining tables like this, I really need a hint.
Just load the user and modifiy the items of the role list. Then commit the transaction. - That's all.
EntityManager em ...
...
<begin Transaction>
...
User user = em.find(User.class, 1); //load by id 1 - just for example
User role1 = em.find(Role.class, 1); //load by id 1 - just for example
user.getRoles().add(role1);
...
<commit Transaction>
It is so simple because you use an ORM (Object Relational Mapper)(Hibernate). I almost all cases there is no need to write queries for updates, instead the state of the objects gets persisted.