I am creating a small program for a school exercise. I have no clue where I could have done anything wrong. Could someone please help me with this?
I get this error when I run my test. I get the error at the this.emf = TestUtil.getEMF(); line.
/*
* 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 herkansing;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
#Entity
#NamedQueries({
#NamedQuery(name = "Account.getAll", query = "select a from Account as a"),
#NamedQuery(name = "Account.count", query = "select count(a) from Account as a"),
#NamedQuery(name = "Account.findByAccountNr", query = "select a from Account as a where a.accountNr = :accountNr")
})
public class Player implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long Id;
private Long accountNr;
private String email;
private Long money;
private Long points;
public Player() {
}
public Player(Long accountNr){
money = 0L;
points = 0L;
this.accountNr = accountNr;
}
//<editor-fold defaultstate="collapsed" desc="getters and setters ....">
public Boolean add(Long amount) {
if (money + amount >= points) {
money += amount;
return true;
} else {
return false;
}
}
public Long getId() {
return Id;
}
public void setId(Long id) {
this.Id = id;
}
public Long getAccountNr() {
return accountNr;
}
public void setAccountNr(Long nr) {
this.accountNr = nr;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Long getMoney() {
return money;
}
public void setMoney(Long money) {
this.money = money;
}
public Long getPoints() {
return points;
}
public void setPoints(Long points) {
this.points = points;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Player other = (Player) obj;
if (this.accountNr != other.accountNr && (this.accountNr == null || !this.accountNr.equals(other.accountNr))) {
return false;
}
if (this.money != other.money && (this.money == null || !this.money.equals(other.money))) {
return false;
}
if (this.points != other.points && (this.points == null || !this.points.equals(other.points))) {
return false;
}
return true;
}
}
Player class
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="playerPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>herkansing.Player</class>
<shared-cache-mode>NONE</shared-cache-mode>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/?user=root"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
<!--adds logging-->
<property name="eclipselink.logging.logger" value="DefaultLogger"/>
<property name="eclipselink.logging.level" value="FINE"/>
</properties>
</persistence-unit>
</persistence>
persistence.xml
/*
* 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 herkansing;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
/**
*
* #author Bart
*/
public class TestUtil {
static final EntityManagerFactory emf = Persistence.createEntityManagerFactory("playerPU");
/**
*
* #return the number of Accounts stored in the database
*/
static public int getNrOfAccountRecordsInDB() {
EntityManager em = getEMF().createEntityManager();
return ((Number) em.createNamedQuery("Player.count").getSingleResult()).intValue();
}
/**
* Search for an entity of the specified class and primary key.
*
* #param id
* #return the found Account instance or null if the entity does not exist
*/
static public Player getAccountById(Long id) {
EntityManager em = getEMF().createEntityManager();
return em.find(Player.class, id);
}
static public EntityManagerFactory getEMF() {
return emf;
}
}
TestUtil 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 herkansingTest;
import herkansing.TestUtil;
import herkansing.DatabaseCleaner;
import herkansing.Player;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* #author Bart
*/
public class PlayerTest {
final EntityManagerFactory emf;
EntityManager em, em1, em2;
private static final Logger LOG = Logger.getLogger(PlayerTest.class.getName());
public PlayerTest() {
this.emf = TestUtil.getEMF();
}
#Before
public void setUp() {
em = emf.createEntityManager();
em1 = emf.createEntityManager();
em2 = emf.createEntityManager();
new DatabaseCleaner().resetDatabase();
}
}
PlayerTest
java.lang.ExceptionInInitializerError
at herkansingTest.PlayerTest.<init>(PlayerTest.java:34)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at org.junit.runners.BlockJUnit4ClassRunner.createTest(BlockJUnit4ClassRunner.java:217)
at org.junit.runners.BlockJUnit4ClassRunner$1.runReflectiveCall(BlockJUnit4ClassRunner.java:266)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
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:497)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
Caused by: javax.persistence.PersistenceException: Exception [EclipseLink-28019] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Deployment of PersistenceUnit [playerPU] failed. Close all factories for this PersistenceUnit.
Internal Exception: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Problem compiling [select a from Account as a].
[14, 21] The abstract schema type 'Account' is unknown.
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.createDeployFailedPersistenceException(EntityManagerSetupImpl.java:866)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:806)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getAbstractSession(EntityManagerFactoryDelegate.java:205)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getDatabaseSession(EntityManagerFactoryDelegate.java:183)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.getDatabaseSession(EntityManagerFactoryImpl.java:528)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactoryImpl(PersistenceProvider.java:146)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactory(PersistenceProvider.java:183)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at herkansing.TestUtil.<clinit>(TestUtil.java:18)
... 31 more
Caused by: Exception [EclipseLink-28019] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Deployment of PersistenceUnit [playerPU] failed. Close all factories for this PersistenceUnit.
Internal Exception: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Problem compiling [select a from Account as a].
[14, 21] The abstract schema type 'Account' is unknown.
at org.eclipse.persistence.exceptions.EntityManagerSetupException.deployFailed(EntityManagerSetupException.java:239)
... 41 more
Caused by: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Problem compiling [select a from Account as a].
[14, 21] The abstract schema type 'Account' is unknown.
at org.eclipse.persistence.internal.jpa.jpql.HermesParser.buildException(HermesParser.java:155)
at org.eclipse.persistence.internal.jpa.jpql.HermesParser.validate(HermesParser.java:347)
at org.eclipse.persistence.internal.jpa.jpql.HermesParser.populateQueryImp(HermesParser.java:278)
at org.eclipse.persistence.internal.jpa.jpql.HermesParser.buildQuery(HermesParser.java:163)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:142)
at org.eclipse.persistence.internal.jpa.JPAQuery.processJPQLQuery(JPAQuery.java:223)
at org.eclipse.persistence.internal.jpa.JPAQuery.prepare(JPAQuery.java:184)
at org.eclipse.persistence.queries.DatabaseQuery.prepareInternal(DatabaseQuery.java:624)
at org.eclipse.persistence.internal.sessions.AbstractSession.processJPAQuery(AbstractSession.java:4363)
at org.eclipse.persistence.internal.sessions.AbstractSession.processJPAQueries(AbstractSession.java:4323)
at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.initializeDescriptors(DatabaseSessionImpl.java:584)
at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.postConnectDatasource(DatabaseSessionImpl.java:804)
at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.loginAndDetectDatasource(DatabaseSessionImpl.java:748)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider.login(EntityManagerFactoryProvider.java:253)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:728)
... 39 more
The Stacktrace
You can see the cause in the stacktrace here:
Exception Description: Problem compiling [select a from Account as a].
[14, 21] The abstract schema type 'Account' is unknown.
JPA was unable to locate the Account entity and could not create the EntityManagerFactory.
You have to list all the entities in persistence.xml like you listed the Playerclass:
<class>herkansing.Player</class>
<class>herkansing.Account</class>
...
Even if you are not using the Account entity explicitly in your code, there is a named query that references it and JPA tries to validate this query and gives you the exception:
#NamedQueries({
#NamedQuery(name = "Account.getAll", query = "select a from Account as a"),
#NamedQuery(name = "Account.count", query = "select count(a) from Account as a"),
#NamedQuery(name = "Account.findByAccountNr", query = "select a from Account as a where a.accountNr = :accountNr")
})
Alternatively, you could delete the #NamedQueries declaration.
Related
source code
I want to use jsonb column type. When I used postgresql there is no problem. But when I use H2 I can not persist my entity. Native sql works but when saving EntityManager.persist i got below error
ERROR: Data conversion error converting "X'aced000574000f7b226b6579223a2276616c7565227d' (json_entities: ""attributes"" ""JSONB"")"; SQL statement:
insert into json_entities (attributes, id) values (?, ?) [22018-200]
javax.persistence.RollbackException: Error while committing the transaction
at org.hibernate.internal.ExceptionConverterImpl.convertCommitException(ExceptionConverterImpl.java:81)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:104)
at H2Test.jsonFieldTest(H2Test.java:39)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.DataException: could not execute statement
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
at org.hibernate.internal.ExceptionConverterImpl.convertCommitException(ExceptionConverterImpl.java:65)
... 29 more
Caused by: org.hibernate.exception.DataException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:52)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:200)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3254)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3779)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:107)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604)
at org.hibernate.engine.spi.ActionQueue.lambda$executeActions$1(ActionQueue.java:478)
at java.util.LinkedHashMap.forEach(LinkedHashMap.java:684)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:475)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:348)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:40)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1360)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:451)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3210)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2378)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:447)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:281)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101)
... 28 more
Caused by: org.h2.jdbc.JdbcSQLDataException: Data conversion error converting "X'aced000574000f7b226b6579223a2276616c7565227d' (json_entities: ""attributes"" ""JSONB"")"; SQL statement:
insert into json_entities (attributes, id) values (?, ?) [22018-200]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:457)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:429)
at org.h2.message.DbException.get(DbException.java:194)
at org.h2.table.Column.getDataConversionError(Column.java:409)
at org.h2.table.Column.validateConvertUpdateSequence(Column.java:381)
at org.h2.table.Table.validateConvertUpdateSequence(Table.java:845)
at org.h2.command.dml.Insert.insertRows(Insert.java:187)
at org.h2.command.dml.Insert.update(Insert.java:151)
at org.h2.command.CommandContainer.update(CommandContainer.java:198)
at org.h2.command.Command.executeUpdate(Command.java:251)
at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:191)
at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:152)
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61)
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:197)
... 47 more
Caused by: org.h2.message.DbException: Data conversion error converting "OTHER to JSON" [22018-200]
at org.h2.message.DbException.get(DbException.java:205)
at org.h2.message.DbException.get(DbException.java:181)
at org.h2.value.Value.getDataConversionError(Value.java:1504)
at org.h2.value.Value.convertToJson(Value.java:1439)
at org.h2.value.Value.convertTo(Value.java:861)
at org.h2.value.Value.convertTo(Value.java:772)
at org.h2.value.TypeInfo.cast(TypeInfo.java:515)
at org.h2.table.Column.validateConvertUpdateSequence(Column.java:378)
... 57 more
Caused by: org.h2.jdbc.JdbcSQLDataException: Data conversion error converting "OTHER to JSON" [22018-200]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:457)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:429)
... 65 more
Here is my simple project.
Custom hibernate type for jsonb
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.UserType;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
/**
* Created by sanco on 29/09/2020.
* h2jsontest
*/
public class PGJsonType implements UserType {
private final int CUSTOM_TYPE = Types.OTHER;
private final static ObjectMapper jsonMapper = new ObjectMapper();
#Override
public int[] sqlTypes() {
return new int[]{CUSTOM_TYPE};
}
#Override
public Class returnedClass() {
return JsonNode.class;
}
#Override
public boolean equals(Object x, Object y) throws HibernateException {
return x==null? y==null : ((JsonNode)x).equals((JsonNode)y);
}
#Override
public int hashCode(Object x) throws HibernateException {
return ((JsonNode)x).hashCode();
}
#Override
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
final String cellContent = rs.getString(names[0]);
if (cellContent == null) {
return null;
}
try {
return jsonMapper.readTree(cellContent);
} catch (final Exception ex) {
throw new RuntimeException("Failed to convert jsonb to JsonNode: " + ex.getMessage(), ex);
}
}
#Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
if (value == null) {
st.setNull(index, CUSTOM_TYPE);
return;
}
try {
st.setObject(index, jsonMapper.writeValueAsString(value), CUSTOM_TYPE);
} catch (final Exception ex) {
throw new RuntimeException("Failed to convert JsonNode to jsonb: " + ex.getMessage(), ex);
}
}
#Override
public Object deepCopy(Object value) throws HibernateException {
return value==null? null : ((JsonNode)value).deepCopy();
}
#Override
public boolean isMutable() {
return true;
}
#Override
public Serializable disassemble(Object value) throws HibernateException {
return (Serializable) value;
}
#Override
public Object assemble(Serializable cached, Object owner) throws HibernateException {
return cached;
}
#Override
public Object replace(Object original, Object target, Object owner) throws HibernateException {
return original;
}
}
my entity class
import com.fasterxml.jackson.databind.JsonNode;
import org.hibernate.annotations.Type;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Created by sanco on 29/09/2020.
* h2jsontest
*/
#Entity
#Table(name="json_entities")
public class JsonEntity {
#Id
private Long id;
#Type(type = "PGJsonType")
#Column(columnDefinition = "jsonb")
private JsonNode attributes;
public void setId(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public JsonNode getAttributes() {
return attributes;
}
public void setAttributes(JsonNode attributes) {
this.attributes = attributes;
}
}
persistence unit
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="postgre">
<description>
Hibernate using JPA
</description>
<class>JsonEntity</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/postgres"/>
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/>
<property name="hibernate.connection.username" value="postgres"/>
<property name="hibernate.connection.password" value="s2351910"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL10Dialect"/>
<property name="hibernate.temp.use_jdbc_metadata_defaults"
value="false"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.enable_lazy_load_no_trans" value="true"/>
<property name="hibernate.connection.provider_class"
value="org.hibernate.hikaricp.internal.HikariCPConnectionProvider"/>
<property name="hibernate.hikari.minimumIdle" value="5"/>
<property name="hibernate.hikari.maximumPoolSize" value="20"/>
<property name="hibernate.hikari.idleTimeout" value="45000"/>
</properties>
</persistence-unit>
<persistence-unit name="h2">
<description>
Hibernate using JPA
</description>
<class>JsonEntity</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:h2:mem:organization;MODE=PostgreSQL;IGNORECASE=TRUE;DATABASE_TO_LOWER=TRUE;AUTO_RECONNECT=TRUE;INIT=CREATE DOMAIN IF NOT EXISTS jsonb AS other\;CREATE TYPE if not exists "JSONB" AS json;"/>
<property name="hibernate.connection.driver_class" value="org.h2.Driver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<property name="hibernate.temp.use_jdbc_metadata_defaults"
value="false"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.enable_lazy_load_no_trans" value="true"/>
<property name="hibernate.connection.provider_class"
value="org.hibernate.hikaricp.internal.HikariCPConnectionProvider"/>
<property name="hibernate.hikari.minimumIdle" value="5"/>
<property name="hibernate.hikari.maximumPoolSize" value="20"/>
<property name="hibernate.hikari.idleTimeout" value="60000"/>
</properties>
</persistence-unit>
</persistence>
test classes
H2
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
/**
* Created by sanco on 29/09/2020.
* h2jsontest
*/
public class H2Test {
private static EntityManagerFactory factory;
private static ObjectMapper mapper;
#BeforeClass
public static void init(){
factory = Persistence.createEntityManagerFactory("h2");
mapper = new ObjectMapper();
}
#Test
public void jsonFieldTest(){
EntityManager em = factory.createEntityManager();
JsonEntity je = new JsonEntity();
je.setId(1L);
ObjectNode on = mapper.createObjectNode();
on.put("key", "value");
je.setAttributes(on);
try {
em.getTransaction().begin();
em.persist(je);
em.getTransaction().commit();
}catch (Exception e){
e.printStackTrace();
em.getTransaction().rollback();
}
assert (em.createQuery("select j.id from JsonEntity j", Long.class).getSingleResult())==1L;
}
#AfterClass
public static void cleanResource(){
if(factory!=null)
factory.close();
}
}
Postgresql
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
/**
* Created by sanco on 29/09/2020.
* h2jsontest
*/
public class PostgreSQLTest {
private static EntityManagerFactory factory;
private static ObjectMapper mapper;
#BeforeClass
public static void init(){
factory = Persistence.createEntityManagerFactory("postgre");
mapper = new ObjectMapper();
}
#Test
public void jsonFieldTest(){
EntityManager em = factory.createEntityManager();
JsonEntity je = new JsonEntity();
je.setId(1L);
ObjectNode on = mapper.createObjectNode();
on.put("key", "value");
je.setAttributes(on);
try {
em.getTransaction().begin();
em.persist(je);
em.getTransaction().commit();
}catch (Exception e){
e.printStackTrace();
em.getTransaction().rollback();
}
assert (em.createQuery("select j.id from JsonEntity j", Long.class).getSingleResult())==1L;
}
#AfterClass
public static void cleanResource(){
if(factory!=null)
factory.close();
}
}
I read lots of forms but the suggested solution does not work for me. I also debug the H2 source code and see that ValueJson.convertToJson throw exception because of value type not handle on switch case. Look at the source code of org.h2.value.Value.java
private ValueJson convertToJson() {
switch (getValueType()) {
case BOOLEAN:
return ValueJson.get(getBoolean());
case BYTE:
case SHORT:
case INT:
return ValueJson.get(getInt());
case LONG:
return ValueJson.get(getLong());
case FLOAT:
case DOUBLE:
case DECIMAL:
return ValueJson.get(getBigDecimal());
case BYTES:
case BLOB:
return ValueJson.fromJson(getBytesNoCopy());
case STRING:
case STRING_IGNORECASE:
case STRING_FIXED:
case CLOB:
return ValueJson.get(getString());
case GEOMETRY: {
ValueGeometry vg = (ValueGeometry) this;
return ValueJson.getInternal(GeoJsonUtils.ewkbToGeoJson(vg.getBytesNoCopy(), vg.getDimensionSystem()));
}
default:
throw getDataConversionError(Value.JSON);
}
}
getValueType return 19 which means JAVA_OBJECT. How can I handle this problem?
I'm using Spring Boot with Liquibase and this library (https://github.com/vladmihalcea/hibernate-types) to accomplish this. And this article to accomplish this https://vladmihalcea.com/how-to-map-json-objects-using-generic-hibernate-types/.
The first step is have a Liquibase change set that only runs in test mode to treat JSONB column types as JSON. H2 supports the latter but not the former.
This is the first change set that runs, and it is only targeted if the context is test and if the target DB is H2.
<changeSet id="0" author="psc" context="test" dbms="h2">
<sql>
CREATE TYPE IF NOT EXISTS "JSONB" as json;
</sql>
</changeSet>
Contents of application-test.properties
spring.liquibase.contexts=test
My test entity. See How to map json article to better understand the annotations that were used.
import com.vladmihalcea.hibernate.type.json.JsonType;
import lombok.*;
import net.energyhub.testcontainers.dto.CustomerData;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import org.hibernate.annotations.TypeDefs;
import javax.persistence.*;
#Entity
#Table(name = "customers")
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#Builder
#TypeDefs({
#TypeDef(name = "json", typeClass = JsonType.class)
})
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
#Type(type = "json")
#Column(columnDefinition = "jsonb")
private CustomerData customerDetails;
}
Example of a test that exercises the JSON column. I'm making use of Spring Boot's DataJPATest test slice feature.
#DataJpaTest
#ActiveProfiles("test")
public class CustomerServiceH2Test {
#Autowired
private CustomerRepository customerRepository;
#Test
public void testFindAll() {
Customer customer = Customer.builder()
.name("Phil Calouche")
.customerDetails(CustomerData.builder().x("x-value").build())
.build();
customerRepository.save(customer);
assertThat(customerRepository.findAll()).hasSize(4);
}
}
guys please help me for solve this error, it's been 4 days, this problem hasn't been solved.
this is my Entity Class code :
package mybengkel;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
*
* #author rhmtsaepuloh
*/
#Entity
#Table(name = "employee")
#NamedQueries({
#NamedQuery(name = "Employee.findAll", query = "SELECT e FROM Employee e"),
#NamedQuery(name = "Employee.findById", query = "SELECT e FROM Employee e WHERE e.id = :id"),
#NamedQuery(name = "Employee.findByUsername", query = "SELECT e FROM Employee e WHERE e.username = :username"),
#NamedQuery(name = "Employee.findByPassword", query = "SELECT e FROM Employee e WHERE e.password = :password")})
public class Employee 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)
#Column(name = "username")
private String username;
#Basic(optional = false)
#Column(name = "password")
private String password;
public Employee() {
}
public Employee(Integer id) {
this.id = id;
}
public Employee(Integer id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
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;
}
#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 Employee)) {
return false;
}
Employee other = (Employee) 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 "mybengkel.Employee[ id=" + id + " ]";
}
}
Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="MyBengkelPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<jar-file>/Users/rhmtsaepuloh/Downloads/mysql-connector-java-8.0.18/mysql-connector-java-8.0.18.jar</jar-file>
<class>mybengkel.Employee</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/oop?serverTimezone=UTC"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>
and Main class java :
package mybengkel;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
/**
*
* #author rhmtsaepuloh
*/
public class MyBengkel {
public static void main(String[] args) {
EntityManager em;
EntityManagerFactory emf;
emf = Persistence.createEntityManagerFactory("MyBengkelPU");
em = emf.createEntityManager();
em.getTransaction().begin();
Employee e = new Employee();
e.setUsername("haha");
e.setPassword("hehe");
em.persist(e);
em.getTransaction().commit();
}
}
the problem is when I run the program found error code :
[EL Info]: 2019-11-28 16:07:45.916--ServerSession(347978868)--EclipseLink, version: Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd
[EL Info]: connection: 2019-11-28 16:07:46.813--ServerSession(347978868)--file:/Volumes/Data/Perkuliahan/OOP/NetBeans/MyBengkel/build/classes/_MyBengkelPU login successful
[EL Warning]: metamodel: 2019-11-28 16:07:46.859--The collection of metamodel types is empty. Model classes may not have been found during entity search for Java SE and some Java EE container managed persistence units. Please verify that your entity classes are referenced in persistence.xml using either <class> elements or a global <exclude-unlisted-classes>false</exclude-unlisted-classes> element
Exception in thread "main" java.lang.IllegalArgumentException: Object: mybengkel.Employee[ id=null ] is not a known entity type.
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4228)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:496)
at mybengkel.MyBengkel.main(MyBengkel.java:29)
/Users/rhmtsaepuloh/Library/Caches/NetBeans/11.1/executor-snippets/run.xml:111: The following error occurred while executing this line:
/Users/rhmtsaepuloh/Library/Caches/NetBeans/11.1/executor-snippets/run.xml:68: Java returned: 1
BUILD FAILED (total time: 3 seconds)
I try this on netbeans 11.1 and mysql connector java 8.0.18 Please help me to fix it guys... Thanks before
i created a project on netbeans and add jpa , but when i run this project i take this error. I use netbeans ide.
[EL Info]: 2017-11-05 00:01:05.271--ServerSession(1276666395)--EclipseLink, version: Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd
[EL Info]: connection: 2017-11-05 00:01:05.451--ServerSession(1276666395)--file:/C:/Users/kB/Documents/NetBeansProjects/JavaApplication11/build/classes/_JavaApplication11PU login successful
[EL Warning]: 2017-11-05 00:01:20.582--ServerSession(1276666395)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: Table 'room' already exists
Error Code: 1050
Call: CREATE TABLE room (room_id INTEGER NOT NULL, room_name VARCHAR(255), PRIMARY KEY (room_id))
Query: DataModifyQuery(sql="CREATE TABLE room (room_id INTEGER NOT NULL, room_name VARCHAR(255), PRIMARY KEY (room_id))")
[EL Warning]: 2017-11-05 00:01:35.687--ServerSession(1276666395)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: Table 'sequence' already exists
Error Code: 1050
Call: CREATE TABLE SEQUENCE (SEQ_NAME VARCHAR(50) NOT NULL, SEQ_COUNT DECIMAL(38), PRIMARY KEY (SEQ_NAME))
Query: DataModifyQuery(sql="CREATE TABLE SEQUENCE (SEQ_NAME VARCHAR(50) NOT NULL, SEQ_COUNT DECIMAL(38), PRIMARY KEY (SEQ_NAME))")
[EL Warning]: 2017-11-05 00:01:35.816--UnitOfWork(190868662)--java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Number
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Number
at org.eclipse.persistence.sequencing.QuerySequence.updateAndSelectSequence(QuerySequence.java:278)
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:468)
at org.eclipse.persistence.internal.sequencing.SequencingManager.getNextValue(SequencingManager.java:1067)
at org.eclipse.persistence.internal.sequencing.ClientSessionSequencing.getNextValue(ClientSessionSequencing.java:70)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.assignSequenceNumber(ObjectBuilder.java:361)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.assignSequenceNumber(ObjectBuilder.java:320)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.assignSequenceNumber(UnitOfWorkImpl.java:486)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNotRegisteredNewObjectForPersist(UnitOfWorkImpl.java:4290)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.registerNotRegisteredNewObjectForPersist(RepeatableWriteUnitOfWork.java:518)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4235)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:496)
at javaapplication11.JavaApplication11.main(JavaApplication11.java:29)
C:\Users\kB\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 31 seconds)
It is my Entity Class
package javaapplication11;
import java.io.Serializable;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
*
* #author kB
*/
#Entity
#Table(name="room")
public class NewEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "room_id")
private int id;
#Column(name = "room_name")
private String name;
public NewEntity() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public int hashCode() {
int hash = 5;
hash = 29 * hash + this.id;
hash = 29 * hash + Objects.hashCode(this.name);
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final NewEntity other = (NewEntity) obj;
if (this.id != other.id) {
return false;
}
if (!Objects.equals(this.name, other.name)) {
return false;
}
return true;
}
#Override
public String toString() {
return super.toString(); //To change body of generated methods, choose Tools | Templates.
}
}
And it is main class
package javaapplication11;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
/**
*
* #author kB
*/
public class JavaApplication11 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
EntityManagerFactory emf = Persistence.createEntityManagerFactory("JavaApplication11PU");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
NewEntity x = new NewEntity();
x.setName("anan");
em.persist(x);
em.getTransaction().commit();
em.close();
emf.close();
}
}
Lastly it is my persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="JavaApplication11PU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>javaapplication11.NewEntity</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/felek"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>
Is this the whole code?
Because the end of stack trace points to JavaApplication11.java:29, which is } sign of your main, which is weird.
Queries in the form of an entity class A in the form of
SELECT a from A a WHERE TYPE(a) = A
fail with
could not resolve property: class of: de.richtercloud.type.operator.nonsense.A [SELECT a from de.richtercloud.type.operator.nonsense.A a WHERE TYPE(a) = A]
which I don't understand because restricting A to A should exclude all superclass instances which aren't As as well as subclass instances.
Example:
package de.richtercloud.type.operator.nonsense;
import java.io.File;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
/**
* Illustrates the problem/misunderstanding that storing an {#link A} and
* querying it with a {#code WHERE TYPE([identifier]) = A} fails with
* {#code org.hibernate.QueryException: could not resolve property:
* class of: de.richtercloud.type.operator.nonsense.A}.
* #author richter
*/
public class NewMain {
private final static File DATABASE_DIR = new File("/tmp/type-operator-nonsense");
private final static String DERBY_CONNECTION_URL = String.format("jdbc:derby:%s", DATABASE_DIR.getAbsolutePath());
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws SQLException {
//setup database
EntityManagerFactory entityManagerFactory = null;
try {
Map<Object, Object> entityManagerFactoryMap = new HashMap<>();
entityManagerFactoryMap.put("javax.persistence.jdbc.url",
String.format("%s;create=%s", DERBY_CONNECTION_URL, !DATABASE_DIR.exists()));
entityManagerFactory = Persistence.createEntityManagerFactory("type-operator-nonsense",
entityManagerFactoryMap);
//show issue
EntityManager entityManager = entityManagerFactory.createEntityManager();
A a = new A(1L, "b");
entityManager.getTransaction().begin();
entityManager.persist(a);
entityManager.flush();
Query query = entityManager.createQuery("SELECT a from A a WHERE TYPE(a) = A");
List<?> queryResult = query.getResultList();
entityManager.getTransaction().commit();
System.out.println(queryResult.size());
}finally {
if(entityManagerFactory != null) {
entityManagerFactory.close();
}
}
}
}
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="type-operator-nonsense" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>de.richtercloud.type.operator.nonsense.A</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:derby:/tmp/type-operator-nonsense"/>
<property name="javax.persistence.jdbc.user" value=""/>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
with org.hibernate:hibernate-entitymanager:5.1.0.Final and org.apache.derby:derby:10.11.1.1
A is a POJO in this example which doesn't involve inheritance, that shouldn't matter for the restriction I expect (although it wouldn't make sense to apply it if there's no inheritance):
package de.richtercloud.type.operator.nonsense;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class A implements Serializable {
private static final long serialVersionUID = 1L;
private String b;
#Id
private Long id;
public A() {
}
public A(Long id, String b) {
this.id = id;
this.b = b;
}
public void setB(String b) {
this.b = b;
}
public String getB() {
return b;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
This behaviour occurs due to a hibernate bug https://hibernate.atlassian.net/browse/HHH-10653. The example above works fine with OpenJPA.
TYPE() can only be used in inheritance mapping.
Is A a class in a inheritance mapping and A either the route class with #Inheritance or A extends a class that has #Inheritance declared?
Example.
#Inheritance
#Entity
public class Project
#Entity
public class DesignProject extends Project
#Entity
public class QualityProject extends Project
#Entity
public class SoftwareProject extends Project
Now you can use TYPE()
SELECT p
FROM Project p
WHERE TYPE(p) = DesignProject OR TYPE(p) = QualityProject
i am developping a project base on J2EE EJB JSF, database is MYsql, the project works very well last week. but today, it can't be deployed when i run it. here are some exception:
Initial deploying ECOM to C:\Users\John624\Documents\NetBeansProjects\PromoCoupon\ECOM\dist\gfdeploy\ECOM
Completed initial distribution of ECOM
Initializing...
invalid header field name: Exception Description
C:\Users\John624\Documents\NetBeansProjects\PromoCoupon\ECOM\nbproject\build-impl.xml:307: The module has not been deployed.
See the server log for details.
BUILD FAILED (total time: 5 seconds)
Glassfish:
<code> SEVERE: Exception while invoking class org.glassfish.persistence.jpa.JPADeployer prepare method
SEVERE: Exception while invoking class org.glassfish.javaee.full.deployment.EarDeployer prepare method
SEVERE: org.glassfish.deployment.common.DeploymentException: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [ECOM-ejbPU] failed.
Internal Exception: Exception [EclipseLink-7158] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Error encountered when building the #NamedQuery [Adresse.maxId] from entity class [class org.eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata].
Internal Exception: java.lang.ClassCastException: org.eclipse.persistence.jpa.jpql.parser.NullExpression cannot be cast to org.eclipse.persistence.jpa.jpql.parser.IdentificationVariable
at org.glassfish.javaee.full.deployment.EarDeployer.prepare(EarDeployer.java:180)
at com.sun.enterprise.v3.server.ApplicationLifecycle.prepareModule(ApplicationLifecycle.java:922)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:431)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:527)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:523)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:356)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:522)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:546)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1423)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1500(CommandRunnerImpl.java:108)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1762)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1674)
at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
at org.glassfish.grizzly.http.server.StaticHttpHandler.service(StaticHttpHandler.java:297)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:246)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:724)
Caused by: javax.persistence.PersistenceException: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [ECOM-ejbPU] failed.
Internal Exception: Exception [EclipseLink-7158] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Error encountered when building the #NamedQuery [Adresse.maxId] from entity class [class org.eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata].
Internal Exception: java.lang.ClassCastException: org.eclipse.persistence.jpa.jpql.parser.NullExpression cannot be cast to org.eclipse.persistence.jpa.jpql.parser.IdentificationVariable
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.createPredeployFailedPersistenceException(EntityManagerSetupImpl.java:1950)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:1941)
at org.eclipse.persistence.jpa.PersistenceProvider.createContainerEntityManagerFactory(PersistenceProvider.java:322)
at org.glassfish.persistence.jpa.PersistenceUnitLoader.loadPU(PersistenceUnitLoader.java:199)
at org.glassfish.persistence.jpa.PersistenceUnitLoader.<init>(PersistenceUnitLoader.java:107)
at org.glassfish.persistence.jpa.JPADeployer$1.visitPUD(JPADeployer.java:223)
at org.glassfish.persistence.jpa.JPADeployer$PersistenceUnitDescriptorIterator.iteratePUDs(JPADeployer.java:510)
at org.glassfish.persistence.jpa.JPADeployer.createEMFs(JPADeployer.java:230)
at org.glassfish.persistence.jpa.JPADeployer.prepare(JPADeployer.java:168)
at com.sun.enterprise.v3.server.ApplicationLifecycle.prepareModule(ApplicationLifecycle.java:922)
at org.glassfish.javaee.full.deployment.EarDeployer.prepareBundle(EarDeployer.java:307)
at org.glassfish.javaee.full.deployment.EarDeployer.access$200(EarDeployer.java:88)
at org.glassfish.javaee.full.deployment.EarDeployer$1.doBundle(EarDeployer.java:153)
at org.glassfish.javaee.full.deployment.EarDeployer$1.doBundle(EarDeployer.java:150)
at org.glassfish.javaee.full.deployment.EarDeployer.doOnBundles(EarDeployer.java:230)
at org.glassfish.javaee.full.deployment.EarDeployer.doOnAllTypedBundles(EarDeployer.java:239)
at org.glassfish.javaee.full.deployment.EarDeployer.doOnAllBundles(EarDeployer.java:265)
at org.glassfish.javaee.full.deployment.EarDeployer.prepare(EarDeployer.java:150)
... 35 more
Caused by: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [ECOM-ejbPU] failed.
Internal Exception: Exception [EclipseLink-7158] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Error encountered when building the #NamedQuery [Adresse.maxId] from entity class [class org.eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata].
Internal Exception: java.lang.ClassCastException: org.eclipse.persistence.jpa.jpql.parser.NullExpression cannot be cast to org.eclipse.persistence.jpa.jpql.parser.IdentificationVariable
at org.eclipse.persistence.exceptions.EntityManagerSetupException.predeployFailed(EntityManagerSetupException.java:230)
... 53 more
Caused by: Exception [EclipseLink-7158] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Error encountered when building the #NamedQuery [Adresse.maxId] from entity class [class org.eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata].
Internal Exception: java.lang.ClassCastException: org.eclipse.persistence.jpa.jpql.parser.NullExpression cannot be cast to org.eclipse.persistence.jpa.jpql.parser.IdentificationVariable
at org.eclipse.persistence.exceptions.ValidationException.errorProcessingNamedQuery(ValidationException.java:824)
at org.
SEVERE: Exception while preparing the app
SEVERE: eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata.process(NamedQueryMetadata.java:194)
at org.eclipse.persistence.internal.jpa.metadata.MetadataProject.processQueries(MetadataProject.java:1628)
at org.eclipse.persistence.internal.jpa.metadata.MetadataProcessor.addNamedQueries(MetadataProcessor.java:148)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:1894)
... 51 more
Caused by: java.lang.ClassCastException: org.eclipse.persistence.jpa.jpql.parser.NullExpression cannot be cast to org.eclipse.persistence.jpa.jpql.parser.IdentificationVariable
at org.eclipse.persistence.internal.jpa.jpql.DeclarationResolver$DeclarationVisitor.visit(DeclarationResolver.java:626)
at org.eclipse.persistence.jpa.jpql.parser.RangeVariableDeclaration.accept(RangeVariableDeclaration.java:98)
at org.eclipse.persistence.internal.jpa.jpql.DeclarationResolver$DeclarationVisitor.visit(DeclarationResolver.java:577)
at org.eclipse.persistence.jpa.jpql.parser.IdentificationVariableDeclaration.accept(IdentificationVariableDeclaration.java:71)
at org.eclipse.persistence.internal.jpa.jpql.DeclarationResolver$DeclarationVisitor.visit(DeclarationResolver.java:566)
at org.eclipse.persistence.jpa.jpql.parser.FromClause.accept(FromClause.java:48)
at org.eclipse.persistence.internal.jpa.jpql.DeclarationResolver.populateImp(DeclarationResolver.java:417)
at org.eclipse.persistence.internal.jpa.jpql.DeclarationResolver.populate(DeclarationResolver.java:407)
at org.eclipse.persistence.internal.jpa.jpql.JPQLQueryHelper$DescriptorCollector.collectDescriptors(JPQLQueryHelper.java:179)
at org.eclipse.persistence.internal.jpa.jpql.JPQLQueryHelper$DescriptorCollector.visit(JPQLQueryHelper.java:204)
at org.eclipse.persistence.jpa.jpql.parser.FromClause.accept(FromClause.java:48)
at org.eclipse.persistence.jpa.jpql.parser.AbstractSelectStatement.acceptChildren(AbstractSelectStatement.java:93)
at org.eclipse.persistence.jpa.jpql.parser.SelectStatement.acceptChildren(SelectStatement.java:110)
at org.eclipse.persistence.jpa.jpql.parser.AbstractTraverseChildrenVisitor.visit(AbstractTraverseChildrenVisitor.java:32)
at org.eclipse.persistence.jpa.jpql.parser.AnonymousExpressionVisitor.visit(AnonymousExpressionVisitor.java:470)
at org.eclipse.persistence.jpa.jpql.parser.SelectStatement.accept(SelectStatement.java:102)
at org.eclipse.persistence.jpa.jpql.parser.JPQLExpression.acceptChildren(JPQLExpression.java:143)
at org.eclipse.persistence.jpa.jpql.parser.AbstractTraverseChildrenVisitor.visit(AbstractTraverseChildrenVisitor.java:32)
at org.eclipse.persistence.jpa.jpql.parser.AnonymousExpressionVisitor.visit(AnonymousExpressionVisitor.java:302)
at org.eclipse.persistence.jpa.jpql.parser.JPQLExpression.accept(JPQLExpression.java:136)
at org.eclipse.persistence.internal.jpa.jpql.JPQLQueryHelper.getClassDescriptors(JPQLQueryHelper.java:87)
at org.eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata.addJPAQuery(NamedQueryMetadata.java:105)
at org.eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata.process(NamedQueryMetadata.java:192)
... 54 more
<code>
entity bean
/*
* To change this template, 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.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
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 John624
*/
#Entity
#Table(name = "Adresse")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Adresse.maxId", query = "SELECT max(idAdresse) FROM Adresse"),
#NamedQuery(name = "Adresse.findAll", query = "SELECT a FROM Adresse a"),
#NamedQuery(name = "Adresse.findByIdAdresse", query = "SELECT a FROM Adresse a WHERE a.idAdresse = :idAdresse"),
#NamedQuery(name = "Adresse.findByNumEtRue", query = "SELECT a FROM Adresse a WHERE a.numEtRue = :numEtRue"),
#NamedQuery(name = "Adresse.findByComple", query = "SELECT a FROM Adresse a WHERE a.comple = :comple"),
#NamedQuery(name = "Adresse.findByCodePostale", query = "SELECT a FROM Adresse a WHERE a.codePostale = :codePostale"),
#NamedQuery(name = "Adresse.findByVille", query = "SELECT a FROM Adresse a WHERE a.ville = :ville"),
#NamedQuery(name = "Adresse.findByPays", query = "SELECT a FROM Adresse a WHERE a.pays = :pays"),
#NamedQuery(name = "Adresse.findByDateModif", query = "SELECT a FROM Adresse a WHERE a.dateModif = :dateModif")})
public class Adresse implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "idAdresse")
private Long idAdresse;
#Size(max = 100)
#Column(name = "numEtRue")
private String numEtRue;
#Size(max = 100)
#Column(name = "comple")
private String comple;
#Size(max = 5)
#Column(name = "codePostale")
private String codePostale;
#Size(max = 35)
#Column(name = "ville")
private String ville;
#Size(max = 35)
#Column(name = "pays")
private String pays;
#Column(name = "dateModif")
#Temporal(TemporalType.DATE)
private Date dateModif;
#OneToMany(mappedBy = "adrU")
private Collection<Utilisateur> utilisateurCollection;
#OneToMany(mappedBy = "adrRecep")
private Collection<Livraison> livraisonCollection;
#OneToMany(mappedBy = "adrE")
private Collection<Entreprise> entrepriseCollection;
public Adresse() {
}
public Adresse(Long idAdresse) {
this.idAdresse = idAdresse;
}
public Long getIdAdresse() {
return idAdresse;
}
public void setIdAdresse(Long idAdresse) {
this.idAdresse = idAdresse;
}
public String getNumEtRue() {
return numEtRue;
}
public void setNumEtRue(String numEtRue) {
this.numEtRue = numEtRue;
}
public String getComple() {
return comple;
}
public void setComple(String comple) {
this.comple = comple;
}
public String getCodePostale() {
return codePostale;
}
public void setCodePostale(String codePostale) {
this.codePostale = codePostale;
}
public String getVille() {
return ville;
}
public void setVille(String ville) {
this.ville = ville;
}
public String getPays() {
return pays;
}
public void setPays(String pays) {
this.pays = pays;
}
public Date getDateModif() {
return dateModif;
}
public void setDateModif(Date dateModif) {
this.dateModif = dateModif;
}
#XmlTransient
public Collection<Utilisateur> getUtilisateurCollection() {
return utilisateurCollection;
}
public void setUtilisateurCollection(Collection<Utilisateur> utilisateurCollection) {
this.utilisateurCollection = utilisateurCollection;
}
#XmlTransient
public Collection<Livraison> getLivraisonCollection() {
return livraisonCollection;
}
public void setLivraisonCollection(Collection<Livraison> livraisonCollection) {
this.livraisonCollection = livraisonCollection;
}
#XmlTransient
public Collection<Entreprise> getEntrepriseCollection() {
return entrepriseCollection;
}
public void setEntrepriseCollection(Collection<Entreprise> entrepriseCollection) {
this.entrepriseCollection = entrepriseCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idAdresse != null ? idAdresse.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 Adresse)) {
return false;
}
Adresse other = (Adresse) object;
if ((this.idAdresse == null && other.idAdresse != null) || (this.idAdresse != null && !this.idAdresse.equals(other.idAdresse))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entities.Adresse[ idAdresse=" + idAdresse + " ]";
}
}
session bean
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package session;
import entities.Adresse;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* #author John624
*/
#Stateless
#LocalBean
public class AdresseManager {
#PersistenceContext(unitName = "ECOM-ejbPU")
private EntityManager em;
public List<Adresse> getAllAdresses() {
Query query=em.createNamedQuery("Adresse.findAll");
return query.getResultList();
}
public Adresse update(Adresse adresse) {
return em.merge(adresse);
}
public void persist(Object object) {
em.persist(object);
}
public Long nextId(){
Query query = em.createNamedQuery("Adresse.maxId");
long res;
res = query.getResultList().indexOf(0)+1;
return res;
}
}
JSF managedbean
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package managedbeans;
import entities.Adresse;
import java.io.Serializable;
import java.util.List;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import session.AdresseManager;
/**
*
* #author John624
*/
#Named(value="adresseMBean")
#SessionScoped
public class AdresseMBean implements Serializable{
private List<Adresse> adresses;
private Adresse adresse;
#EJB
private AdresseManager adresseManager;
public AdresseMBean() {
adresse=new Adresse();
adresseManager = new AdresseManager();
}
/**
* returns customer list for display in a datatable DataTable
* #return
*/
public List<Adresse> getAdresses() {
if((adresses == null) || (adresses.isEmpty()))
adresses = adresseManager.getAllAdresses();
return adresseManager.getAllAdresses();
}
// public void refresh() {
// tousLesComptes = compteBancaireFacade.findAll();
// }
/**
* returns details of a customer. Useful for displaying in a form a customer's details
* #return
*/
public Adresse getDetails() {
return adresse;
}
/**
* Action handler - Called when a line in the table is clicked
* #param adresse
* #return
*/
public String showDetails(Adresse adresse) {
this.adresse = adresse;
return "AdresseDetails"; // will display CustomerDetails.xml JSF page
}
/**
* Action handler - update the customer model in the database.
* called when one press the update button in the form
* #return
*/
public String update() {
System.out.println("###UPDATE###");
adresse = adresseManager.update(adresse);
return "AdresseList"; // will display the customer list in a table
}
/**
* Action handler - returns to the list of customers in the table
*/
public String list() {
System.out.println("###LIST###");
return "AdresseList";
}
public void update(Adresse adrU) {
System.out.println("###UPDATE###");
adresseManager.update(adrU);
}
}
Thanks in advance.
As indicated by the following exception stacktrace
Exception Description: Error encountered when building the #NamedQuery [Adresse.maxId] from entity class [class org.eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata].
the problem is here :
#NamedQuery(name = "Adresse.maxId", query = "SELECT max(idAdresse) FROM Adresse"),
To solve the problem, try this instead:
#NamedQuery(name = "Adresse.maxId", query = "SELECT max(a.idAdresse) FROM Adresse a"),
Try out these steps:
Undeploy the application from glassfish server.
Restart the glassfish server.
Restart netbeans.
Again deploy your application on the glassfish server.
Try to remove adresseManager = new AdresseManager(); from your AdresseMBean class.
#EJB injects and creates already the object.
Then try to redeploy the project and put a debug breakpoint in getAdresses method to see if adresseManager object isn't null or do a poor Sysout.
If you want to initialize services on starting of a managed bean, you'll need to use #PostConstruct annotation on a custom public method inside managed bean and code your initialisation there (eg. loading entity list from db).
Hope it will help you.
PS : Excuse my mistakes for english language, i'm French.
PS2 : I've not seen that it was working before, so it is perhaps a deployment problem !