Hot questions for Using GlassFish in jpa

Question:

I need to be able to store characters like \xF0\x9F\x94\xA5 in my database, which, according to this post need UTF8mb4 encoding.

So I set up my database with

CREATE DATABASE `myDB` CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci

and verified in the MySQL shell if it was effective:

SHOW FULL COLUMNS FROM myTable;

+---------+------------------+--------------------+----
| Field   | Type             | Collation          | ...
+---------+------------------+--------------------+-----
| id      | int(10) unsigned | NULL               | ...   
| myColumn| text             | utf8mb4_general_ci | ...
+---------+------------------+--------------------+-----

So far so good.

After running my program, I got this Exception:

Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: Illegal mix of collations (utf8mb4_general_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation 'like'
Error Code: 1267

For the record: I am using the Java Persistency API (JPA) in my webapplication with GlassFish 3.1. The Exception gets thrown when executing a named query:

@NamedQuery(name = "myTable.findByMyColumn", query = "SELECT c FROM myTable c WHERE c.myColumn LIKE :myColumn")

However, it appears that the error only occurs when the queried String actually contains those weired emoji characters (\xF0\x9F\x94\xA5)

Call: SELECT id, myColumn FROM myDB.myTable WHERE myColumn LIKE ?
bind => [Something something Lorem Ipsum 🇬🇧]  

So I thought, that somewhere might still be a utf8_general_ci set up and I tried putting the COLLATION directly into the query (as suggested in this post here)

@NamedQuery(name = "myTable.findByMyColumn", query = "SELECT c COLLATE utf8mb4_general_ci FROM myTable c WHERE c.myColumn LIKE :myColumn")

But still nothing.

Then I tried putting the collation directly in the connection (in GlassFish I am using a connection_pool) as I read here

characterEncoding, UTF8mb4

But GlassFish said only Connection could not be allocated because: Unsupported character encoding 'UTF8mb4'

The last thing I did was checking the Database System (I am using MariaDB)

show variables WHERE variable_name like "col%";
+----------------------+------------------+
| Variable_name        | Value            |
+----------------------+------------------+
| collation_connection | utf8_general_ci  |
| collation_database   | utf32_general_ci |
| collation_server     | utf8_general_ci  |
+----------------------+------------------+

And now I am completely lost...

What can I do to use utf8mb4 or utf-32 or anything else for that matter that is more advanced that simple UTF-8 ?


Answer:

You do not need any change in the Java side, as utf8mb4 is just UTF-8 in Java.

Instead, as you can see here:

show variables WHERE variable_name like "col%";
+----------------------+------------------+
| Variable_name        | Value            |
+----------------------+------------------+
| collation_connection | utf8_general_ci  |
| collation_database   | utf32_general_ci |
| collation_server     | utf8_general_ci  |
+----------------------+------------------+

your connection setting is still utf8_general_ci; to set it at the connection level, one option is to execute the (mysql specific) query:

SET NAMES='utf8mb4'

before any attempt to use the utf8mb4 collation; or, generally for the mysql server, in /etc/my.cnf:

[mysql]
default-character-set = utf8mb4

[mysqld]
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci

Another option without changing the connection string, is using a jdbc driver version >= 5.1.13: http://www.opensubscriber.com/message/java@lists.mysql.com/14151747.html

Question:

Situation: (using Payara Server)

I have multiple Groups, and each Group has their own specific set of GroupMeetings.

These GroupMeetings are tracked over multiple years. Each Group contains 100-10000 GroupMeetings. But usually only the current year's GroupMeetings are queried and used.

Problem:

How can I load all Groups, but only load each Group's GroupMeeting List for a specific interval, for example only the GroupMeetings of 2019? Or, if need be, specific years or ranges, i.e. 2017-2021 etc?

If I simply run a "SELECT *", then with the FetchType.LAZYI will get empty an emtpy List<GroupMeeting>, but as soon as I access it somewhere in the code, all the items will be loaded.

Question: Whats the best strategy, i.e. somewhat efficient but not overly convoluted?

  • Is there an easy SQL/JPQL query that I can run with the classes below?
  • Is there some structural change - especially in the annotations - needed?
  • Should I consider Criteria API?
  • Do I have to use two List<GroupMeeting>s, one with the commonly used meetings, the other with the 'old' meetings?

Example: Here are the two classes:

import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;

@Entity
public class Group {
    @Id //
    @GeneratedValue() //
    private long id;

    private String name;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true) @JoinTable(name = "group_meetings") //
    private final List<GroupMeeting> meetings = new ArrayList<>();
}

and

import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class GroupMeeting {
    @Id //
    @GeneratedValue() //
    private long id;

    private String  title;
    private Date    start;
    private Date    end;
}

Answer:

You can use Hibernate filters to achieve that, for instance:

@Entity
@FilterDef(name="groupMeetingFilter",
        parameters={@ParamDef( name="fromDate", type="date"), @ParamDef(name="toDate", type="date")} )
public class Group {
    @Id //
    @GeneratedValue() //
    private long id;

    private String name;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true) @JoinTable(name = "group_meetings")
    @Filter(
        name = "groupMeetingFilter",
        condition="start <= :fromDate and end >= :toDate"
    )
    private final List<GroupMeeting> meetings = new ArrayList<>();
}

And you need to enable your filter somewhere in your application, just like this:

Session session = HibernateUtil.getSessionFactory().openSession();
Filter filter = session.enableFilter("groupMeetingFilter");
//Define here the dates that you want
filter.setParameter("fromDate", new Date());
filter.setParameter("toDate", new Date());

You could go further with your research and make the filter global available, if you're using Spring for instance, is easier.

Question:

I am new at JPA , I use Glassfish 4.1.1, when I try to create an EntityManagerFactory it shows this Exception message:

javax.persistence.PersistenceException: Exception [EclipseLink-7060] (Eclipse Persistence Services - 2.6.1.v20150605-31e8258): org.eclipse.persistence.exceptions.ValidationException Exception Description: Cannot acquire data source [java:app/quiz]. Internal Exception: javax.naming.NamingException: Lookup failed for 'java:app/quiz' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: No object bound to name java:app/quiz]

I checked my configurations files, and I think they are correct, can anyone help me?

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="QuizPU" transaction-type="JTA">
    <jta-data-source>java:app/quiz</jta-data-source>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
      <property name="javax.persistence.schema-generation.database.action" value="create"/>
    </properties>
  </persistence-unit>
</persistence>

glassfish-ressources.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Resource Definitions//EN" "http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>
    <jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="mysql_quiz_rootPool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.DataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
        <property name="serverName" value="localhost"/>
        <property name="portNumber" value="3306"/>
        <property name="databaseName" value="quiz"/>
        <property name="User" value="root"/>
        <property name="Password" value=""/>
        <property name="URL" value="jdbc:mysql://localhost:3306/quiz?zeroDateTimeBehavior=convertToNull"/>
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
    </jdbc-connection-pool>
    <jdbc-resource enabled="true" jndi-name="java:app/jdbc:mysql://localhost:3306/quiz" object-type="user" pool-name="mysql_quiz_rootPool"/>
</resources>

Answer:

well, I added this code to the web.xml file and it works fine

<resource-ref>
 <res-ref-name>java:app/quiz</res-ref-name>
 <res-type>javax.sql.DataSource</res-type>
 <res-auth>Container</res-auth>
 <res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>

Question:

I use Glassfish 4.1.1 (build 1), JPA, EJB, Netbeans, EclipseLink and MySQL. So I have a Web Application project with a JDBC Connection Pool and JDBC Resource.

Here my persistance.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="JavaProjectPU" transaction-type="JTA">
        <jta-data-source>java:app/jdbc/JavaProjectRessource</jta-data-source>
        <exclude-unlisted-classes>false</exclude-unlisted-classes>
        <properties/>
    </persistence-unit>
</persistence>

And my glassfish-resources.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Resource Definitions//EN" "http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>
  <jdbc-resource enabled="true" jndi-name="jdbc/JavaProjectRessource" object-type="user" pool-name="connectionPool">
    <description/>
  </jdbc-resource>
  <jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="connectionPool" non-transactional-connections="false" ping="false" pool-resize-quantity="2" pooling="true" res-type="javax.sql.DataSource" statement-cache-size="0" statement-leak-reclaim="false" statement-leak-timeout-in-seconds="0" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
    <property name="URL" value="jdbc:mysql://localhost:3306/javaproject"/>
    <property name="User" value="root"/>
    <property name="Password" value=""/>
  </jdbc-connection-pool>
</resources>

So all the configurations seem to be good between the application and MySQL database but when i'm running the app I got the following error :

Grave:   java.lang.RuntimeException: Invalid resource : { ResourceInfo : (jndiName=java:app/jdbc/JavaProjectRessource__pm), (applicationName=JavaProject) }
at com.sun.enterprise.connectors.ConnectorRuntime.lookupDataSourceInDAS(ConnectorRuntime.java:593)
at com.sun.enterprise.connectors.ConnectorRuntime.lookupPMResource(ConnectorRuntime.java:517)
at org.glassfish.persistence.common.PersistenceHelper.lookupPMResource(PersistenceHelper.java:63)
at org.glassfish.persistence.jpa.ProviderContainerContractInfoBase.lookupDataSource(ProviderContainerContractInfoBase.java:71)
at org.glassfish.persistence.jpa.PersistenceUnitInfoImpl.<init>(PersistenceUnitInfoImpl.java:108)
at org.glassfish.persistence.jpa.PersistenceUnitLoader.loadPU(PersistenceUnitLoader.java:142)
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:925)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:434)
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:539)
....

Does anyone have ideas what happened and what to do? I read that I need to download the Mysql's driver and place it in the lib folder but nothing changed


Answer:

The persistence xml file should have <jta-data-source>jdbc/JavaProjectRessource</jta-data-source>

Question:

I write Entity.jar .It's EJB Module contain entity class and etitydao class. When i run it on GlassFish , i have error:

Caused by: java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName null
    at com.sun.enterprise.container.common.impl.EntityManagerWrapper.init(EntityManagerWrapper.java:138)
    at com.sun.enterprise.container.common.impl.EntityManagerWrapper.doTxRequiredCheck(EntityManagerWrapper.java:158)
    at com.sun.enterprise.container.common.impl.EntityManagerWrapper.doTransactionScopedTxCheck(EntityManagerWrapper.java:151)
    at com.sun.enterprise.container.common.impl.EntityManagerWrapper.persist(EntityManagerWrapper.java:281)
    at com.styl.thincapayment.dao.impl.DataAccessImpl.insertToDatabase(DataAccessImpl.java:42)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)

I think it comes from persistence.xml . I put it wrong place. How to resolve this problem.

  • I put persistence file in entities/src/resources/persistence.xml . I use Maven to manage project

  • Declaration EntityManager:

    @PersistenceContext(unitName="entities")

    protected EntityManager entityManager;


Answer:

persistence.xml should be put inside the folder CLASS_PATH_ROOT/META-INF.

If you are using Maven 's standard project layout , the path should be src/main/resources/META-INF/persistence.xml

Question:

I need to delete a list of employees ignoring any integrity constraints (i.e. successfully delete the entity that doesn't related to any others yet or skip the entity that related to others) using JPA 2.0 and EJB3.0 on glassfish3.0:

I iterated on the list and call entity manager in a require_new transaction within a try/catch, I expect this will open small-nested transactions within the big transaction and I use em.flush() to force the updates.

but within iteration of a related entity it throws;

Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.4.2.v20130514-5956486): org.eclipse.persistence.exceptions.DatabaseException Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails

and continue to the next employee but at the commit of the big transaction it rollbacks and throw the same exception!

I expect to throw/catch the exception with in the new-small transaction and commit the successfully deleted entities of the rest of the list...

do I miss anything?

EDIT:

Here is some code, the code in the Facade to call the entity manager to remove the bean, I annotate the function by required-new:

 public void deleteEmployeeData(Set<Employees> deleted) throws DatabaseException {

        Iterator itr;
        Employees emp;


        //delete unused recordes 
        try {

            itr = deleted.iterator();

            while (itr.hasNext()) {
                emp = (Employees) itr.next();
                deleteEmployee(emp);                
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("DONE");
    }

    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    private void deleteEmployee(Employees emp){
        try {
                    this.remove(emp);
                } catch (Exception ex) {
                    System.out.println(ex.getMessage());
                }

    }

Answer:

deleteEmployee method is not wrapped into a new transaction because you are referencing method on this. What you can do is to inject reference to the facade itself and then call deleteEmployee method on it (it should be public).

More or less something like this:

@Stateless
public class MyFacade {
    @EJB
    private MyFacade self;

   public void deleteEmployeeData(Set<Employees> deleted) throws DatabaseException {
     ...
     try {
       self.deleteEmployee(emp);
     } catch (Exception ex) {
       // ...
     }
     ...
   }

    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void deleteEmployee(Employees emp) {
      this.remove(emp);
    }

}

Question:

I am very new to JavaEE. I've lookup a lot of questions about NullPinterException with EJB injection in this site and others, but have no success yet. I can't find the solution for my problem.

I created DynamicWebProject in Eclipse with JPA, JAX-RS, Glassfish Web Extensions facets. Here is the sctructure of my project (web.xml file is under the glassfish-web.xml file):


I try to call getemployees webservice which deployed to localhost Glassfish server and try to get information about all employees from my database (also at localhost). Here is the code of my GetEmployees class.

package bean;

import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

import com.google.gson.Gson;

import ejb.EmployeeEJB;

@ApplicationScoped
@ManagedBean
@Path("/getemployees")
public class GetEmployees {

    @Inject
    EmployeeEJB employeeEJB;

    @GET
    @Produces("application/json; charset=utf-8")
    public Response getAllEmployees() throws Exception {
        Gson gson = new Gson();
        String jsonString = null;
        try {
            jsonString = gson.toJson(employeeEJB.getAll());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Response.status(200).entity(jsonString).build();
    }
}

I created Managed and Session beans. I made Managed bean from my GetEmployees RESTful webservice class. Is it correct?

EmployeeEJB is the session bean:

package ejb;

import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import entity.Employee;

@LocalBean
@Stateless
public class EmployeeEJB {

    @PersistenceContext
    EntityManager em;

    public void saveEmployee(Employee employee) {
        em.merge(employee);
    }

    public void deleteEmployee(Employee employee) {
        em.remove(employee);
    }

    public List<Employee> getAll() {
        Query query = em.createQuery("SELECT emp FROM Employee emp", Employee.class);
        List<Employee> emp = (List<Employee>) query.getResultList();
        return emp;
    }

}

Here is my persistence.xml file. JDBC connection pool and JDBC resource created in Glassfish admin console. Connection to database is Ok.

<?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="FirstDynamicWebProject">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <jta-data-source>jdbc/second_attempt_hibernate</jta-data-source>
    <class>entity.Docstatus</class>
    <class>entity.Doctype</class>
    <class>entity.Document</class>
    <class>entity.Employee</class>
    <class>entity.Mailorder</class>
    <class>entity.Mailorderstatus</class>
    </persistence-unit>
</persistence>

NullPointerException occur when I try to call an employeeEJB.getAll() method in GetEmployees class:

2017-04-10T00:59:07.063+0500|Severe: java.lang.NullPointerException
    at bean.GetEmployees.getAllEmployees(GetEmployees.java:28)
    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 com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
    at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
    at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
    at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
    at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:558)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:733)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
    at java.lang.Thread.run(Thread.java:745)

I think the injection of EmployeeEJB is not correct, but have no ideas how to win it.


Answer:

I guess the problem is that you are using the wrong package for @ApplicationScoped. And you don't need the @ManagedBean there I think.

You are using:

import javax.faces.bean.ApplicationScoped;

Try the following:

import javax.enterprise.context.ApplicationScoped;

See also:

  • Why are there different bean management annotations

Question:

I am creating a server with Glassfish, Jersey, and a MySQL database

My EntityManager used to work but now does not

Here's an example of a simple method that used to work but now does not

@GET
@Path("movie/{id}")
@JSONP
@Produces({"application/javascript", MediaType.APPLICATION_JSON})
public Movie getMovie(@PathParam("id") int id) {
    EntityManager em = (EntityManager) context.getAttribute("em");
    Movie requestedMovie = em.find(Movie.class, id);
    return requestedMovie;
}

It now returns java.lang.IllegalArgumentException: Unknown Entity bean class: class data.entry.Movie, please verify that this class has been marked with the @Entity annotation.

Bizarrely, it still does this even when I use git to roll my code back to a commit where I know it used to work.

Additionally, the code still works on my teammate's laptops.

The issue started when I attempted to add annotations to another class, and attempted to test it. This error started appearing. I then rolled my code back to previous commits to undo my changes, but I am still getting the error.

I have tried rebooting my laptop multiple times as well to no avail.

Any idea what could cause entity manager to stop being able to find entities?


Answer:

Please try to remove built file. It's mostly related to IDE cache / build cache.

Unknown Entity bean class: class data.entry.Movie, please verify that this class has been marked with the @Entity annotation.

And please check this too.

Question:

I am trying to pass a set of JPA entity from the business tier to the presentation tier. All is deployed on the same app server (Glassfish 4). The client is deployed as a .war file, while the Business Tier as an .ear with the ejb reachable trough a Remote interface.

For this I have those very simple methods, with absolutely no logic:

Client

    public List<CompletedDesign> selectCompletedDesigns() {
        try {
            List<CompletedDesign> designs = customerFacade.selectCompletedDesigns();
            return designs;
        } catch (EJBException e) {
            e.printStackTrace();
        }
        return null;
    }

And in the ejb

// EJB
@Override
@RolesAllowed("customer")
public List<CompletedDesign> selectCompletedDesigns() {

    final Principal callerPrincipal = sessionCtx.getCallerPrincipal();

    String name = callerPrincipal.getName();
    Customer customer = dataXchangeBean.getCustomerByID(name);
    List<CompletedDesign> cds = customerBean.selectCompletedDesigns(customer);
    return cds;
}

Final this is a fragment of the JPA Entity.

@Entity
@Table(name = "COMPLETED_DESIGN")
@NamedQueries({......})
public class CompletedDesign implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 20)
    @Column(name = "ID")
    private String id;
    @Column(name = "DESCRIPTION")
    private String description;
    @Column(name = "NAME")
    private String name;
    @Column(name = "STATUS")
    private DesignStatus status;    
    @JoinColumn(name = "CUSTOMER_FK", referencedColumnName = "ID")
    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    private Customer customerFk;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "designFk", fetch = FetchType.LAZY)
    private List<Product> products;

By putting a breakpoint I can see the cds list is correctly retrieved in the EJB side. The very first question would be, why I am getting a Vector instead of a List ? I am using a TypedQuery from the JPS side and that was supposed to correctly cast the object.

However my main concern is this: in the subsequent breakpoint on the client class itself in the presentation layer, it seems that it cannot fully reconstruct the object, the values are all null, and the type is missing. What am I missing here ?


Answer:

You are using LAZY loading, which means related objects will be loaded when you access them, and not when the primary object is loaded (so that they won't be loaded if you really don't need them). This however, does not work when the primary object is detached from the session. Therefore you must either use EAGER instead of lazy, or just load (access) the collections you need inside the transaction, before passed over the remote interface.