Following is my Entity class
#Entity
#Table(name = "USER_DETAILS")
public class UserDetails {
#Id
private int userId;
#Column (name="USER_NAME")
private String userName;
#Temporal(TemporalType.DATE)
private Date date;
#ElementCollection
private Set<Address> streetAddress = new HashSet<Address>();
public Set<Address> getStreetAddress() {
return streetAddress;
}
public void setStreetAddress(Set<Address> streetAddress) {
this.streetAddress = streetAddress;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
Following is Address class
public class Address {
private String city;
private String pin;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPin() {
return pin;
}
public void setPin(String pin) {
this.pin = pin;
}
}
And following is main class
public class HibernateMain {
public static void main(String[] args) {
Address address = new Address();
address.setCity("Pune");
address.setPin("1232");
Address homeAddress = new Address();
homeAddress.setCity("home_Pune");
homeAddress.setPin("home_1232");
UserDetails user = new UserDetails();
user.setUserId(3);
user.setUserName("Second user");
user.setDate(new Date());
user.getStreetAddress().add(address);
user.getStreetAddress().add(homeAddress);
Configuration cfg = new Configuration().configure("hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory(new ServiceRegistryBuilder()
.applySettings(cfg.getProperties()).build());
Session session = sf.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
session.close();
}
}
Exception is thrown at run time
Exception in thread "main" org.hibernate.MappingException: Could not determine type for: com.example.model.Address, at table: UserDetails_streetAddress, for columns: [org.hibernate.mapping.Column(streetAddress)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:336)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:310)
at org.hibernate.mapping.Collection.validate(Collection.java:315)
at org.hibernate.mapping.Set.validate(Set.java:40)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1362)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1849)
at com.example.hibernate.HibernateMain.main(HibernateMain.java:36)
I am using hibernate 4.3 and MySQL as database. If i dont use collection then it works for rest.What is wrong with code.
EDIT:
One other question.Am i using right code to get SessionFactory for my hibernate version as my IDE showing ServiceRegistryBuilder class as depricated.
Thanks for help.
The address class must be annotated with mapping annotations. Particularly, #Embeddable and if necessary #Column to map to the appropriate columns in the database.
#Embeddable
public class Address {
private String city;
private String pin;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPin() {
return pin;
}
public void setPin(String pin) {
this.pin = pin;
}
}
Related
I'm fairly new to Spring, and coding in general. I want to build an application from which a user can update existing records in a database from a CSV file. I'm using spring batch to do so, but when I execute the test, I get the famous:
java.lang.IllegalStateException: Existing transaction detected in JobRepository. Please fix this and try again (e.g. remove #Transactional annotations from client).
If I remove the #Transactional, I get this error instead:
org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for DML operations [UPDATE com.example.testApp.Models.Person p SET p.address = p.address, p.country = p.country, p.cellphone = p.cellphone, p.city = p.city, p.phone = p.cellphone, p.email = p.email, p.age = p.age WHERE p.pplId IN (:ids_0, :ids_1, :ids_2, :ids_3, :ids_4, :ids_5, :ids_6, :ids_7, :ids_8, :ids_9, :ids_10)]
I've looked around some other solutions here, but they don't seem to work for what I want to do. I'm aware that hibernate supports batch updates, but again, I'm not sure how to make it work with what I already have.
Here's my test class (obviously with just the method I've been having problems with):
#SpringBootTest
public class PersonTests {
#Autowired
private PeopleRepository peopleRepository;
#Autowired
JobLauncher jobLauncher;
#Autowired
Job peopleInsertJob; //Separate job for inserting from a CSV file
#Autowired
Job peopleUpdateJob;
#Order(4) //executes after the insert from CSV test, for obvious reasons.
#Test
public void updateRecordsFromCsvFile() throws Exception {
Map<String, JobParameter> maps = new HashMap<>();
maps.put("time", new JobParameter(System.currentTimeMillis()));
JobParameters parameters = new JobParameters(maps);
JobExecution jobExecution = jobLauncher.run(peopleUpdateJob, parameters);
assertEquals("COMPLETED", jobExecution.getStatus().name());
}
}
Here's my Batch configuration file for the update:
#Bean
public Job peopleUpdateJob(JobBuilderFactory jobBuilderFactory,
StepBuilderFactory stepBuilderFactory,
ItemReader<Person> itemReaderForUpdate,
ItemProcessor<Person, Person> itemProcessor,
#Qualifier("DBPeopleUpdater") ItemWriter<Person> itemUpdater)
{
Step step = stepBuilderFactory.get("ETL-file-load")
.<People, People>chunk(100)
.reader(itemReaderForUpdate)
.processor(itemProcessor)
.writer(itemUpdater)
.build();
return jobBuilderFactory.get("ETL-Load")
.incrementer(new RunIdIncrementer())
.start(step)
.build();
}
#Bean
public FlatFileItemReader itemReaderForUpdate() throws Exception
{
FlatFileItemReader<Person> flatFileItemReader = new FlatFileItemReader<>();
flatFileItemReader.setResource(new FileSystemResource("src/main/resources/CSV/TestFilePeople-UpdateBatch.csv"));
flatFileItemReader.setName("PeopleCSV-Update-Reader");
flatFileItemReader.setLinesToSkip(1);
flatFileItemReader.setLineMapper(lineMapper());
return flatFileItemReader;
}
#Bean
public LineMapper<Person> lineMapper()
{
DefaultLineMapper<Person> defaultLineMapper = new DefaultLineMapper<>();
DelimitedLineTokenizer lineTokenizer = new DelimitedLineTokenizer();
lineTokenizer.setDelimiter(",");
lineTokenizer.setStrict(false);
lineTokenizer.setNames("Id","lastname", "lastname2", "firstname",
"midname","phone", "cellphone", "email", "status", "address", "city", "region", "country");
BeanWrapperFieldSetMapper<Person> fieldSetMapper = new BeanWrapperFieldSetMapper<>();
fieldSetMapper.setTargetType(Person.class);
defaultLineMapper.setLineTokenizer(lineTokenizer);
defaultLineMapper.setFieldSetMapper(fieldSetMapper);
return defaultLineMapper;
}
This is the ItemWriter I'm using for the update:
#Component
public class DBPeopleUpdater implements ItemWriter<Person> {
#Autowired
PeopleRepository peopleRepository;
#Override
public void write(List<? extends Person> list) throws Exception
{
List<String> pplIds = new ArrayList<>();
for(People p : list)
{
pplIds.add(p.getpplId());
}
peopleRepository.updatePersonsByIdIsIn(pplIds);
}
}
This is the method that I'm using from my PeopleRepository. It's the only method I have. My repository is extends CrudRepository:
#Modifying
#Query("UPDATE Person p SET p.address= p.address, p.country = p.country," +
"p.cellphone = p.cellphone, p.city = p.city, p.phone = p.cellphone," +
"p.email = p.email, p.status = p.status WHERE p.pplId IN :ids")
List<Person>updatePersonsByPplIdIsIn(List<String> ids);
I'm mapping my Person class as an entity that connects to a PostgreSQL database table. I don't have any local sql files in my project. I have no other tables in the database.
If it's not possible to solve this using spring batch, if you could guide me towards jpa/hibernate resources I could use to understand how to solve this problem, I would really appreciate it.
EDIT
Here's the code for the entity
#Entity
#Table(name = "people", schema = "example_schema")
public class Person {
#NonNull
#Id
#Column(name = "ppl_id")
private String pplId;
#Column(name = "ppl_last_name")
private String lastname;
#Column(name = "ppl_sec_last_name")
private String lastname2;
#Column(name = "ppl_first_name")
private String firstname;
#Column(name = "ppl_mid_name")
private String midname;
#Column(name = "ppl_phone_no")
private String phone;
#Column(name = "ppl_cell_no")
private String cellphone;
#Column(name = "ppl_corp_email")
private String email;
#Column(name="ppl_status")
private String status;
#Column(name="ppl_address")
private String address;
#Column(name="ppl_city")
private String city;
#Column(name="ppl_region")
private String region;
#Column(name="ppl_country")
private String country;
//Default constructor
public Person()
{
super();
}
public Person(#NonNull String pplId, String lastname, String lastname2, String firstname, String midname, String phone, String cellphone, String email, String status, String address, String city, String region, String country) {
this.pplId = pplId;
this.lastname = lastname;
this.lastname2 = lastname2;
this.firstname = firstname;
this.midname = midname;
this.phone = phone;
this.cellphone = cellphone;
this.email = email;
this.status = status;
this.address = address;
this.city = city;
this.region = region;
this.country = country;
}
public String getPplId() {
return pplId;
}
public void setWrkId(String pplId) {
this.pplId = pplId;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getLastname2() {
return lastname2;
}
public void setLastname2(String lastname2) {
this.lastname2 = lastname2;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getMidname() {
return midname;
}
public void setMidname(String midname) {
this.midname = midname;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getCellphone() {
return cellphone;
}
public void setCellphone(String cellphone) {
this.cellphone = cellphone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
Main method
EntityManagerFactory emf=Persistence.createEntityManagerFactory("manager1");
EntityManager em1=emf.createEntityManager();
EntityTransaction entityTransaction=em1.getTransaction();
entityTransaction.begin();
Person persons=JPA_basic_Example.setPerson();//fills all the fields of person
Credential cred=JPA_basic_Example.setCredential();//fills all fields of credentials
System.out.println("check1");
cred.setPerson(persons);
persons.setCredential(cred);
em1.persist(cred);
entityTransaction.commit();
em1.close();
emf.close();
Java Bean Credential oneToone Bidirectional with Person
public class Credential {
#Id
#Column(name ="credentialid")
private int credential_id;
private String UserName;
private String Password;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name="Personid")
private Person person;
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public int getCredential_id() {
return credential_id;
}
public void setCredential_id(int credential_id) {
this.credential_id = credential_id;
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
Java Bean Person
#Entity
public class Person {
#Id
#Column(name ="Personid")
private int person_id;
//#Basic(optional = false)
//#Column(name ="Name", unique = true)
private String name;
#ElementCollection
#CollectionTable
List<String> contact=new ArrayList<String>();
private Address address=new Address();
#OneToOne(mappedBy = "person", orphanRemoval = true )
Credential credential ;
public Credential getCredential() {
return credential;
}
public void setCredential(Credential credential) {
this.credential = credential;
}
public List<String> getContact() {
return contact;
}
public void setContact(List<String> contact) {
this.contact = contact;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPerson_id() {
return person_id;
}
public void setPerson_id(int person_id) {
this.person_id = person_id;
}
}
Output Console
Hibernate:
insert
into
Person
(area, city, pincode, state, name, Personid)
values
(?, ?, ?, ?, ?, ?)
AFter this code stuck and nit moving forward nor showing any exceptions or errors
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;
}
...
}
I have a problem with Hibernate. Im struggling with this since yesterday, it seems very easy but I have no idea why it is not working...
I have entity Login.java:
package offersmanager.model.entity;
import org.json.JSONObject;
import javax.persistence.*;
#Entity
public class Login {
#Id
#GeneratedValue
private Integer id;
#Column(nullable = false, unique = true)
String username;
#Column(nullable = false)
String password;
public Login(){
}
public Login(String username, String password){
this.username = username;
this.password = password;
}
public Login(JSONObject jsonObject) {
this.id = (Integer) jsonObject.get("id");
this.username = (String) jsonObject.get("username");
this.password = (String) jsonObject.get("password");
}
public JSONObject toJsonObject() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", this.id);
jsonObject.put("username", this.username);
jsonObject.put("password", this.password);
return jsonObject;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
And entity TourOffice.java:
package offersmanager.model.entity;
import org.json.JSONObject;
import javax.persistence.*;
#Entity
public class TourOffice {
#Id
#GeneratedValue
private Integer id;
#Column(nullable = false)
String officeName;
#Column(nullable = false)
String eMail;
#Column(nullable = false)
String phoneNumber;
#Column(nullable = false)
String city;
#Column(nullable = false)
String zipCode;
#Column(nullable = false)
String address;
#OneToOne(cascade = {CascadeType.ALL})
#JoinColumn(name = "login_id")
Login login;
public TourOffice(){
}
public TourOffice(String officeName, String eMail, String phoneNumber, String city, String zipCode, String address) {
this.officeName = officeName;
this.eMail = eMail;
this.phoneNumber = phoneNumber;
this.city = city;
this.zipCode = zipCode;
this.address = address;
}
public TourOffice(JSONObject jsonObject) {
this.id = (Integer) jsonObject.get("id");
this.officeName = (String) jsonObject.get("officeName");
this.eMail = (String) jsonObject.get("eMail");
this.phoneNumber = (String) jsonObject.get("phoneNumber");
this.city = (String) jsonObject.get("city");
this.zipCode = (String) jsonObject.get("zipCode");
this.address = (String) jsonObject.get("address");
this.login = (new Login((JSONObject) jsonObject.get("login")));
}
public JSONObject toJsonObject() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", this.id);
jsonObject.put("officeName", this.officeName);
jsonObject.put("eMail", this.eMail);
jsonObject.put("phoneNumber", this.phoneNumber);
jsonObject.put("city", this.city);
jsonObject.put("zipCode", this.zipCode);
jsonObject.put("address", this.address);
jsonObject.put("login", this.login == null? null : login.toJsonObject());
return jsonObject;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getOfficeName() {
return officeName;
}
public void setOfficeName(String officeName) {
this.officeName = officeName;
}
public String geteMail() {
return eMail;
}
public void seteMail(String eMail) {
this.eMail = eMail;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Login getLogin() {
return login;
}
public void setLogin(Login login) {
this.login = login;
}
}
These entities are connected with #OneToOne relation.
What I'm trying to do is to find the name of my office (officeName) with field of Login class (username).
This is my function in TourOfficeDAO.java:
public TourOffice findOfficeNameByLogin(String username) {
Criteria name = createCriteria();
name.add(Restrictions.eq("login.username", username));
return (TourOffice) name.uniqueResult();
}
It goes through TourOfficeService to my rest controller where this method is invoked. But it doesn't matter cause exeception is thrown in DAO:
could not resolve property: login.username of:
offersmanager.model.entity.TourOffice; nested exception is
org.hibernate.QueryException: could not resolve property:
login.username of: offersmanager.model.entity.TourOffice
It can't find "login.username" and have no idea why... everything seems good.
I looked for similiar topics but I haven't still managed to make this works. Any help would be appreciated.
EDIT 1:
This is my abstract class DAO.java where is the function createCriteria()
public abstract class DAO<MODEL> implements Serializable {
public abstract Class<MODEL> getEntityClass();
#Autowired
protected SessionFactory sessionFactory;
protected Session getSession(){
return sessionFactory.getCurrentSession();
}
protected Query createQuery(String query){
return getSession().createQuery(query);
}
protected SQLQuery createSQLQuery(String query){
return getSession().createSQLQuery(query);
}
protected Criteria createCriteria(){
return getSession().createCriteria(getEntityClass());
}
#SuppressWarnings("unchecked")
public MODEL findById(Integer id) {
return (MODEL) getSession().get(getEntityClass(), id);
}
public void save(MODEL entity) {
getSession().save(entity);
getSession().flush();
}
public void update(MODEL entity) {
getSession().update(entity);
getSession().flush();
}
public void saveOrUpdate(MODEL entity) {
getSession().saveOrUpdate(entity);
getSession().flush();
}
public void delete(MODEL entity) {
getSession().delete(entity);
getSession().flush();
}
public List<MODEL> list(){
Criteria criteria = createCriteria();
#SuppressWarnings("unchecked")
List<MODEL> list = criteria.list();
return list;
}
}
I think you need first to create an alias like that:
public TourOffice findOfficeNameByLogin(String username) {
Criteria name = createCriteria();
name.createAlias("login", "login");
name.add(Restrictions.eq("login.username", username));
return (TourOffice) name.uniqueResult();
}
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!