I am facing following problem while inserting data into table using single inheritance in jpa.
run:
[EL Info]: 2014-04-17 22:40:45.947--ServerSession(863001717)--EclipseLink, version: Eclipse Persistence Services - 2.2.0.v20110202-r8913
[EL Info]: 2014-04-17 22:40:46.387--ServerSession(863001717)--file:/C:/Users/xone/Documents/NetBeansProjects/JPAAditiDAS/build/classes/_TESTJPAPU login successful
[EL Warning]: 2014-04-17 22:40:46.469--ClientSession(1037426453)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.2.0.v20110202-r8913): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'customerjpa.sequence' doesn't exist
Error Code: 1146
Call: UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?
bind => [2 parameters bound]
Query: DataModifyQuery(name="SEQUENCE" sql="UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?")
Exception in thread "main" Local Exception Stack:
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.2.0.v20110202-r8913): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'customerjpa.sequence' doesn't exist
Error Code: 1146
Call: UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?
bind => [2 parameters bound]
Query: DataModifyQuery(name="SEQUENCE" sql="UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?")
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:324)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:798)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeNoSelect(DatabaseAccessor.java:864)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:583)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:526)
at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:1729)
at org.eclipse.persistence.sessions.server.ClientSession.executeCall(ClientSession.java:234)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:207)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:193)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeNoSelectCall(DatasourceCallQueryMechanism.java:236)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeNoSelect(DatasourceCallQueryMechanism.java:216)
at org.eclipse.persistence.queries.DataModifyQuery.executeDatabaseQuery(DataModifyQuery.java:85)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:808)
at org.eclipse.persistence.internal.sessions.AbstractSession.internalExecuteQuery(AbstractSession.java:2800)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1521)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1503)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1477)
at org.eclipse.persistence.sequencing.QuerySequence.update(QuerySequence.java:336)
at org.eclipse.persistence.sequencing.QuerySequence.updateAndSelectSequence(QuerySequence.java:275)
at org.eclipse.persistence.sequencing.StandardSequence.getGeneratedVector(StandardSequence.java:71)
at org.eclipse.persistence.sequencing.DefaultSequence.getGeneratedVector(DefaultSequence.java:163)
at org.eclipse.persistence.sequencing.Sequence.getGeneratedVector(Sequence.java:257)
at org.eclipse.persistence.internal.sequencing.SequencingManager$Preallocation_Transaction_NoAccessor_State.getNextValue(SequencingManager.java:474)
at org.eclipse.persistence.internal.sequencing.SequencingManager.getNextValue(SequencingManager.java:961)
at org.eclipse.persistence.internal.sequencing.ClientSessionSequencing.getNextValue(ClientSessionSequencing.java:70)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.assignSequenceNumber(ObjectBuilder.java:292)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.assignSequenceNumber(UnitOfWorkImpl.java:454)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNotRegisteredNewObjectForPersist(UnitOfWorkImpl.java:4190)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.registerNotRegisteredNewObjectForPersist(RepeatableWriteUnitOfWork.java:493)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4135)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:406)
at test.SingleInheritenceCustTest.main(SingleInheritenceCustTest.java:35)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'customerjpa.sequence' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1053)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4120)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2794)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2458)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2375)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2359)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:789)
... 30 more
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)
Main Class:
package test;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;
import entity.CustomerSingle;
import entity.OnlineCustomer;
/*
* This is a test class for testing Single table inheritance
*/
public class SingleInheritenceCustTest {
public static void main(String[] args) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("TESTJPAPU");
EntityManager em = entityManagerFactory.createEntityManager();
EntityTransaction userTransaction = em.getTransaction();
userTransaction.begin();
//inserting Customer
CustomerSingle customer = new CustomerSingle();
customer.setFirstName("Antony");
customer.setLastName("John");
customer.setCustType("RETAIL");
customer.getAddress().setStreet("1 Broad street");
customer.getAddress().setAppt("111");
customer.getAddress().setCity("NewYork");
customer.getAddress().setZipCode("23456");
em.persist(customer);
inserting Online Customer
OnlineCustomer onlineCust = new OnlineCustomer();
onlineCust.setFirstName("Henry");
onlineCust.setLastName("Ho");
onlineCust.setCustType("ONLINE");
onlineCust.getAddress().setStreet("1 Mission Street");
onlineCust.getAddress().setAppt("222");
onlineCust.getAddress().setCity("Seatle");
onlineCust.getAddress().setZipCode("33345");
onlineCust.setWebsite("www.amazon.com");
em.persist(onlineCust);
userTransaction.commit();
// fetch only the online customers
/*Query query = em.createQuery("SELECT customer FROM ONLINECUSTOMER customer");
List<OnlineCustomer> list= query.getResultList();
System.out.println("The list is: "+ list);
for(int i=0;i<list.size();i++){
System.out.println("ONLINE CUSTOMER ["+ i +"] " + list.get(i));
}*/
em.close();
entityManagerFactory.close();
}
}
Entity Class CustomerSingle:
It contains common features of customer. It is used to insert data by using discrimination value "RETAIL"
package entity;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
/*
* CUSTOMER ENTITY CLASS -> This is an example of Single table inheritance
*/
#Table(name="CUSTOMER")
#Entity(name = "CUSTOMER2") //Name of the entity
#Inheritance(strategy=InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name="CUST_TYPE", discriminatorType=DiscriminatorType.STRING,length=10)
#DiscriminatorValue("RETAIL")
public class CustomerSingle implements Serializable{
#Id //signifies the primary key
#Column(name = "CUST_ID", nullable = false)
#GeneratedValue(strategy = GenerationType.AUTO)
private long custId;
#Column(name = "FIRST_NAME", nullable = false,length = 50)
private String firstName;
#Column(name = "LAST_NAME", length = 50)
private String lastName;
#Embedded
private Address address = new Address();
#Column(name = "CUST_TYPE", length = 10)
private String custType;
#Column(name = "LAST_UPDATED_TIME")
#Temporal(TemporalType.TIMESTAMP)
private Date updatedTime;
public long getCustId() {
return custId;
}
public void setCustId(long custId) {
this.custId = custId;
}
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 Date getUpdatedTime() {
return updatedTime;
}
public void setUpdatedTime(Date updatedTime) {
this.updatedTime = updatedTime;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String getCustType() {
return custType;
}
public void setCustType(String custType) {
this.custType = custType;
}
//
ToString()
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("custId : " + custId);
sb.append(" First Name : " + firstName);
sb.append(" Last Name : " + lastName);
sb.append(" customer type : " + custType);
return sb.toString();
}
}
ONLINECUSTOMER is an another entity class which extends CUSTOMERSINGLE. It is used to insert data by usinf discrimination value "ONLINE"
package entity;
import javax.persistence.*;
/*
* ONLINE CUSTOMER ENTITY CLASS -> This is an example of Single table inheritance
*/
#Entity(name = "ONLINECUSTOMER") //Name of the entity
#DiscriminatorValue("ONLINE")
public class OnlineCustomer extends CustomerSingle{
#Column(name = "WEBSITE", length = 100)
private String website;
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(super.toString());
sb.append(" website: "+website);
return sb.toString();
}
}
The exception is caused due to a missing sequence table in the underlying database:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
Table 'customerjpa.sequence' doesn't exist
There are two solutions depending on the configuration:
Let EclipseLink do it for you by specifying eclipselink.ddl-generation in pesistence.xml. (preferred)
Create sequence manually by executing SQL statement.
Related
I'm having issues when trying to deploy my enterprise java bean application to GlassFish server 5.1.0. My errors are shown here:
Exception while deploying the app [ED-EMS-SLSB]|#]
Exception during lifecycle processing
org.glassfish.deployment.common.DeploymentException: Exception [EclipseLink-28019] (Eclipse Persistence Services - 2.7.4.v20190115-ad5b7c6b2a): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Deployment of PersistenceUnit [ED-EMS-SLSB-ejbPU] failed. Close all factories for this PersistenceUnit.
Internal Exception: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.7.4.v20190115-ad5b7c6b2a): org.eclipse.persistence.exceptions.IntegrityException
Descriptor Exceptions:
---------------------------------------------------------
Exception [EclipseLink-168] (Eclipse Persistence Services - 2.7.4.v20190115-ad5b7c6b2a): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: Problem in creating new instance using the default constructor. The default constructor triggered an exception.
Internal Exception: java.lang.reflect.InvocationTargetException
Target Invocation Exception: java.lang.RuntimeException:
Descriptor: RelationalDescriptor(entity.EmsEmployee --> [DatabaseTable(EMS_EMPLOYEE)])
Runtime Exceptions:
---------------------------------------------------------
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.createDeployFailedPersistenceException(EntityManagerSetupImpl.java:908)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:848)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getAbstractSession(EntityManagerFactoryDelegate.java:219)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.createEntityManagerImpl(EntityManagerFactoryDelegate.java:327)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:350)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:313)
at org.glassfish.persistence.jpa.JPADeployer$2.visitPUD(JPADeployer.java:427)
at org.glassfish.persistence.jpa.JPADeployer$PersistenceUnitDescriptorIterator.iteratePUDs(JPADeployer.java:486)
at org.glassfish.persistence.jpa.JPADeployer.iterateInitializedPUsAtApplicationPrepare(JPADeployer.java:468)
at org.glassfish.persistence.jpa.JPADeployer.event(JPADeployer.java:371)
at org.glassfish.kernel.event.EventsImpl.send(EventsImpl.java:107)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:463)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:195)
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:467)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:516)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:512)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:360)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:511)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:542)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:534)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:360)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:533)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1441)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:86)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1823)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1699)
at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:510)
at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:200)
at org.glassfish.grizzly.http.server.StaticHttpHandlerBase.service(StaticHttpHandlerBase.java:166)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:439)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:144)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:182)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:156)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:218)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:95)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:260)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:177)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:109)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:88)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:53)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:515)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:89)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:94)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:33)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:114)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:569)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:549)
at java.lang.Thread.run(Thread.java:748)
|#]
Exception while deploying the app [ED-EMS-SLSB] : Exception [EclipseLink-28019] (Eclipse Persistence Services - 2.7.4.v20190115-ad5b7c6b2a): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Deployment of PersistenceUnit [ED-EMS-SLSB-ejbPU] failed. Close all factories for this PersistenceUnit.
Internal Exception: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.7.4.v20190115-ad5b7c6b2a): org.eclipse.persistence.exceptions.IntegrityException
Descriptor Exceptions:
---------------------------------------------------------
Exception [EclipseLink-168] (Eclipse Persistence Services - 2.7.4.v20190115-ad5b7c6b2a): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: Problem in creating new instance using the default constructor. The default constructor triggered an exception.
Internal Exception: java.lang.reflect.InvocationTargetException
Target Invocation Exception: java.lang.RuntimeException:
Descriptor: RelationalDescriptor(entity.EmsEmployee --> [DatabaseTable(EMS_EMPLOYEE)])
Runtime Exceptions:
---------------------------------------------------------
|#]
I'm hoping someone could shed some light on this as this is my first time dealing with Enterprise Java Beans and I find it to be very difficult, considering that everything has to be setup a certain way. If anyone can recommend something or point me in the right direction, that'll be great.
Edit:
This is my entity class EmsEmployee.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entity;
import java.io.Serializable;
import java.math.BigDecimal;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author jeremy
*/
#Entity
#Table(name = "EMS_EMPLOYEE")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "EmsEmployee.findAll", query = "SELECT e FROM EmsEmployee e"),
#NamedQuery(name = "EmsEmployee.findByEmpid", query = "SELECT e FROM EmsEmployee e WHERE e.empid = :empid"),
#NamedQuery(name = "EmsEmployee.findByName", query = "SELECT e FROM EmsEmployee e WHERE e.name = :name"),
#NamedQuery(name = "EmsEmployee.findByPassword", query = "SELECT e FROM EmsEmployee e WHERE e.password = :password"),
#NamedQuery(name = "EmsEmployee.findByEmail", query = "SELECT e FROM EmsEmployee e WHERE e.email = :email"),
#NamedQuery(name = "EmsEmployee.findByPhone", query = "SELECT e FROM EmsEmployee e WHERE e.phone = :phone"),
#NamedQuery(name = "EmsEmployee.findByAddress", query = "SELECT e FROM EmsEmployee e WHERE e.address = :address"),
#NamedQuery(name = "EmsEmployee.findBySecqn", query = "SELECT e FROM EmsEmployee e WHERE e.secqn = :secqn"),
#NamedQuery(name = "EmsEmployee.findBySecans", query = "SELECT e FROM EmsEmployee e WHERE e.secans = :secans"),
#NamedQuery(name = "EmsEmployee.findByBsbid", query = "SELECT e FROM EmsEmployee e WHERE e.bsbid = :bsbid"),
#NamedQuery(name = "EmsEmployee.findByAccid", query = "SELECT e FROM EmsEmployee e WHERE e.accid = :accid"),
#NamedQuery(name = "EmsEmployee.findBySalary", query = "SELECT e FROM EmsEmployee e WHERE e.salary = :salary"),
#NamedQuery(name = "EmsEmployee.findByAppgroup", query = "SELECT e FROM EmsEmployee e WHERE e.appgroup = :appgroup"),
#NamedQuery(name = "EmsEmployee.findByActive", query = "SELECT e FROM EmsEmployee e WHERE e.active = :active"),
#NamedQuery(name = "EmsEmployee.findByMemo", query = "SELECT e FROM EmsEmployee e WHERE e.memo = :memo")})
public class EmsEmployee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 6)
#Column(name = "EMPID")
private String empid;
#Size(max = 50)
#Column(name = "NAME")
private String name;
#Size(max = 64)
#Column(name = "PASSWORD")
private String password;
// #Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation
#Size(max = 50)
#Column(name = "EMAIL")
private String email;
// #Pattern(regexp="^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$", message="Invalid phone/fax format, should be as xxx-xxx-xxxx")//if the field contains phone or fax number consider using this annotation to enforce field validation
#Size(max = 10)
#Column(name = "PHONE")
private String phone;
#Size(max = 50)
#Column(name = "ADDRESS")
private String address;
#Size(max = 60)
#Column(name = "SECQN")
private String secqn;
#Size(max = 60)
#Column(name = "SECANS")
private String secans;
#Size(max = 6)
#Column(name = "BSBID")
private String bsbid;
#Size(max = 10)
#Column(name = "ACCID")
private String accid;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Column(name = "SALARY")
private BigDecimal salary;
#Size(max = 15)
#Column(name = "APPGROUP")
private String appgroup;
#Column(name = "ACTIVE")
private Boolean active;
#Size(max = 255)
#Column(name = "MEMO")
private String memo;
public EmsEmployee() {
}
public EmsEmployee(String empid) {
this.empid = empid;
}
public String getEmpid() {
return empid;
}
public void setEmpid(String empid) {
this.empid = empid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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 String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSecqn() {
return secqn;
}
public void setSecqn(String secqn) {
this.secqn = secqn;
}
public String getSecans() {
return secans;
}
public void setSecans(String secans) {
this.secans = secans;
}
public String getBsbid() {
return bsbid;
}
public void setBsbid(String bsbid) {
this.bsbid = bsbid;
}
public String getAccid() {
return accid;
}
public void setAccid(String accid) {
this.accid = accid;
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public String getAppgroup() {
return appgroup;
}
public void setAppgroup(String appgroup) {
this.appgroup = appgroup;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
#Override
public int hashCode() {
int hash = 0;
hash += (empid != null ? empid.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof EmsEmployee)) {
return false;
}
EmsEmployee other = (EmsEmployee) object;
if ((this.empid == null && other.empid != null) || (this.empid != null && !this.empid.equals(other.empid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entity.EmsEmployee[ empid=" + empid + " ]";
}
}
This is my stateless session bean class EmsEmployeeFacade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package session;
import entity.EmsEmployee;
import entity.EmsEmployeeDTO;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* #author jeremy
*/
#Stateless
public class EmsEmployeeFacade implements EmsEmployeeFacadeRemote {
#PersistenceContext(unitName = "ED-EMS-SLSB-ejbPU")
private EntityManager em;
protected EntityManager getEntityManager() {
return em;
}
private void create(EmsEmployee emsEmployee) {
em.persist(emsEmployee);
}
private void edit(EmsEmployee emsEmployee) {
em.merge(emsEmployee);
}
private void remove(EmsEmployee emsEmployee) {
em.remove(em.merge(emsEmployee));
}
private EmsEmployee find(Object id) {
return em.find(EmsEmployee.class, id);
}
private EmsEmployee myDTO2DAO(EmsEmployeeDTO emsEmployeeDTO) {
EmsEmployee emsEmployee = new EmsEmployee();
emsEmployee.setEmpid(emsEmployeeDTO.getEmpid());
emsEmployee.setName(emsEmployeeDTO.getName());
emsEmployee.setPassword(emsEmployeeDTO.getPassword());
emsEmployee.setEmail(emsEmployeeDTO.getEmail());
emsEmployee.setPhone(emsEmployeeDTO.getPhone());
emsEmployee.setAddress(emsEmployeeDTO.getAddress());
emsEmployee.setSecqn(emsEmployeeDTO.getSecqn());
emsEmployee.setSecans(emsEmployeeDTO.getSecans());
emsEmployee.setBsbid(emsEmployeeDTO.getBsbid());
emsEmployee.setAccid(emsEmployeeDTO.getAccid());
emsEmployee.setSalary(emsEmployeeDTO.getSalary());
emsEmployee.setAppgroup(emsEmployeeDTO.getAppgroup());
emsEmployee.setActive(emsEmployeeDTO.getActive());
emsEmployee.setMemo(emsEmployeeDTO.getMemo());
return emsEmployee;
}
#Override
public boolean createRecord(EmsEmployeeDTO emsEmployeeDTO) {
// try to find the database record in the database first
EmsEmployee tmpEmployee = em.find(EmsEmployee.class, emsEmployeeDTO.getEmpid());
if (tmpEmployee != null) {
// employee whose empid can be found; should not add the record
return false;
}
// employee whose empid could not be found; add it to the database
try {
// convert a DTO to DAO
EmsEmployee emsEmployee = this.myDTO2DAO(emsEmployeeDTO);
// add to database via JPA
this.create(emsEmployee);
return true;
} catch (Exception ex) {
// something is wrong, should not be here though
return false;
}
}
}
You are using GlassFish 5.1.0 and this only supports Java 8.
I assume that you are using a newer Java version (probably 14) that causes this exception.
I've this Java application in package com.luv2code.hibernate.demo:
package com.luv2code.hibernate.demo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.luv2code.hibernate.demo.entity.Employee;
public class CreateEmployeeDemo {
public static void main(String[] args) {
// create session factory
SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Employee.class)
.buildSessionFactory();
// create a session
Session session = factory.getCurrentSession();
try {
// create the employee object
System.out.println("Creating a new employee object...");
Employee tempEmployee = new Employee("John", "Doe", "Doe Corp.");
// start a transaction
session.beginTransaction();
// save the employee object
System.out.println("Saving the employee...");
session.save(tempEmployee);
// commit the transaction
session.getTransaction().commit();
// find the employee's ID: primary key
System.out.println("Save employee. Generated ID: " + tempEmployee.getId());
// now get a new session and start transaction
session = factory.getCurrentSession();
session.beginTransaction();
// retrieve employee based on the ID: primary key
System.out.println("\nGettin employee with id: " + tempEmployee.getId());
Employee myEmployee = session.get(Employee.class, tempEmployee.getId());
System.out.println("Get complete: " + myEmployee);
// commit the transaction
session.getTransaction().commit();
// delete student id=2
System.out.println("Deleting student id=2");
session.createQuery("delete from Student where id = '2'").executeUpdate();
// commit the transaction
session.getTransaction().commit();
System.out.println("Done!");
}
finally {
factory.close();
}
}
}
It uses this Employee class in package com.luv2code.hibernate.demo.entity:
package com.luv2code.hibernate.demo.entity;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
public class Employee {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="first_name")
private String firstName;
#Column(name="last_name")
private String lastName;
#Column(name="company")
private String company;
public Employee() {
}
public Employee(String firstName, String lastName, String company) {
this.firstName = firstName;
this.lastName = lastName;
this.company = company;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
#Override
public String toString() {
return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", company=" + company + "]";
}
}
When I run the program I get this error:
Saving the employee...
Jul 17, 2020 6:46:40 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PoolState stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=false&serverTimezone=UTC]
Jul 17, 2020 6:46:40 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections close
ERROR: Connection leak detected: there are 1 unclosed connections upon shutting down pool jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=false&serverTimezone=UTC
Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.luv2code.hibernate.demo.entity.Employee
at org.hibernate.metamodel.internal.MetamodelImpl.entityPersister(MetamodelImpl.java:704)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1606)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:114)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:179)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:75)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:634)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:627)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:622)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:351)
at com.sun.proxy.$Proxy25.save(Unknown Source)
at com.luv2code.hibernate.demo.CreateEmployeeDemo.main(CreateEmployeeDemo.java:33)
I can't see what could be wrong here. It seems to be a mapping exception but I think my mappings should be correct. Can anybody spot the issue?
Use #Entity and #Table for map database table name with Employee class
#Entity
#Table(name = "employee")
public class Employee { ... }
I have a Java RESTapi, where I want to convert a list of my custom Pet object into Json, and display it in an endpoint.
This I what I have so far:
#Path("/allPets")
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response getPetsfromCollection() {
List<Pet> petList = new ArrayList<>();
petList.addAll(facade.returnAllPets());
String json = gson.toJson(petList);
//TODO return proper representation object
return Response.ok().entity(json).build();
}
I'm using the facade pattern where I have a method of adding Java entities to a list as such:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("PetHospitaljpa");
public Collection<Pet> returnAllPets (){
EntityManager em = emf.createEntityManager();
//vi laver en typed query for at specificere hvilken datatype,
// det er vi leder efter, i dette tilfælde er det en Pet
TypedQuery<Pet> query = em.createNamedQuery("Pet.findAll", Pet.class);
return query.getResultList();
}
I'm returning a collection in case I want to change the data structure of ArrayList to something else later.
I have tried several workarounds, but I keep getting a stack overflow error.
Iøm aware of the fact, that I need to use DTO's instead, and I have made a custom method to change entities to DTO's as such:
public static DTOPet converttoDTO(Pet entity){
DTOPet dto = new DTOPet();
dto.setId(entity.getId());
dto.setName(entity.getName());
dto.setBirth(entity.getBirth());
dto.setDeath(entity.getDeath());
dto.setSpecies(entity.getSpecies());
return dto;
}
I'm not sure if this is good code practice if I there is something else I can do instead to transform a collection of entities into DTO's?
As pointed out. The problem occurs because I have a circular reference.
inside my Pet Entity class:
#ManyToOne
private Owner ownerId;
inside my Owner Entity class:
#OneToMany(mappedBy = "ownerId")
private Collection<Pet> petCollection;
My Pet Class:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Entities;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* #author kristoffer
*/
#Entity
#Table(name = "pet")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Pet.findAll", query = "SELECT p FROM Pet p")
, #NamedQuery(name = "Pet.findById", query = "SELECT p FROM Pet p WHERE p.id = :id")
, #NamedQuery(name = "Pet.findByName", query = "SELECT p FROM Pet p WHERE p.name = :name")
, #NamedQuery(name = "Pet.findByBirth", query = "SELECT p FROM Pet p WHERE p.birth = :birth")
, #NamedQuery(name = "Pet.findBySpecies", query = "SELECT p FROM Pet p WHERE p.species = :species")
, #NamedQuery(name = "Pet.findByDeath", query = "SELECT p FROM Pet p WHERE p.death = :death")})
public class Pet implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "name")
private String name;
#Basic(optional = false)
#NotNull
#Column(name = "birth")
#Temporal(TemporalType.DATE)
private Date birth;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "species")
private String species;
#Column(name = "death")
#Temporal(TemporalType.DATE)
private Date death;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "petId")
private Collection<Event> eventCollection;
#JoinColumn(name = "owner_id", referencedColumnName = "id")
#ManyToOne
private Owner ownerId;
public Pet() {
}
public Pet(Integer id) {
this.id = id;
}
public Pet(Integer id, String name, Date birth, String species) {
this.id = id;
this.name = name;
this.birth = birth;
this.species = species;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
public Date getDeath() {
return death;
}
public void setDeath(Date death) {
this.death = death;
}
#XmlTransient
public Collection<Event> getEventCollection() {
return eventCollection;
}
public void setEventCollection(Collection<Event> eventCollection) {
this.eventCollection = eventCollection;
}
public Owner getOwnerId() {
return ownerId;
}
public void setOwnerId(Owner ownerId) {
this.ownerId = ownerId;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Pet)) {
return false;
}
Pet other = (Pet) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "Pet{" + "id=" + id + ", name=" + name + ", birth=" + birth + ", species=" + species + ", death=" + death + ", eventCollection=" + eventCollection + ", ownerId=" + ownerId + '}';
}
}
EDIT:
I tried creating a method, where I convert all the objects to DTO's, but the string is still empty when it is displayed:
#Path("/allPets")
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response getPetsfromCollection() {
//med denne metode skal vi bruge et DTO(data transfer object til at formatere til Json)
List<Pet> petList = new ArrayList<>();
List<DTOPet> DTOPetList = new ArrayList<>();
petList.addAll(facade.returnAllPets());
for(Pet pet: petList){
DTOPet dtopet = EntitytoDTO.converttoDTO(pet);
DTOPetList.add(dtopet);
}
String json = gson2.toJson(DTOPetList);
return Response.ok().entity(json).build();
}
When I use the debugger, the new list is created successfully, with the right parameters, but the String JSON is just created like this [{},{},{},{}], even though I use GSON
You need to detect what place of error. I recommend to add debug information, like
#Path("/allPets")
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response getPetsfromCollection() {
log.debug("getPetsfromCollection start");
List<Pet> petList = new ArrayList<>(facade.returnAllPets());
log.debug("petList" + petList.length());
String json = gson.toJson(petList);
log.debug("json " + json);
//TODO return proper representation object
return Response.ok().entity(json).build();
}
EntityManagerFactory emf = Persistence.createEntityManagerFactory("PetHospitaljpa");
public Collection<Pet> returnAllPets (){
log.debug("returnAllPets start");
EntityManager em = emf.createEntityManager();
log.debug("createNamedQuery start");
TypedQuery<Pet> query = em.createNamedQuery("Pet.findAll", Pet.class);
log.debug("single result" + query.getSingleResult() );
TypedQuery<Pet> query = em.createNamedQuery("Pet.findAll", Pet.class);
log.debug("list result" + query.getResultList());
TypedQuery<Pet> query = em.createNamedQuery("Pet.findAll", Pet.class);
return query.getResultList();
}
P.S. Also, please show Pet class, may be problem is with this class.
Update: I recommend also to try temporary delete:
#OneToMany(cascade = CascadeType.ALL, mappedBy = "petId")
private Collection<Event> eventCollection;
And / or
#JoinColumn(name = "owner_id", referencedColumnName = "id")
#ManyToOne
private Owner ownerId;
And check do you have such SO exception or not. It is look like Event or Owner table is too big or have circle dependencies.
Without seeing what the "Pet" class looks like, it is difficult to pinpoint the problem. I suspect you have a variable of another class in your Pet class that also has a reference to the pet class itself (creating a circular reference that would cause a stack overflow in the serialization process)
Tables script:
DROP TABLE IF EXISTS STOCK; CREATE TABLE STOCK ( STOCK_ID INT(10) NOT NULL, STOCK_CODE VARCHAR(10) NOT NULL, STOCK_NAME VARCHAR(20) NOT NULL, PRIMARY KEY (STOCK_ID,STOCK_CODE), KEY STOCK_CODE_IDX (STOCK_CODE) );
DROP TABLE IF EXISTS STOCK_DAILY_RECORD;
CREATE TABLE STOCK_DAILY_RECORD ( RECORD_ID INT(10) NOT NULL, STOCK_CODE VARCHAR(10) NOT NULL, PRICE_OPEN FLOAT(6,2) DEFAULT NULL, PRICE_CLOSE FLOAT(6,2) DEFAULT NULL, PRICE_CHANGE FLOAT(6,2) DEFAULT NULL, VOLUME BIGINT(20) DEFAULT NULL, STOCK_ID INT(10) NOT NULL, PRIMARY KEY (RECORD_ID,STOCK_CODE), KEY FK_STOCK_ID (STOCK_ID,STOCK_CODE), CONSTRAINT FK_STOCK_ID FOREIGN KEY (STOCK_ID,STOCK_CODE) REFERENCES STOCK (STOCK_ID,STOCK_CODE) ) ;
This is main class where I can populate the entity classes to save values in stock and stockdailyrecord tables:
package org.hibernate.HibernateEntity;
import org.hibernate.Session;
import com.model.Stock;
import com.model.StockDailyRecord;
import com.model.StockDailyRecordId;
import com.model.StockId;
/**
* Hello world!
*
*/
public class App
{
public static void main(String[] args) {
System.out.println("Hibernate one to one (Annotation)");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Stock stock = new Stock();
StockId id = new StockId(2, "7052");
stock.setId(id);
stock.setStockName("PADINI");
StockDailyRecord stockDetail = new StockDailyRecord();
StockDailyRecordId id1 = new StockDailyRecordId(101, "7052");
stockDetail.setId(id1);
stockDetail.setPriceChange(200.0f);
stockDetail.setPriceClose(210.0f);
stockDetail.setPriceOpen(120.0f);
stockDetail.setVolume(12l);
stock.getStockDailyRecords().add(stockDetail);
stockDetail.setStock(stock);
session.save(stock);
//session.save(stockDetail);
session.getTransaction().commit();
System.out.println("Done");
}
}
Entity class which is configured with composite key with hibernate embedded and id:
package com.model;
// Generated Jan 12, 2018 8:17:38 AM by Hibernate Tools 5.2.6.Final
import java.util.HashSet;
import java.util.Set;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
/**
* Stock generated by hbm2java
*/
#Entity
#Table(name = "stock", catalog = "testdb")
public class Stock implements java.io.Serializable {
private StockId id;
private String stockName;
private Set<StockDailyRecord> stockDailyRecords = new HashSet<StockDailyRecord>(0);
public Stock() {
}
public Stock(StockId id, String stockName) {
this.id = id;
this.stockName = stockName;
}
public Stock(StockId id, String stockName, Set<StockDailyRecord> stockDailyRecords) {
this.id = id;
this.stockName = stockName;
this.stockDailyRecords = stockDailyRecords;
}
#EmbeddedId
#AttributeOverrides({ #AttributeOverride(name = "stockId", column = #Column(name = "STOCK_ID", nullable = false)),
#AttributeOverride(name = "stockCode", column = #Column(name = "STOCK_CODE", nullable = false, length = 10)) })
public StockId getId() {
return this.id;
}
public void setId(StockId id) {
this.id = id;
}
#Column(name = "STOCK_NAME", nullable = false, length = 20)
public String getStockName() {
return this.stockName;
}
public void setStockName(String stockName) {
this.stockName = stockName;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "stock")
#Cascade(CascadeType.ALL)
public Set<StockDailyRecord> getStockDailyRecords() {
return this.stockDailyRecords;
}
public void setStockDailyRecords(Set<StockDailyRecord> stockDailyRecords) {
this.stockDailyRecords = stockDailyRecords;
}
}
Entity class which is configured with composite key with hibernate embedded and id:
package com.model;
// Generated Jan 12, 2018 8:17:38 AM by Hibernate Tools 5.2.6.Final
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* StockDailyRecord generated by hbm2java
*/
#Entity
#Table(name = "stock_daily_record", catalog = "testdb")
public class StockDailyRecord implements java.io.Serializable {
private StockDailyRecordId id;
private Stock stock;
private Float priceOpen;
private Float priceClose;
private Float priceChange;
private Long volume;
public StockDailyRecord() {
}
public StockDailyRecord(StockDailyRecordId id, Stock stock) {
this.id = id;
this.stock = stock;
}
public StockDailyRecord(StockDailyRecordId id, Stock stock, Float priceOpen, Float priceClose, Float priceChange,
Long volume) {
this.id = id;
this.stock = stock;
this.priceOpen = priceOpen;
this.priceClose = priceClose;
this.priceChange = priceChange;
this.volume = volume;
}
#EmbeddedId
#AttributeOverrides({ #AttributeOverride(name = "recordId", column = #Column(name = "RECORD_ID", nullable = false)),
#AttributeOverride(name = "stockCode", column = #Column(name = "STOCK_CODE", nullable = false, length = 10)) })
public StockDailyRecordId getId() {
return this.id;
}
public void setId(StockDailyRecordId id) {
this.id = id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumns({
#JoinColumn(name = "STOCK_ID", referencedColumnName = "STOCK_ID", nullable = false, insertable = false, updatable = false),
#JoinColumn(name = "STOCK_CODE", referencedColumnName = "STOCK_CODE", nullable = false, insertable = false, updatable = false) })
public Stock getStock() {
return this.stock;
}
public void setStock(Stock stock) {
this.stock = stock;
}
#Column(name = "PRICE_OPEN", precision = 6)
public Float getPriceOpen() {
return this.priceOpen;
}
public void setPriceOpen(Float priceOpen) {
this.priceOpen = priceOpen;
}
#Column(name = "PRICE_CLOSE", precision = 6)
public Float getPriceClose() {
return this.priceClose;
}
public void setPriceClose(Float priceClose) {
this.priceClose = priceClose;
}
#Column(name = "PRICE_CHANGE", precision = 6)
public Float getPriceChange() {
return this.priceChange;
}
public void setPriceChange(Float priceChange) {
this.priceChange = priceChange;
}
#Column(name = "VOLUME")
public Long getVolume() {
return this.volume;
}
public void setVolume(Long volume) {
this.volume = volume;
}
}
Entity class which is configured with composite key with hibernate embedded and id:
package com.model;
// Generated Jan 12, 2018 8:17:38 AM by Hibernate Tools 5.2.6.Final
import javax.persistence.Column;
import javax.persistence.Embeddable;
/**
* StockDailyRecordId generated by hbm2java
*/
#Embeddable
public class StockDailyRecordId implements java.io.Serializable {
private int recordId;
private String stockCode;
public StockDailyRecordId() {
}
public StockDailyRecordId(int recordId, String stockCode) {
this.recordId = recordId;
this.stockCode = stockCode;
}
#Column(name = "RECORD_ID", nullable = false)
public int getRecordId() {
return this.recordId;
}
public void setRecordId(int recordId) {
this.recordId = recordId;
}
#Column(name = "STOCK_CODE", nullable = false, length = 10)
public String getStockCode() {
return this.stockCode;
}
public void setStockCode(String stockCode) {
this.stockCode = stockCode;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof StockDailyRecordId))
return false;
StockDailyRecordId castOther = (StockDailyRecordId) other;
return (this.getRecordId() == castOther.getRecordId())
&& ((this.getStockCode() == castOther.getStockCode()) || (this.getStockCode() != null
&& castOther.getStockCode() != null && this.getStockCode().equals(castOther.getStockCode())));
}
public int hashCode() {
int result = 17;
result = 37 * result + this.getRecordId();
result = 37 * result + (getStockCode() == null ? 0 : this.getStockCode().hashCode());
return result;
}
}
Entity class which is configured with composite key with hibernate embedded and id:
package com.model;
// Generated Jan 12, 2018 8:17:38 AM by Hibernate Tools 5.2.6.Final
import javax.persistence.Column;
import javax.persistence.Embeddable;
/**
* StockId generated by hbm2java
*/
#Embeddable
public class StockId implements java.io.Serializable {
private int stockId;
private String stockCode;
public StockId() {
}
public StockId(int stockId, String stockCode) {
this.stockId = stockId;
this.stockCode = stockCode;
}
#Column(name = "STOCK_ID", nullable = false)
public int getStockId() {
return this.stockId;
}
public void setStockId(int stockId) {
this.stockId = stockId;
}
#Column(name = "STOCK_CODE", nullable = false, length = 10)
public String getStockCode() {
return this.stockCode;
}
public void setStockCode(String stockCode) {
this.stockCode = stockCode;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof StockId))
return false;
StockId castOther = (StockId) other;
return (this.getStockId() == castOther.getStockId())
&& ((this.getStockCode() == castOther.getStockCode()) || (this.getStockCode() != null
&& castOther.getStockCode() != null && this.getStockCode().equals(castOther.getStockCode())));
}
public int hashCode() {
int result = 17;
result = 37 * result + this.getStockId();
result = 37 * result + (getStockCode() == null ? 0 : this.getStockCode().hashCode());
return result;
}
}
Class used to create a session factory using hibernate configuration:
package org.hibernate.HibernateEntity;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
Stockdailyrecord not getting populated with stock id , please advice.
08:20:05.202 [main] DEBUG org.hibernate.pretty.Printer - listing entities:
08:20:05.203 [main] DEBUG org.hibernate.pretty.Printer - com.model.StockDailyRecord{priceChange=200.0, volume=12, priceClose=210.0, priceOpen=120.0, id=component[recordId,stockCode]{recordId=101, stockCode=7052}, stock=com.model.Stock#component[stockCode,stockId]{stockId=2, stockCode=7052}}
08:20:05.203 [main] DEBUG org.hibernate.pretty.Printer - com.model.Stock{stockName=PADINI, stockDailyRecords=[com.model.StockDailyRecord#component[recordId,stockCode]{recordId=101, stockCode=7052}], id=component[stockCode,stockId]{stockId=2, stockCode=7052}}
08:20:05.205 [main] DEBUG org.hibernate.jdbc.AbstractBatcher - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
08:20:05.206 [main] DEBUG org.hibernate.SQL - insert into testdb.stock (STOCK_NAME, STOCK_CODE, STOCK_ID) values (?, ?, ?)
08:20:05.207 [main] DEBUG org.hibernate.jdbc.AbstractBatcher - Executing batch size: 1
08:20:05.271 [main] DEBUG org.hibernate.jdbc.AbstractBatcher - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
08:20:05.271 [main] DEBUG org.hibernate.jdbc.AbstractBatcher - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
08:20:05.271 [main] DEBUG org.hibernate.SQL - insert into testdb.stock_daily_record (PRICE_CHANGE, PRICE_CLOSE, PRICE_OPEN, VOLUME, RECORD_ID, STOCK_CODE) values (?, ?, ?, ?, ?, ?)
08:20:05.277 [main] DEBUG org.hibernate.jdbc.AbstractBatcher - Executing batch size: 1
08:20:05.300 [main] DEBUG org.hibernate.jdbc.AbstractBatcher - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
08:20:05.315 [main] DEBUG o.h.util.JDBCExceptionReporter - Could not execute JDBC batch update [insert into testdb.stock_daily_record (PRICE_CHANGE, PRICE_CLOSE, PRICE_OPEN, VOLUME, RECORD_ID, STOCK_CODE) values (?, ?, ?, ?, ?, ?)]
java.sql.BatchUpdateException: Field 'STOCK_ID' doesn't have a default value
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:2024) ~[mysql-connector-java-5.1.15.jar:na]
at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1449) ~[mysql-connector-java-5.1.15.jar:na]
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70) ~[hibernate-core-3.6.3.Final.jar:3.6.3.Final]
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268) ~[hibernate-core-3.6.3.Final.jar:3.6.3.Final]
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:268) [hibernate-core-3.6.3.Final.jar:3.6.3.Final]
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:184) [hibernate-core-3.6.3.Final.jar:3.6.3.Final]
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321) [hibernate-core-3.6.3.Final.jar:3.6.3.Final]
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51) [hibernate-core-3.6.3.Final.jar:3.6.3.Final]
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216) [hibernate-core-3.6.3.Final.jar:3.6.3.Final]
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383) [hibernate-core-3.6.3.Final.jar:3.6.3.Final]
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133) [hibernate-core-3.6.3.Final.jar:3.6.3.Final]
at org.hibernate.HibernateEntity.App.main(App.java:40) [classes/:na]
Caused by: java.sql.SQLException: Field 'STOCK_ID' doesn't have a default value
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073) ~[mysql-connector-java-5.1.15.jar:na]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3603) ~[mysql-connector-java-5.1.15.jar:na]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3535) ~[mysql-connector-java-5.1.15.jar:na]
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1989) ~[mysql-connector-java-5.1.15.jar:na]
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2150) ~[mysql-connector-java-5.1.15.jar:na]
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2626) ~[mysql-connector-java-5.1.15.jar:na]
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2119) ~[mysql-connector-java-5.1.15.jar:na]
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2415) ~[mysql-connector-java-5.1.15.jar:na]
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1976) ~[mysql-connector-java-5.1.15.jar:na]
... 11 common frames omitted
08:20:05.316 [main] WARN o.h.util.JDBCExceptionReporter - SQL Error: 1364, SQLState: HY000
08:20:05.316 [main] ERROR o.h.util.JDBCExceptionReporter - Field 'STOCK_ID' doesn't have a default value
Exception in thread "main" org.hibernate.exception.GenericJDBCException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:140)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:128)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:268)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:184)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)
at org.hibernate.HibernateEntity.App.main(App.java:40)
Caused by: java.sql.BatchUpdateException: Field 'STOCK_ID' doesn't have a default value
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:2024)
at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1449)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
... 8 more
Caused by: java.sql.SQLException: Field 'STOCK_ID' doesn't have a default value
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3603)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3535)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1989)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2150)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2626)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2119)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2415)
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1976)
... 11 more
Thsi error raised beacuse you not filled field STOCK_ID but its can't be null in database. Add clause AUTO_INCREMENT to defenition of field STOCK_ID in table STOCK:
STOCK_ID INT(10) NOT NULL AUTO_INCREMENT
and to RECORD_ID in table STOCK_DAILY_RECORD:
RECORD_ID INT(10) NOT NULL AUTO_INCREMENT
But remember that STOCK_CODE not null too and you must fill it before insert.
Can you post the code where you create the instance of the entity and save it? The error is self explanatory. You have to set the value of STOCK_ID. Did you want it to be an identity column (auto_increment in mysql)?. If that's the case, change the data model to declare STOCK_ID as identity and add #GeneratedValue(strategy=GenerationType.IDENTITY) for stockId.
I have these entities that I want to relate bi-directionaly.
Credential:
#Entity
#Access(AccessType.PROPERTY)
#Table(name = "credential")
public class Credential extends MetaInfo implements Serializable {
...
private Email email;
...
#OneToOne(cascade = CascadeType.ALL, optional = false, orphanRemoval = true)
#JoinColumn(name="email", referencedColumnName="email_address")
public Email getEmail() {
return email;
}
public void setEmail(Email email) {
this.email = email;
}
...
}
Email:
#Entity
#Access(AccessType.PROPERTY)
#Table(name = "email")
public class Email extends MetaInfo implements Serializable{
...
private Credential credential;
public Email() {
}
public Email(String emailAddress) {
this.emailAddress = emailAddress;
}
#Id
#Column(name="email_address")
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
#OneToOne(mappedBy = "email", optional=false)
public Credential getCredential() {
return credential;
}
public void setCredential(Credential credential) {
this.credential = credential;
}
}
In a CredentialRepository class I am testing whether the passed-in email
is not assigned to any user except for the user with the username passed-in as the second (optional) parameter:
#Override
public boolean emailIsAssigned(String... args) {
assert(args.length > 0);
if(InputValidators.isValidEmail.test(args[0])){
EntityManager em = entityManagerFactory.createEntityManager();
try {
TypedQuery<Long> count = em.createQuery("SELECT COUNT(e) "
+ "FROM Email e WHERE e.emailAddress "
+ "= :email AND e "
+ "IN (SELECT c.email FROM Credential c WHERE c.username "
+ "!= :username)", Long.TYPE).setParameter("email", args[0])
.setParameter("username", null);
if(InputValidators.stringNotNullNorEmpty.apply(args[1])){
//only if the username has been provided
count.setParameter("username", args[1]);
}
return count.getSingleResult() > 0;
} catch (Exception e) {
System.out.println(e.getMessage());
return false;
} finally {
em.close();
}
}else{
throw new NotAValidEmailException(args[0] + " is not a"
+ " valid email address.");
}
}
Thus above args[0] is the email under test and args[1] is the username under test.
And this is the test that is causing me problems (note that before I already successfully tested inserts, updates and even the emailIsAssigned method but without the c.email part which seems to cause the issue:
#Test
public void emailAlreadyExistsTest(){
assertTrue(credentialRepo.emailIsAssigned("existing_email#yahoo.ca"));
}
And this is the error message that I have:
[EL Warning]: 2017-04-17 17:55:33.606--ServerSession(234430897)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Can't write; duplicate key in table '#sql-3e4_9a'
Error Code: 1022
Call: ALTER TABLE credential ADD CONSTRAINT FK_credential_email FOREIGN KEY (email) REFERENCES email (email_address)
Query: DataModifyQuery(sql="ALTER TABLE credential ADD CONSTRAINT FK_credential_email FOREIGN KEY (email) REFERENCES email (email_address)")
I would appreciate if someone could give me a piece of advice. I could always just change the email into a String and mark it as "unique" in #Column, but I feel that there is no reason for the chosen approach not to work.
I am using MySQL as the DB vendor, and Eclipse-Link JPA implementation. I did try to "hard-change" the name of the FK constraint but to no avail. The DB and all tables have the same collation (utf8_unicode_ci).
Try to delete the primary key for class Email because "extends MetaInfo"