Can anyone please help me to write an update query - java

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.

Related

HibernateQuery returns List of Objects instead of Entities

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

error when I try to login with Spring & JPA?

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.

MySQL Syntax Error Exception while executing JPQL in spring project

Above is the JPA Class
public class UsersDaoJpa extends BaseDaoJpa<Users> implements UsersDao {
public UsersDaoJpa() {
super(Users.class, "Users");
}
#Override
public List<Users> findByRegisteredUserEmail(String emailId) {
Query query = getEntityManager().createQuery("SELECT us FROM Users AS us WHERE us.emailId =:emailId");
query.setParameter("emailId", emailId);
return query.getResultList();
}
#Override
public List<Users> findByRegisteredUserPhone(String mobileNo) {
Query query = getEntityManager().createQuery("SELECT us FROM Users AS us WHERE us.mobileNo =:mobileNo");
query.setParameter("mobileNo", mobileNo);
return query.getResultList();
}
#Override
public List<Users> FindUsersByEmailPhoneRole(String emailId, String mobileNo, String userRole) {
Query query = getEntityManager().createQuery("SELECT us FROM Users AS us WHERE us.mobileNo =:mobileNo AND us.emailId =:emailId AND us.userRole =:userRole");
query.setParameter("mobileNo", mobileNo);
query.setParameter("emailId", emailId);
query.setParameter("userRole", userRole);
return query.getResultList();
}
#Override
public List<Users> checkUserNameAvailability(String userName) {
System.out.println("the username is " + userName);
Query query = getEntityManager().createQuery("SELECT us FROM Users AS us WHERE us.userName =:userName");
System.out.println("the username2 is " + userName);
query.setParameter("userName", userName);
System.out.println("the username3 is " + userName);
return query.getResultList();
}
#Override
public List<Users> checkEmailNMobileVerificationByUname(String userName, Boolean bolVal) {
Query query = getEntityManager().createQuery("SELECT us FROM Users AS us WHERE us.userName =:userName AND us.mobileVerifyStatus =:bolVal AND us.emailVerifyStatus =:bolVal");
query.setParameter("userName", userName);
query.setParameter("bolVal", bolVal);
return query.getResultList();
}
}
Above is the Domain Class or entity class against my db table
#Entity
#Table(name = "users")
public class Users extends BaseDomain {
private static final long serialVersionUID = 1L;
#Basic(optional = false)
#Column(name = "full_name")
private String fullName;
#Basic(optional = false)
#Column(name = "email_id")
private String emailId;
#Basic(optional = false)
#Column(name = "mobile_no")
private String mobileNo;
#Basic(optional = false)
#Column(name = "dob")
#Temporal(TemporalType.DATE)
private Date dob;
#Basic(optional = false)
#Column(name = "user_name")
private String userName;
#Basic(optional = false)
#Column(name = "password")
private String password;
#Basic(optional = false)
#Column(name = "email_verify_code")
private String emailVerifyCode;
#Basic(optional = false)
#Column(name = "mobile_verify_code")
private String mobileVerifyCode;
#Basic(optional = false)
#Column(name = "email_verify_status")
private boolean emailVerifyStatus;
#Basic(optional = false)
#Column(name = "mobile_verify_status")
private boolean mobileVerifyStatus;
#Basic(optional = false)
#Column(name = "user_role")
private String userRole;
#Basic(optional = false)
#Column(name = "login _utc")
#Temporal(TemporalType.TIMESTAMP)
private Date loginUtc;
#Basic(optional = false)
#Column(name = "registration_utc")
#Temporal(TemporalType.TIMESTAMP)
private Date registrationUtc;
#Basic(optional = false)
#Column(name = "is_approved")
private boolean isApproved;
#Basic(optional = false)
#Column(name = "is_blocked")
private boolean isBlocked;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userId")
private Collection<AdvisorDocument> advisorDocumentCollection;
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getMobileNo() {
return mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
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 getEmailVerifyCode() {
return emailVerifyCode;
}
public void setEmailVerifyCode(String emailVerifyCode) {
this.emailVerifyCode = emailVerifyCode;
}
public String getMobileVerifyCode() {
return mobileVerifyCode;
}
public void setMobileVerifyCode(String mobileVerifyCode) {
this.mobileVerifyCode = mobileVerifyCode;
}
public boolean getEmailVerifyStatus() {
return emailVerifyStatus;
}
public void setEmailVerifyStatus(boolean emailVerifyStatus) {
this.emailVerifyStatus = emailVerifyStatus;
}
public boolean getMobileVerifyStatus() {
return mobileVerifyStatus;
}
public void setMobileVerifyStatus(boolean mobileVerifyStatus) {
this.mobileVerifyStatus = mobileVerifyStatus;
}
public String getUserRole() {
return userRole;
}
public void setUserRole(String userRole) {
this.userRole = userRole;
}
public Date getLoginUtc() {
return loginUtc;
}
public void setLoginUtc(Date loginUtc) {
this.loginUtc = loginUtc;
}
public Date getRegistrationUtc() {
return registrationUtc;
}
public void setRegistrationUtc(Date registrationUtc) {
this.registrationUtc = registrationUtc;
}
public boolean getIsApproved() {
return isApproved;
}
public void setIsApproved(boolean isApproved) {
this.isApproved = isApproved;
}
public boolean getIsBlocked() {
return isBlocked;
}
public void setIsBlocked(boolean isBlocked) {
this.isBlocked = isBlocked;
}
public Collection<AdvisorDocument> getAdvisorDocumentCollection() {
return advisorDocumentCollection;
}
public void setAdvisorDocumentCollection(Collection<AdvisorDocument> advisorDocumentCollection) {
this.advisorDocumentCollection = advisorDocumentCollection;
}
}
And the error its throwing that its a mysql sysntax error exception. But according to me the code should work properly but dont know why isn't it not working .
the error that its throwing is as follows

How to populate foreign key in table Spring + Hibernate + Spring Security

I want make a case, when user is authenticated by Spring Security and then he fill adres form I would like to automatically updated a foreign key column "adres_id" in user table. Please give me a tip how implement this in the most popular way
I how somethig like this
Address Table:
User Table:
Adres
#Entity
#Table(name="adres")
public class Adres {
#Id
#GeneratedValue(strategy = GenerationType.AUTO )
int id;
#Column(name="country", nullable=false)
private String country;
private String street;
private String postcode;
private String telephone;
private String pesel;
#OneToOne(mappedBy ="adres")
private User user;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getPesel() {
return pesel;
}
public void setPesel(String pesel) {
this.pesel = pesel;
}
public String getStreet() {
return postcode;
}
public void setStreet(String street) {
this.street = street;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
User
#Entity
#Table(name="users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO )
int id;
#Column(name="username", nullable=false)
private String username;
private String password;
private String email;
private Boolean enabled;
#OneToOne(cascade = CascadeType.ALL)
private Adres adres;
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
AdresDAO
#Repository
#Transactional
public class AdresDAOImpl implements AdresDAO{
#Autowired
SessionFactory sessionFactory;
public void addAdres(Adres adres) {
sessionFactory.getCurrentSession().save(adres);
}
public List<Adres> listAdres() {
return sessionFactory.getCurrentSession().createQuery("from Adres order by id").list();
}
public void removeAdres(int id) {
Adres adres = (Adres) sessionFactory.getCurrentSession().load(
Adres.class, id);
if (null != adres) {
sessionFactory.getCurrentSession().delete(adres);
}
}
public Adres getAdres(int id) {
return (Adres)sessionFactory.getCurrentSession().get(Adres.class, id);
}
public void editAdres(Adres adres) {
sessionFactory.getCurrentSession().update(adres);
}
}
AdresService
#Service
public class AdresServiceImpl implements AdresService{
#Autowired
AdresDAO adresDAO;
#Transactional
public void addAdres(Adres adres) {
adresDAO.addAdres(adres);
}
#Transactional
public void editAdres(Adres adres) {
adresDAO.editAdres(adres);
}
#Transactional
public List<Adres> listAdres() {
return adresDAO.listAdres();
}
#Transactional
public void removeAdres(int id) {
adresDAO.removeAdres(id);
}
#Transactional
public Adres getAdres(int id) {
return adresDAO.getAdres(id);
}
}
User unidirectional relation between User and Address if Address object does not supposed to know about its owner (generally it does not). I would prefer user id in Address table if a User have more than one Address (one-to-many relation).
But for your question you may design like that,
public class User{
...
#OneToOne(CascadeType.REMOVE)//this is for to remove address when user is removed
#JoinColumn(name="HOME_ADDRESS_ID")
private Address address;
...
}
and
public class Address {
#Id
#GeneratedValue(strategy = GenerationType.AUTO )
int id;
#Column(name="country", nullable=false)
private String country;
private String street;
private String postcode;
private String telephone;
private String pesel;
//no user object here
public int getId() {
return id;
}
...
}

Java entity manager merge don't edit only make new record

Hi I can't get merge working it only makes new record but don't update record
EDIT:
Object:
#Entity(name = "ALLEGRO_TRANSACTION")
public class AllegroTransactionImpl implements AllegroTransaction{
#Id
#Column(name = "ID")
#GeneratedValue(strategy = GenerationType.AUTO)
protected Long id;
#Column(name = "ALIEXPRESS_NUMBER")
protected String aliexpressNumber;
#Column(name = "CREATE_DATE")
protected Date createDate;
#OneToOne(optional = true, targetEntity = PaymentTypeImpl.class)
#JoinColumn(name = "PAYMENT_ID")
protected PaymentTypeImpl paymentType;
#Column(name = "FIRST_NAME")
protected String firstName;
#Column(name = "LAST_NAME")
protected String lastName;
#Column(name = "PRICE")
protected float price;
#Column(name = "EMAIL")
protected String email;
#Column(name = "PHONE", nullable = true)
protected String phone;
#Column(name = "ADDRESS", columnDefinition="LONGTEXT")
protected String address;
#Column(name = "ATTENTION", columnDefinition="LONGTEXT")
protected String attention;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAliexpressNumber() {
return aliexpressNumber;
}
public void setAliexpressNumber(String aliexpressNumber){
this.aliexpressNumber = aliexpressNumber;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public PaymentTypeImpl getPaymentType() {
return paymentType;
}
public void setPaymentType(PaymentTypeImpl paymentType) {
this.paymentType = paymentType;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAttention() {
return attention;
}
public void setAttention(String attention) {
this.attention = attention;
}
}
Manager:
#Service
public class AllegroTransactionService {
private final static Logger logger = Logger.getLogger(AllegroTransactionService.class);
#PersistenceContext( unitName = "allegroTransactionPersistenceUnit", type= PersistenceContextType.EXTENDED )
protected EntityManager em;
public List<AllegroTransactionImpl> readAllegroTransactionByCreateDate()
{
Query query = this.em.createQuery( "SELECT allegroTransaction FROM com.springapp.mvc.classes.AllegroTransactionImpl allegroTransaction ORDER BY createDate DESC" );
return query.getResultList();
}
#Transactional
public AllegroTransactionImpl saveAllegroTransaction(AllegroTransactionImpl allegroTransaction)
{
this.em.merge( allegroTransaction );
return allegroTransaction;
}
}
Still can't get this working ... Maybe you guys figure something out ? Entity manager works i can easly get readAllegroTransaction function working but merge don't work - its create another object.
Problem was not passing correctly ID parameter

Categories

Resources