I have the next situation. I ahve entity object User:
package models;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.*;
import org.hibernate.annotations.Proxy;
#Entity
#Table(name="users")
#Proxy(lazy=true)
public class User {
private int id;
private String login;
private String password;
private String name;
private String email;
private Integer age;
private String country;
private Set<UserRole> roles = new HashSet<UserRole>();
private UserStatus status;
private Date created;
private Date updated;
public User() {
status=UserStatus.A;
}
public User(String user_login, String user_password, String user_name, String user_email) {
this.login = user_login;
this.password = user_password;
this.name = user_name;
this.email = user_email;
status=UserStatus.A;
}
public User(String user_login, String user_password, String user_name, String user_email, int age) {
this(user_login, user_password, user_name, user_email);
this.age = age;
}
public User(String user_login, String user_password, String user_name, String user_email, int age, String country) {
this(user_login, user_password, user_name, user_email, age);
this.country = country;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="user_id", unique = true)
public int getId() {
return id;
}
public void setId(int user_id) {
this.id = user_id;
}
#Column(name="user_login")
public String getLogin() {
return login;
}
public void setLogin(String user_login) {
this.login = user_login;
}
#Column(name="user_password")
public String getPassword() {
return password;
}
public void setPassword(String user_password) {
this.password = user_password;
}
#Column(name="user_name")
public String getName() {
return name;
}
public void setName(String user_name) {
this.name = user_name;
}
#Column(name="user_email")
public String getEmail() {
return email;
}
public void setEmail(String user_email) {
this.email = user_email;
}
#Column(name="user_age")
public Integer getAge() {
return age;
}
public void setAge(Integer user_age) {
this.age = user_age;
}
#Column(name="user_country")
public String getCountry() {
return country;
}
public void setCountry(String user_country) {
this.country = user_country;
}
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(name = "users_to_userroles", joinColumns = { #JoinColumn(name = "user_id") },
inverseJoinColumns = { #JoinColumn(name = "user_role_id ") })
public Set<UserRole> getRoles() {
return roles;
}
public void setRoles(Set<UserRole> user_roles) {
this.roles = user_roles;
}
#Column(name="user_status")
#Enumerated(EnumType.STRING)
public UserStatus getStatus() {
return status;
}
public void setStatus(UserStatus status) {
this.status = status;
}
#Transient
#Column(name="user_created")
public Date getCreated() {
return created;
}
public void setCreated(Date user_created) {
this.created = user_created;
}
#Transient
#Column(name="user_updated")
public Date getUpdated() {
return updated;
}
public void setUpdated(Date user_updated) {
this.updated = user_updated;
}
}
And JSP page (simple form, not related to question) with the form to create new user and table to show all existing users. I have used binding between form and Entity object User (it is inside controller):
User user = new User();
List<User> users = userService.getAllUsers();//to fill table with users
List<UserRole> userRoles = userRolesService.getAllRoles();//to fill tables with users
model.addAttribute("rolesList", userRoles);
model.addAttribute("users", users);
model.put("adminForm", user);//Here adminForm is the name of form in JSP page
Now what is the problem: as you see User has two fields user_created and user_updated (they are created automatically by Postgres server). They are forwarded withh all other fields to table in JSP page. BUT my form in JSP does not provide these fields (no need - right)))), so they are null when transfered from form to controller. And now Hibernate can not add line on Postgres server because two fields are empty((( So my question is:
can I somehow mark these columns as #Transient but only when I save entity not read it from database.
I know I still can bind separate field in form not the whole object. But still is it possible to do what I ask? With existing configuration, new User is saved but these two fields are not read and JSP table columns are empty(((
You need to set the insertable and updatable properties of your column mapping to false. This will make the field read-only for Hibernate.
#Column(name="user_created", insertable=false, updatable=false)
Related
I have the below repository which extends JpaRepository.
public interface UserRepository extends JpaRepository<User, Long> {
// #Query(value = "SELECT * FROM users u WHERE u.email = ?1", nativeQuery = true)
User findByEmail(String email);
}
When I call the function from the below mapping no result is returned, no empty object, nothing.
#GetMapping(value = "email")
public User getByEmail(#RequestBody String email) {
return userRepository.findByEmail(email);
}
Found similar issues but with no actual answers. I have also tried native queries, as you can see the commented #Query annotation. The mapping is in a simple controller which just has a post function and a get function for all the users.
What am I doing wrong?
Edit ---
User model
package com.example.demo.User;
import javax.persistence.*;
#Entity(name="Users")
#Table(name = "users", uniqueConstraints = {
#UniqueConstraint(name = "user_email_unique", columnNames = "email")
})
public class User {
#Id
#SequenceGenerator(
name = "users_sequence",
sequenceName = "users_sequence",
allocationSize = 1
)
#GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "users_sequence"
)
#Column(name = "id", updatable = false) // Column options for the id
private long id;
#Column(name = "first_name", nullable = false, columnDefinition = "TEXT")
private String name;
private String lastName;
#Column(nullable = false, columnDefinition = "TEXT")
private String email;
private int age;
private int weight;
public User() {}
public User(String name, String lastName, String email, int age, int weight) {
this.name = name;
this.lastName = lastName;
this.email = email;
this.age = age;
this.weight = weight;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
I have found the answer in the docs of spring boot, only POST/PUT requests have a request body.
#RequestBody annotation binds the content sent in (POST / PUT) request body with the annotated variable. Since there is no 'body' part in GET request, spring throws HttpMessageNotReadableException to indicate the same.
As a general rule, you can only use #RequestBody for the requests which can have 'body' content e.g. POST or PUT.
I am creating an app where there are two entities
users
chatrooms
There is a many to many relationship between users and chatrooms.
I created a many to many relationship with a join table named users_chatrooms. The values are getting populated in the join table correctly when I wrote code for a user to join a chatroom.
My issue is that, I need an endpoint that can fetch all the users of a given chatroom. For this, I need the table created by the join (users_chatrooms) as part of Jpa. How to accomplish this in JPA ?
User class
package com.example.chat.models;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(name="USERS")
public class User {
#Id
#Column(name="userid")
private String username;
#Column(name="pass")
private String password;
#ManyToMany(mappedBy = "users",fetch=FetchType.EAGER,cascade = CascadeType.ALL)
List<Chatroom>rooms;
public List<Chatroom> getRooms() {
return rooms;
}
public void setRooms(List<Chatroom> rooms) {
this.rooms = rooms;
}
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Chatroom class
package com.example.chat.models;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(name="Chatrooms")
public class Chatroom {
#Id
#Column(name="chatroomId")
private String id;
#Column(name="chatRoomName")
private String name;
#Column(name="chatroomDesc")
private String description;
#ManyToMany(fetch=FetchType.EAGER,cascade = CascadeType.ALL)
#JoinTable(
name = "users_chatrooms",
joinColumns = #JoinColumn(name = "chatroomId"),
inverseJoinColumns = #JoinColumn(name = "userid"))
private List<User>users;
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
You can simply join the two entities using #JoinColumn
#Entity
#Table(name="Chatrooms")
public class Chatroom {
#Id
#Column(name="chatroomId")
private String id;
#Column(name="chatRoomName")
private String name;
#Column(name="chatroomDesc")
private String description;
#ManyToMany(fetch=FetchType.EAGER,cascade = CascadeType.ALL)
#JoinColumn(name = "userid", referencedColumnName = "chatroomId")
private List<User>users;
// getters and setters
}
hello i'm trying to learn one to many mapping but i really having trouble with hibernate. I was able to persist to database but when trying to apply one to many relationship it doesn't persist to DB and also doesn't display the relationship when viewing the response body in postman. I really need help been on this problem since yesterday morning. I have looked on tutorials on youtube and on internet but every tutorial seem basic and when applying same idea no success. I have an entity person and another entity organization. A person can belong up to one organization but different persons can belong to the same organization. So my approach was using a one to many relationship.
Below is my entity of Organization:
#Entity
#Table(name="organization")
public class Organization {
#Id
#Column(name="org_Id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name, description;
#OneToMany(/*fetch = FetchType.EAGER, cascade = CascadeType.ALL*/)
#JoinTable(joinColumns = #JoinColumn(name="org_Id"),
inverseJoinColumns = #JoinColumn(name="person_Id"))
// #JsonIgnore
//#JoinColumn(name="org_Id")
private Collection<Person> personCollection = new ArrayList<Person>();
public Collection<Person> getPersonCollection() {
return personCollection;
}
public void setPersonCollection(Collection<Person> personCollection) {
this.personCollection = personCollection;
}
private Address address;
public Organization() {}
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 String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
And below is my Person entity:#Entity
#Table(name = "Person")
public class Person {
#Id
#Column(name="person_Id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name="Email",unique = true)
private String email;
#Column(name="FirstName")
private String first_name;
#Column(name="LastName")
private String last_name;
#Column(name="Description")
private String description;
//#Embedded
private Address address;
#ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JsonIgnore
private Organization organization;
public Organization getOrganization() {
return organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
public Person() {}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
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 String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
when trying to create person. Below is my create method:
public Person createPerson(String f_name, String l_name, String email, String city, String state,
String zipCode, String street, String description, Long id) {
Person person = null;
//f_name, l_name, email are required parameters if empty return null and throws an exception..
if(f_name.isEmpty() || l_name.isEmpty() || email.isEmpty()) {
return person;
}
else {
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
person = new Person();
person.setFirst_name(f_name);
person.setLast_name(l_name);
person.setEmail(email);
person.setDescription(description);
Address address = new Address();
address.setStreet(street);
address.setZipCode(zipCode);
address.setState(state);
address.setCity(city);
person.setAddress(address);
/* checks to see if id of organization exist if so add to list if not don't do anything.*/
if(id!=null) {
Organization organization = session.get(Organization.class, id);
if (organization != null) {
/* adds id of organization to person table and vice versa.*/
person.setOrganization(organization);
organization.getPersonCollection().add(person);
} else {
//do nothing
}
}
session.save(person);
transaction.commit();
} catch (HibernateException ex) {
if (transaction != null)
transaction.rollback();
ex.printStackTrace();
} finally {
if (session != null)
session.close();
}
return person;
}
}
I am able to create both person and organization and persist to database. But when i try to add an organization to a person Row in database i cannot add the relationship(verified when i tried looking up database itself) and also no response as i get a lazy initialization collection error as well. Please has anyone encountered this problem
I just executed the code snippet you gave in hibernate with the following simplified structure which works perfectly fine. You should start from here and modify as per your needs.
Entity
#Table(name="organization")
public class Organization {
#Id
#Column(name="org_Id")
private long id;
private String name, description;
#OneToMany(cascade = CascadeType.ALL)
private Collection<Person> personCollection = new ArrayList<Person>();
public Collection<Person> getPersonCollection() {
return personCollection;
}
public void setPersonCollection(Collection<Person> personCollection) {
this.personCollection = personCollection;
}
public Organization() {}
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 String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
and
#Entity
#Table(name = "Person")
public class Person {
#Id
#Column(name="person_Id")
private long id;
#Column(name="Email",unique = true)
private String email;
#Column(name="FirstName")
private String first_name;
#Column(name="LastName")
private String last_name;
#Column(name="Description")
private String description;
#ManyToOne()
private Organization organization;
public Organization getOrganization() {
return organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
public Person() {}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
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 String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
EDIT : The CascadeType.ALL from Person side of the relationship has been moved to the Organization side of the relationship.Because you want when organization is deleted Person should also get deleted, but not the other way round.
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.
I'm trying to use JPA for the first time in a project. Most of my entities are working fine, but I am having trouble with one which is part of a Joined Inheritance Strategy.The entities are also being serialised by Jackson so they also have Json annotations.
The parent "User" class:
(Edit: added "Type" field)
#JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include= JsonTypeInfo.As.WRAPPER_OBJECT)
#JsonTypeName("user")
#JsonSubTypes({
#JsonSubTypes.Type(name="customer", value=Customer.class),
#JsonSubTypes.Type(name="employee", value=Employee.class)})
#Entity(name = "User")
#Table(name="user")
#Inheritance(strategy = InheritanceType.JOINED)
#DiscriminatorColumn(name="type",discriminatorType = DiscriminatorType.INTEGER)
#NamedQuery(name="User.all",query = "select u from User u")
public abstract class User {
#Id
private String username;
#Column(name = "type",nullable = false)
private int type;
public User(){
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public abstract Set<Order> getOrders();
}
A Child "Employee"
#JsonTypeName("employee")
#Entity(name="Employee")
#Table(name="employee")
#PrimaryKeyJoinColumn(name = "username",referencedColumnName = "username")
#DiscriminatorValue("1")
#NamedQuery(name = "Employee.all",query = "select e from Employee e")
public class Employee extends User implements Serializable{
private String username;
private String firstName;
private String lastName;
private String email;
#Convert(converter = LocalDatePersistenceConverter.class)
private LocalDate dateStarted;
#Convert(converter = LocalDatePersistenceConverter.class)
private LocalDate dateEnded;
#OneToMany(mappedBy = "employee",targetEntity = Order.class,fetch = FetchType.EAGER,cascade = CascadeType.PERSIST)
#JsonIgnore
private Set<Order> orders = new HashSet<>();
public Employee() {
}
#Override
public Set<Order> getOrders() {
return orders;
}
public void setOrders(Set<Order> orders) {
this.orders = orders;
}
public void addOrder(Order order){
orders.add(order);
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getEmail() {
return email;
}
public String getDateStarted() {
if(dateStarted != null)
return dateStarted.toString();
else return null;
}
public void setDateStarted(LocalDate dateStarted) {
this.dateStarted = dateStarted;
}
public String getDateEnded() {
if(dateEnded != null)
return dateEnded.toString();
else return null;
}
public void setDateEnded(LocalDate dateEnded) {
this.dateEnded = dateEnded;
}
#Override
public String toString(){
return getUsername();
}
}
And a child "Customer":
(Edit: removed #Id field)
#JsonTypeName("customer")
#Entity(name="Customer")
#Table(name="customer")
#PrimaryKeyJoinColumn(name = "username",referencedColumnName = "username")
#DiscriminatorValue("2")
#NamedQueries({
#NamedQuery(name="Customer.all",query = "select c from Customer c")
})
public class Customer extends User implements Serializable{
public enum VIP_TYPE {NORMAL,SILVER,GOLD,DIAMOND}
#Transient
private static final int SILVER_THRESHOLD = 1000;
#Transient
private static final int GOLD_THRESHOLD = 2000;
#Transient
private static final int DIAMOND_THRESHOLD = 3000;
private String firstName;
private String lastName;
private String email;
private String address;
private String postcode;
private String mobileNumber;
private String homeNumber;
#Convert(converter = VipTypeConverter.class)
private VIP_TYPE vipGroup;
private String discount;
#OneToMany(mappedBy = "customer",targetEntity = Order.class,fetch=FetchType.EAGER,cascade = CascadeType.ALL)
#JsonIgnore
private Set<Order> orders = new HashSet<>();
public Customer() {
}
#Override
public Set<Order> getOrders() {
return orders;
}
public void setOrders(Set<Order> orders) {
this.orders = orders;
}
public void addOrder(final Order order){
orders.add(order);
updateVipGroup();
}
private void updateVipGroup() {
int sum = orders.stream().map(Order::getPayment).distinct().mapToInt(p->p.getAmmount()).sum();
if(sum > DIAMOND_THRESHOLD){
vipGroup = VIP_TYPE.DIAMOND;
return;
}
if(sum > GOLD_THRESHOLD){
vipGroup = VIP_TYPE.GOLD;
return;
}
if(sum > SILVER_THRESHOLD){
vipGroup = VIP_TYPE.SILVER;
return;
}
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setEmail(String email) {
this.email = email;
}
public void setAddress(String address) {
this.address = address;
}
public void setDiscount(String discount) {
this.discount = discount;
}
public void setVipGroup(VIP_TYPE vipGroup) {
this.vipGroup = vipGroup;
}
public void setHomeNumber(String homeNumber) {
this.homeNumber = homeNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public String getDiscount() {
return discount;
}
public VIP_TYPE getVipGroup() {
return vipGroup;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getEmail() {
return email;
}
public String getAddress() {
return address;
}
public String getPostcode() {
return postcode;
}
public String getMobileNumber() {
return mobileNumber;
}
public String getHomeNumber() {
return homeNumber;
}
}
Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="local" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/cod</jta-data-source>
<class>com.technicalpioneers.cod.user.Customer</class>
<class>com.technicalpioneers.cod.user.Employee</class>
<class>com.technicalpioneers.cod.user.User</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
</persistence-unit>
</persistence>
Everything to do with "employee" works file, I can use the named query Employee.all to find all the employees in the database.
However, If I try to retrieve any customers I get errors. If I try to run the named query Customer.all I get:
java.lang.IllegalArgumentException: NamedQuery of name: Customer.all not found.
If I try to use EntityManager's find() method to find a particular customer I get:
javax.servlet.ServletException: Exception [EclipseLink-43] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: Missing class for indicator field value [2] of type [class java.lang.Integer].
Descriptor: RelationalDescriptor(com.technicalpioneers.cod.user.User --> [DatabaseTable(user)])
I don't understand why the Customer entity is not being found by JPA. I've checked the user table and the "type" column is there with correct numbers, and #DescriminatorValue is set correctly. It's almost like the annotations are being ignored?
Have done many clean rebuilds and redeploys too. Any help would be very much appreciated!
I found this eventually. https://bugs.eclipse.org/bugs/show_bug.cgi?id=429992
It turns out EclipseLink will silently ignore entities with lambda expressions! Very annoying for it to not be at least mentioned in logs!
Thanks to everyone who took the time!