Column 'encrypted_password' cannot be null? - java

Im working on a web service using Java and spring-data-jpa. I setted different endpoints that works fine. Now I implemented logics in the post method and get return an error that I can't solve.
I use postman and when I try to make a post request with id,username,lastname and password i get an error 500 and the server return me this error:
java.sql.SQLIntegrityConstraintViolationException: Column 'encrypted_password' cannot be null
package com.nicolacannata.Appws.entity;
import javax.persistence.*;
import java.io.Serializable;
#Entity(name="users")
public class UserEntity implements Serializable{
private static final long serialVersionUID = 8076405899207283205L;
#Id
#GeneratedValue
private long id;
#Column(nullable = false)
private String userId;
#Column(nullable = false, length = 50)
private String firstName;
#Column(nullable = false, length = 50)
private String lastName;
#Column(nullable = false, length = 50)
private String email;
#Column(nullable = false)
private String encryptedPassword;
private String emailVerificationToken;
#Column(nullable = false)
private boolean emailVerificationStatus = false;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getEncryptedPassword() {
return encryptedPassword;
}
public void setEncryptedPassword(String encryptedPassword) {
this.encryptedPassword = encryptedPassword;
}
public String getEmailVerificationToker() {
return emailVerificationToken;
}
public void setEmailVerificationToker(String emailVerificationToker) {
this.emailVerificationToken = emailVerificationToker;
}
public boolean isEmailVerificationStatus() {
return emailVerificationStatus;
}
public void setEmailVerificationStatus(boolean emailVerificationStatus) {
this.emailVerificationStatus = emailVerificationStatus;
}
}

You declared that attribute encryptedPassword cannot be null. The exception means, that this attribute was null when you attempted to save it to database. Either you forgot to set this attribute. Or you set it (you called setter), but the new value was null. To resolve the problem, set this attribute to a not-null value before saving to DB.

You have #Column(nullable = false) for private String encryptedPassword; and you are passing only id, username, lastname and password. which breaks the condition nullable = false and results in java.sql.SQLIntegrityConstraintViolationException: Column 'encrypted_password' cannot be null
Solution
Set #Column(nullable = true)
OR
Pass the value for encryptedPassword

Related

H2 database columns and values don't converge JAVA Spring

I am new one at java and spring framework and have this problem. I have class, which has fields, that should be columns in H2. It looks like this:
package com.bankapp.bankwebapplication.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class PersonClient implements Client {
#Id
#Column(nullable = false, unique = true)
private Long id;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
#Column(nullable = false)
private String firstName;
public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; }
#Column(nullable = false)
private String lastName;
public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; }
#Column(nullable = false)
private String address;
public String getAddress() { return address; }
public void setAddress(String address) { this.address = address; }
#Column
private String workPhone;
public String getWorkPhone() { return workPhone; }
public void setWorkPhone(String workPhone) { this.workPhone = workPhone; }
#Column
private String homePhone;
public String getHomePhone() { return homePhone; }
public void setHomePhone(String homePhone) { this.homePhone = homePhone; }
#Override
public void getDetails() {
}
}
Also, I have data.sql file that inserts 1 value into that table:
INSERT INTO person_client VALUES (1, 'firstName', 'lastName', 'paper street', '+123123', '+321321')
So, the problem is that it looks like this:
Why? And how can I fix that?
Always specify the target columns in INSERT statements:
INSERT INTO person_client
(id, first_name, last_name, address, home_phone, work_phone)
VALUES
(1, 'firstName', 'lastName', 'paper street', '+123123', '+321321')
If you don't specify the target columns, the values are matched by position and apparently the columns are created in a different order than you think they are.
agree with #a_horse_with_no_name, if you not specify column names it will insert based on the position/index. And all your java variables are in string that is the reason it does't throw any classcast exception.

`RollbackException: Error while committing the transaction` when trying to save an object with Spring JPA and MySQL

I'm trying to save an object in my MySQL DB by using Spring JPA.
That's the error I get:
[nio-8088-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Resolved
[org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction]
That's where I'm trying to save my object:
#Override
public RegistrationV1Response registerUser(#Valid RegistrationV1Request registrationV1Request) {
User user = new User();
user.setFirstname(registrationV1Request.getFirstname());
user.setLastname(registrationV1Request.getLastname());
user.setUsername(registrationV1Request.getUsername());
user.setEmail(registrationV1Request.getEmail());
user.setPassword(new BCryptPasswordEncoder().encode(registrationV1Request.getPassword()));
user.setActive(true);
userRepository.save(user);
return new RegistrationV1Response().withUser(user);
}
The UserRepository:
#Repository
public interface UserRepository extends CrudRepository<User, Long> {
public User findFirstByUsername(String username);
}
The User class:
#javax.persistence.Entity
#Table(name = "users")
public class User extends Entity {
#Column(name = "firstname", nullable = false, length = 100)
#NotEmpty()
private String firstname;
#Column(name = "lastname", nullable = false, length = 100)
#NotEmpty()
private String lastname;
#Column(name = "password", nullable = false, length = 100)
#NotEmpty()
private String password;
#Column(name = "username", nullable = false, unique = true, length = 100)
#NotEmpty()
private String username;
#Column(name = "email", nullable = false, unique = true, length = 100)
#NotEmpty()
#Email()
private String email;
#Column(name = "active", nullable = false)
#NotEmpty()
private boolean active;
#Column(name = "description", nullable = true, length = 250)
private String description;
#OneToMany(targetEntity = Post.class, mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Post> posts;
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 String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isActive() { return active; }
public void setActive(boolean active) { this.active = active; }
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<Post> getPosts() { return posts; }
public void setPosts(List<Post> posts) { this.posts = posts; }
}
The Post class:
#javax.persistence.Entity
#Table(name = "posts")
public class Post extends Entity {
#Lob
#Column(name = "text", nullable = false)
#NotEmpty()
private String text;
#ManyToOne(targetEntity = User.class)
private User user;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
Reading from the DB work's without any problems just save (insert / update) doesn't work.
I just read on a similar issue that I need to add the #Transational property to the method. I did this and it's still not working. Also the other possible solutions / statements of similar issues aren't working. They're mostly about missconfigured relations or something and that's not the problem in my case I think.

OneToMany relationship error: Field 'XX' doesn't have a default value

I'm trying to create One-To-Many relationship between two objects but I got this error. I don't know how to mapping property ID from object MyUserAccount to object Book. ID is a String data received from Google (I'm doing Social Login in my project).
Error
PreparedStatementCallback; SQL [INSERT INTO Books(TENSACH, TACGIA, NHANXET, TINHTRANG, THELOAI, IMAGE, IMAGE_NAME) VALUES ( ?, ?, ?, ?, ?, ?, ?)]; Field 'ID' doesn't have a default value; nested exception is java.sql.SQLException: Field 'ID' doesn't have a default value
BookDao (How I save object Book into database)
public void save(Book book) {
// TODO Auto-generated method stub
KeyHolder keyHolder = new GeneratedKeyHolder();
String sql = "INSERT INTO Books(TENSACH, TACGIA, NHANXET, TINHTRANG, THELOAI, IMAGE, IMAGE_NAME) "
+ "VALUES ( :tensach, :tacgia, :nhanxet, :tinhtrang, :theloai, :image, :image_name)";
namedParameterJdbcTemplate.update(sql, getSqlParameterByModel(book), keyHolder);
book.setBook_ID(keyHolder.getKey().intValue());
}
private SqlParameterSource getSqlParameterByModel(Book book) {
MapSqlParameterSource paramSource = new MapSqlParameterSource();
paramSource.addValue("book_id", book.getBook_ID());
paramSource.addValue("tensach", book.getTensach());
paramSource.addValue("tacgia", book.getTacgia());
paramSource.addValue("nhanxet", book.getNhanxet());
paramSource.addValue("tinhtrang", book.getTinhtrang());
paramSource.addValue("image", book.getImage());
paramSource.addValue("image_name", book.getImage_name());
paramSource.addValue("theloai", book.getTheloai());
return paramSource;
}
Model Book
public class Book implements Serializable {
private static final long serialVersionUID = 1L;
private Integer book_ID;
private String tensach;
private String tacgia;
private String nhanxet;
private String tinhtrang;
private String theloai;
private byte[] image;
private String image_name;
private String data;
private MyUserAccount myUserAccount;
public Book() {
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "ID", nullable = false)
public MyUserAccount getMyUserAccount() {
return this.myUserAccount;
}
public void setMyUserAccount(MyUserAccount myUserAccount) {
this.myUserAccount = myUserAccount;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "book_id", unique = true, nullable = false)
public Integer getBook_ID() {
return book_ID;
}
#Column(name = "image_name")
public String getImage_name() {
return image_name;
}
#Column(name = "tensach", length = 50, nullable = true)
public String getTensach() {
return tensach;
}
#Lob
#Type(type = "org.hibernate.type.BinaryType")
#Column(name = "image", columnDefinition = "LONGBLOB", nullable = true)
public byte[] getImage() {
return image;
}
#Column(name = "tacgia", length = 50, nullable = true)
public String getTacgia() {
return tacgia;
}
#Column(name = "nhanxet", length = 100, nullable = true)
public String getNhanxet() {
return nhanxet;
}
#Column(name = "tinhtrang", length = 50, nullable = true)
public String getTinhtrang() {
return tinhtrang;
}
#Column(name = "theloai", length = 50, nullable = true)
public String getTheloai() {
return theloai;
}
#Column(name = "data", length = 16777215)
public String getData() {
return data;
}
public void setBook_ID(Integer book_ID) {
this.book_ID = book_ID;
}
public void setImage_name(String image_name) {
this.image_name = image_name;
}
public void setImage(byte[] image) {
this.image = image;
}
public void setTensach(String tensach) {
this.tensach = tensach;
}
public void setTacgia(String tacgia) {
this.tacgia = tacgia;
}
public void setNhanxet(String nhanxet) {
this.nhanxet = nhanxet;
}
public void setTinhtrang(String tinhtrang) {
this.tinhtrang = tinhtrang;
}
public void setTheloai(String theloai) {
this.theloai = theloai;
}
public void setData(String data) {
this.data = data;
}
#Override
public String toString() {
return "Book [book_ID=" + book_ID + ", tensach=" + tensach + ", tacgia=" + tacgia + ", nhanxet=" + nhanxet
+ ", tinhtrang=" + tinhtrang + ", theloai=" + theloai + ", image=" + Arrays.toString(image) + "]";
}
}
Model MyUserAccount.
public class MyUserAccount implements Serializable {
private static final long serialVersionUID = 1L;
public static final String ROLE_USER = "ROLE_USER";
private String id;
private String email;
private String userName;
private String firstName;
private String lastName;
private String password;
private String role;
private String enabled;
private List<Book> book = new ArrayList<Book>(0);
public MyUserAccount() {
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "myUserAccount")
public List<Book> getBook() {
return book;
}
public void setBook(List<Book> book) {
this.book = book;
}
public MyUserAccount(String id, String email, String userName, String firstName, //
String lastName, String password, String role, String enabled) {
this.id = id;
this.email = email;
this.userName = userName;
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
this.role = role;
this.enabled = enabled;
}
#Id
#Column(name = "ID", unique = true, nullable = false)
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Column(name = "EMAIL", unique = true, nullable = false)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name = "USER_NAME", unique = true, nullable = false)
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
#Column(name = "FIRST_NAME", nullable = false)
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "LAST_NAME", nullable = false)
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Column(name = "PASSWORD", nullable = false)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name = "ROLE", nullable = false)
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
#Column(name = "ENABLED", columnDefinition = "VARCHAR(1) default 'Y'", nullable = false)
public String getEnabled() {
return enabled;
}
public void setEnabled(String enabled) {
this.enabled = enabled;
}
}
Controller
#RequestMapping(value = "/motsach/add/", method = RequestMethod.POST)
public String saveBook(#ModelAttribute("bookForm") #Validated Book book, BindingResult result, Model model,
#RequestParam CommonsMultipartFile[] image, String userName, final RedirectAttributes redirectAttributes)
throws IOException, UnsupportedEncodingException {
MyUserAccount myUserAccount = myUserAccountDAO.findByUserName(userName);
System.out.println(userName + "sssssssssssss");
book.setMyUserAccount(myUserAccount);
redirectAttributes.addFlashAttribute("css", "success");
if (book.getBook_ID() == null) {
System.out.println(book.getBook_ID());
redirectAttributes.addFlashAttribute("msg", "book added successfully!");
} else {
redirectAttributes.addFlashAttribute("msg", "book updated successfully!");
}
for (CommonsMultipartFile aFile : image) {
System.out.println("Saving file: " + aFile.getOriginalFilename());
book.setImage_name(aFile.getOriginalFilename());
book.setImage(aFile.getBytes());
System.out.println("Damn that Shit!");
}
bookService.saveOrUpdate(book);
// POST/REDIRECT/GET
return "redirect:/motsach/" + book.getBook_ID();
}
You have a #manyToOne (with ID as name ) relation that can't be null. So in order to add a book you have to set MyUserAccount to a book before saving or you can turn into :
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "ID", nullable = true)
public MyUserAccount getMyUserAccount() {
return this.myUserAccount;
}
and modify your column in your database to set the possibility of null value.

Hibernate custom ordering and java.text.Collator

I need to sort a Result set depending on a field by asc or dsc order. That field is of type String and contains names of users. Now the names are french name. So to sort list of users based on their names generally I use the following code:
final Collator collator = Collator.getInstance(Locale.FRANCE);
Comparator<ActivityUserDTO> comparator = new Comparator<ActivityUserDTO>() {
#Override
public int compare(ActivityUserDTO dto1, ActivityUserDTO dto2) {
return collator.compare(dto1.getFullName(), dto2.getFullName());
}
};
Collections.sort(users, comparator);
In this case I have the whole list of users loaded from Database and then I am doing the soring.
Now following code is for hibernate where I have startIndex: which sets the FirstResult for Criteria, maxResult: which sets the MaxResults of Criteria and the ordering:
Criteria criteria = getSessionFactory().getCurrentSession().createCriteria(entityClass);
if (StringUtils.isNotEmpty(sortField)) {
criteria.addOrder(sortOrder ? Order.asc(sortField) : Order.desc(sortField));
}
criteria.setFirstResult(startIndex);
criteria.setMaxResults(maxResult);
Here the sortField is fullName which is in French and sortOrder can be either true or false.
Is there any way to make the ordering in custom manner so that it do the sorting/ordering which is done by the Collator? Any pointer would be very helpful to me.
I have seen some site like:
Documentation
Sorting Hibernate Set using a comparator
Hibernate annotations sort using Comparator
where they are using Comparator to sort the Set of Assoicated Objects, but how can I do it in my case?
This is my User:
#javax.persistence.Entity
#Table(name = "USER")
public class User extends Entity {
#Transient
private static final long serialVersionUID = -112950002831333869L;
private String username;
private String firstName;
private String lastName;
private String fullName;
private String mail;
private String homePostalAddress;
private String mobile;
private String homePhone;
private Date dateOfBirth;
private Date dateOfJoining;
private Date dateOfRelease;
private boolean active;
private String role;
private Set<Activity> activities;
public User() {
super();
}
#NaturalId
#Column(name = "USERNAME", nullable = false)
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Column(name = "FIRST_NAME")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "LAST_NAME")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Column(name = "FULL_NAME")
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
#Column(name = "MAIL")
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
#Column(name = "HOME_POSTAL_ADDRESS")
public String getHomePostalAddress() {
return homePostalAddress;
}
public void setHomePostalAddress(String homePostalAddress) {
this.homePostalAddress = homePostalAddress;
}
#Column(name = "MOBILE")
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
#Column(name = "HOME_PHONE")
public String getHomePhone() {
return homePhone;
}
public void setHomePhone(String homePhone) {
this.homePhone = homePhone;
}
#Column(name = "DATE_OF_BIRTH")
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
#Column(name = "DATE_OF_JOINING")
public Date getDateOfJoining() {
return dateOfJoining;
}
public void setDateOfJoining(Date dateOfJoining) {
this.dateOfJoining = dateOfJoining;
}
#Column(name = "DATE_OF_RELEASE")
public Date getDateOfRelease() {
return dateOfRelease;
}
public void setDateOfRelease(Date dateOfRelease) {
this.dateOfRelease = dateOfRelease;
}
#Column(name = "ACTIVE", nullable = false)
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
#Column(name = "ROLE")
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
#ManyToMany(cascade = { CascadeType.ALL }, mappedBy = "users", targetEntity = Activity.class)
public Set<Activity> getActivities() {
return activities;
}
public void setActivities(Set<Activity> activities) {
this.activities = activities;
}
}
Hibernate doesn't do the sorting. The database does. Executing a criteria query boils down to executing a SQL query having an order by fullName clause.
So check the configuration of your database to know how to specify the collation used by a table or column.
ALTER DATABASE adb DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
did the job.

org.hibernate.QueryParameterException: could not locate named parameter

My project setting are Spring MVC, Hibernate 3.2.x, on MySQL DB
Getting the following error:
org.hibernate.QueryParameterException: could not locate named parameter email
Approach #1:
#Override
public Boolean isExist(String email) {
boolean flag = false;
String hql = "from com.cmgr.beans.UserAccount u where u.email = :email";
List<UserAccount> result = currentSession().createQuery(hql)
.setParameter("email", email)
.list();
UserAccount userAccount = (UserAccount)result.get(0);
if (userAccount!=null && userAccount.getEmail().equalsIgnoreCase(email)) {
flag = true;
}
return flag;
}
Approach #2:
#Override
public Boolean isExist(String email) {
boolean flag = false;
String hql = "from com.cmgr.beans.UserAccount u where u.email = :email";
List<UserAccount> result = currentSession().createQuery(hql).setString("email", email).list();
UserAccount userAccount = (UserAccount) result.get(0);
if (userAccount != null && userAccount.getEmail().equalsIgnoreCase(email)) {
flag = true;
}
return flag;
}
Error:
java.lang.IllegalArgumentException: Parameter email does not exist as a named parameter in [from com.cmgr.beans.UserAccount u where u.email = :email]
UserAccount class:
package com.cmgr.beans;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import javax.persistence.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
#Entity
#Table(name = "user_account")
public class UserAccount implements Serializable {
#Autowired
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY, generator = "user_account_seq")
#SequenceGenerator(name = "user_account_seq", sequenceName = "user_account_seq")
#Column(name = "user_id")
private Long UserId = null;
//
#Autowired
#Column(name = "user_name")
private String UserName;
//
#Autowired
#Column(name = "user_type")
private String UserType = null;
//
#Autowired
#Column(name = "first_name")
private String FirstName;
//
#Autowired
#Column(name = "last_name")
private String LastName;
//
#Autowired
#Column(name = "email")
private String Email;
//
#Autowired
#Column(name = "phone_contact_1")
private String PhoneContact1 = null;
//
#Autowired
#Column(name = "phone_contact_2")
private String PhoneContact2 = null;
//primary_address_is_usa
#Autowired
#Column(name = "primary_address_is_usa")
private Boolean primaryAddressIsUsa = null;
//
#Autowired
#Column(name = "address_1")
private String Address1 = null;
//
#Autowired
#Column(name = "city1")
private String city1 = null;
//
#Autowired
#Column(name = "state1")
private String state1 = null;
//
#Autowired
#Column(name = "country1")
private String country1 = null;
//
#Autowired
#Column(name = "zipcode")
private Integer zipcode = 0;
//
#Autowired
#Column(name = "Industry")
private String Industry = null;
//is the user account Active either due to user deactivation,admin deactivation, or nonpayment
#Autowired
#Column(name = "active")
private boolean Active = false;
//1 to 1 relation with registerationCode in Registeration class
#Autowired
#Qualifier("UserRegisteration")
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "Registeration_Code_fk", referencedColumnName = "registeration_code", nullable = false)
private UserRegisteration UserRegisteration;
//1 to many relation with EmailId in Email class
#OneToMany(cascade = {CascadeType.ALL})
#JoinColumn(name = "emailed_id")
private List<Emailed> emailed = null;
//1 to many relation with signatureId in signature class
#OneToMany(cascade = {CascadeType.ALL})
#JoinColumn(name = "signature_id")
private List<Signature> signatures;
//1 to many relation with UserAccountDocId in UserAccountDoc class
#OneToMany(cascade = {CascadeType.ALL})
#JoinColumn(name = "user_doc_id")
private Set<UserAccountDocumentRelationship> UserAccountDocumentRelationship;
#Autowired(required = false)
public UserAccount() {
}
#Autowired(required = true)
public UserAccount(String UserName, String FirstName, String LastName, String Email, String Industry) {
this.FirstName = FirstName;
this.LastName = LastName;
this.Email = Email;
this.Industry = Industry;
this.UserName = UserName;
}
#Autowired(required = false)
public UserAccount(String UserName, Long UserId, String FirstName, String LastName, String Email, String Industry) {
this.UserId = UserId;
this.FirstName = FirstName;
this.LastName = LastName;
this.Email = Email;
this.Industry = Industry;
this.UserName = UserName;
}
public String getIndustry() {
return Industry;
}
public void setIndustry(String Industry) {
this.Industry = Industry;
}
public String getAddress1() {
return Address1;
}
public void setAddress1(String Address1) {
this.Address1 = Address1;
}
public String getPhoneContact1() {
return PhoneContact1;
}
public void setPhoneContact1(String PhoneContact1) {
this.PhoneContact1 = PhoneContact1;
}
public String getPhoneContact2() {
return PhoneContact2;
}
public void setPhoneContact2(String PhoneContact2) {
this.PhoneContact2 = PhoneContact2;
}
public boolean isActive() {
return Active;
}
public void setActive(boolean Active) {
this.Active = Active;
}
public String getEmail() {
return Email;
}
public void setEmail(String Email) {
this.Email = Email;
}
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 com.cmgr.beans.UserRegisteration getUserRegisteration() {
return UserRegisteration;
}
public void setUserRegisteration(com.cmgr.beans.UserRegisteration UserRegisteration) {
this.UserRegisteration = UserRegisteration;
}
public Long getUserId() {
return UserId;
}
public void setUserId(Long UserId) {
this.UserId = UserId;
}
public String getUserType() {
return UserType;
}
public void setUserType(String UserType) {
this.UserType = UserType;
}
public List<Emailed> getEmailed() {
return emailed;
}
public void setEmailed(List<Emailed> emailed) {
this.emailed = emailed;
}
public List<Signature> getSignatures() {
return signatures;
}
public void setSignatures(List<Signature> signatures) {
this.signatures = signatures;
}
public String getCity1() {
return city1;
}
public void setCity1(String city1) {
this.city1 = city1;
}
public String getCountry1() {
return country1;
}
public void setCountry1(String country1) {
this.country1 = country1;
}
public Boolean getPrimaryAddressIsUsa() {
return primaryAddressIsUsa;
}
public void setPrimaryAddressIsUsa(Boolean primaryAddressIsUsa) {
this.primaryAddressIsUsa = primaryAddressIsUsa;
}
public String getState1() {
return state1;
}
public void setState1(String state1) {
this.state1 = state1;
}
public Integer getZipcode() {
return zipcode;
}
public void setZipcode(Integer zipcode) {
this.zipcode = zipcode;
}
public String getUserName() {
return UserName;
}
public void setUserName(String UserName) {
this.UserName = UserName;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final UserAccount other = (UserAccount) obj;
if ((this.UserId == null) ? (other.UserId != null) : !this.UserId.equals(other.UserId)) {
return false;
}
return true;
}
#Override
public int hashCode() {
int hash = 3;
hash = 73 * hash + (this.UserId != null ? this.UserId.hashCode() : 0);
return hash;
}
public Set<com.cmgr.beans.UserAccountDocumentRelationship> getUserAccountDocumentRelationship() {
return UserAccountDocumentRelationship;
}
public void setUserAccountDocumentRelationship(Set<com.cmgr.beans.UserAccountDocumentRelationship> UserAccountDocumentRelationship) {
this.UserAccountDocumentRelationship = UserAccountDocumentRelationship;
}
}
From what i remember, this is a case of Hibernate reporting the wrong error message. I guess, the actual error is "mapping not found for com.cmgr.beans.UserAccount". Try this query:
String hql = "from com.cmgr.beans.UserAccount";
This probably will show you the correct error message. And once you fix that, you can change it to accept the parameters.
Today i had a similar issue...
My entity was not in the scanned packages from Spring. So Hibernate somehow did something but the error message was quite confusing and did not really fit to the real issue.
To solve my problem i had to add the entities to the packagescan.
Change your query to
String hql = "from com.cmgr.beans.UserAccount u where u.Email = :email";
Since your UserAccount class has a property of Email
Hibernate somewhy throws different exception than it has to be.. Probably by correcting this you should get rid of the problem:
Rename fields in the class to follow JavaConventions (should start with a small letter)
Use simple class name instead of fully qualified
I see that in the UserAccount class, the property for the email address is defined as 'Email' and not 'email'.
Refer to the hibernate documentation
It is advisable to use java naming convention hence I would advice you to name your property to 'email' in UserAccount.
replace:
#Autowired
#Column(name = "email")
private String Email;
//
with:
#Autowired
private String email;
use java naming conventions of variable naming small letters & don't need to write
#Column(name = "email")
because variable name is same name as column name
Just Try this....
In place of
List<UserAccount> result = currentSession().createQuery(hql)
.setParameter("email", email)
.list();
use
List<UserAccount> result = currentSession().createQuery(hql)
.setString("email", email)
.list();
may be it will helps you....
Verify that in the SQL query the parameter starts with ':'
Example: WHERE NAME = :pMyParameter
At the same time, you must take into account that in the Java code the parameter must not be named with ':'
Example: parameters.put("pMyParameter", myParameter);
may be it will helps you...

Categories