Hot questions for Using GlassFish in hibernate

Question:

I'm getting an exception with Hibernate when trying to load a class with a Map of .

it works without, but when I add this field to the class it gives the error in the title.

Here are the classes, Person, PhoneNumber, PersonServiceImpl and IPersonService.

All of this seems to work without the Person.PhoneNumber field.

Any ideas?

My test case works fine:

for (int i = 0; i < getIterations(); i++) {
            entityManager.getTransaction().begin();
            Person person = getPersonForIteration(i);
            entityManager.persist(person);
            entityManager.getTransaction().commit();
            Person foundPerson = entityManager.find(Person.class,
                                                              person.getId());
            doAssertsForFoundPerson(foundPerson, person);
        }

Entity and service classes:

@Entity
@Table(name = "ent_person")
public class Person implements Serializable, Comparable<Person> {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    /**
     * Comment for <code>serialVersionUID</code>
     */
    private static final long serialVersionUID = -4680156785318108346L;

    protected String firstName;

    protected String nickname;

    protected String lastName;

    @ElementCollection(fetch = FetchType.EAGER)
    protected List<String> middleNames;

    protected String idNum;

    protected char isMale;

    @Temporal(value = TemporalType.DATE)
    protected Date birthday;

    @ElementCollection(fetch=FetchType.EAGER)
    @MapKeyColumn(name = "name")
    @Column(name = "value")
    protected Map<String, PhoneNumber> phoneNumbers;

    public Person() {
        super();
    }

    /**
     * @param firstName
     * @param nickname
     * @param lastName
     * @param middleNames
     * @param idNum
     * @param isMale
     * @param birthday
     */
    public Person(String firstName, String nickname, String lastName, List<String> middleNames,
            String idNum, char isMale, Date birthday) {
        super();
        this.firstName = firstName;
        this.nickname = nickname;
        this.lastName = lastName;
        this.middleNames = middleNames;
        this.idNum = idNum;
        this.isMale = isMale;
        this.birthday = birthday;
    }

    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public void setPhoneNumber(String numberType, PhoneNumber number) {
        if (phoneNumbers == null) {
            phoneNumbers = new HashMap<String, PhoneNumber>();
        }
        phoneNumbers.put(numberType, number);
    }

    public Map<String, PhoneNumber> getPhoneNumbers() {
        return phoneNumbers;
    }

    /**
     * @return Returns the firstName.
     */
    public String getFirstName() {
        return firstName;
    }

    /**
     * @param firstName The firstName to set.
     */
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    /**
     * @return Returns the nickname.
     */
    public String getNickname() {
        return nickname;
    }

    /**
     * @param nickname The nickname to set.
     */
    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    /**
     * @return Returns the lastName.
     */
    public String getLastName() {
        return lastName;
    }

    /**
     * @param lastName The lastName to set.
     */
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public void addMiddleName(String middleName) {
        if (middleNames == null) {
            middleNames = new ArrayList<String>();
        }

        if (!middleNames.contains(middleName)) {
            middleNames.add(middleName);
        }
    }

    /**
     * @return Returns the middleNames.
     */
    public List<String> getMiddleNames() {
        return middleNames;
    }

    /**
     * @param middleNames The middleNames to set.
     */
    public void setMiddleNames(List<String> middleNames) {
        this.middleNames = middleNames;
    }

    /**
     * @return Returns the idNum.
     */
    public String getIdNum() {
        return idNum;
    }

    /**
     * @param idNum The idNum to set.
     */
    public void setIdNum(String idNum) {
        this.idNum = idNum;
    }

    /**
     * @return Returns the isMale.
     */
    public char getIsMale() {
        return isMale;
    }

    /**
     * @param isMale The isMale to set.
     */
    public void setIsMale(char isMale) {
        this.isMale = isMale;
    }

    @JsonIgnore
    public boolean isMale() {
        return isMale == 'y';
    }

    /**
     * @return Returns the birthday.
     */
    public Date getBirthday() {
        return birthday;
    }

    /**
     * @param birthday The birthday to set.
     */
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    /**
     * @return
     *
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((birthday == null) ? 0 : birthday.hashCode());
        result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
        result = prime * result + ((idNum == null) ? 0 : idNum.hashCode());
        result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
        result = prime * result + ((middleNames == null) ? 0 : middleNames.hashCode());
        result = prime * result + ((nickname == null) ? 0 : nickname.hashCode());
        return result;
    }

    /**
     * @param o
     * @return
     *
     * @see java.lang.Comparable#compareTo(java.lang.Object)
     */
    public int compareTo(Person o) {
        int result = lastName.compareTo(o.getLastName());
        return result == 0 ? firstName.compareTo(o.getLastName()) : result;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Person other = (Person) obj;
        if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) {
            return false;
        }
        if ((this.firstName == null) ? (other.firstName != null) : !this.firstName.equals(other.firstName)) {
            return false;
        }
        if ((this.nickname == null) ? (other.nickname != null) : !this.nickname.equals(other.nickname)) {
            return false;
        }
        if ((this.lastName == null) ? (other.lastName != null) : !this.lastName.equals(other.lastName)) {
            return false;
        }
        if (this.middleNames != other.middleNames && (this.middleNames == null || !this.middleNames.equals(other.middleNames))) {
            return false;
        }
        if ((this.idNum == null) ? (other.idNum != null) : !this.idNum.equals(other.idNum)) {
            return false;
        }
        if (this.birthday != other.birthday && (this.birthday == null || !this.birthday.equals(other.birthday))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "Person{" + "id=" + id + ", firstName=" + firstName + ", nickname=" + nickname + ", lastName=" + lastName + ", middleNames=" + middleNames + ", idNum=" + idNum + ", isMale=" + isMale + ", birthday=" + birthday + ", phoneNumbers=" + phoneNumbers + '}';
    }

}

public class PhoneNumber implements Serializable {

    private static final long serialVersionUID = -423634682785318106L;

    public static transient final String HOME = "Home";

    public static final String PERSONAL_MOBILE = "Personal Mobile";

    public static final String OFFICE = "Office";

    public static final String WORK_MOBILE = "Work Mobile";

    public static final String FAX = "Fax";

    public static final String PAGER = "Pager";

    public static final String TOLL_FREE = "Toll Free";

    public static final String OTHER = "Other";

    String countryCode;

    String areaCode;

    String subscriberNubmer;

    String extension;

    public PhoneNumber() {
        super();
    }

    /**
     * @param countryCode
     * @param areaCode
     * @param subscriberNubmer
     * @param extension
     */
    public PhoneNumber(String countryCode, String areaCode, String subscriberNubmer,
            String extension) {
        super();
        this.countryCode = countryCode;
        this.areaCode = areaCode;
        this.subscriberNubmer = subscriberNubmer;
        this.extension = extension;
    }

    /**
     * @return Returns the countryCode.
     */
    public String getCountryCode() {
        return countryCode;
    }

    /**
     * @param countryCode The countryCode to set.
     */
    public void setCountryCode(String countryCode) {
        this.countryCode = countryCode;
    }

    /**
     * @return Returns the areaCode.
     */
    public String getAreaCode() {
        return areaCode;
    }

    /**
     * @param areaCode The areaCode to set.
     */
    public void setAreaCode(String areaCode) {
        this.areaCode = areaCode;
    }

    /**
     * @return Returns the subscriberNubmer.
     */
    public String getSubscriberNubmer() {
        return subscriberNubmer;
    }

    /**
     * @param subscriberNubmer The subscriberNubmer to set.
     */
    public void setSubscriberNubmer(String subscriberNubmer) {
        this.subscriberNubmer = subscriberNubmer;
    }

    /**
     * @return Returns the extension.
     */
    public String getExtension() {
        return extension;
    }

    /**
     * @param extension The extension to set.
     */
    public void setExtension(String extension) {
        this.extension = extension;
    }

    /**
     * @return
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "PhoneNumber [countryCode=" + countryCode + ", areaCode=" + areaCode
                + ", subscriberNubmer=" + subscriberNubmer + ", extension=" + extension + "]";
    }

    /**
     * @return
     *
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((areaCode == null) ? 0 : areaCode.hashCode());
        result = prime * result + ((countryCode == null) ? 0 : countryCode.hashCode());
        result = prime * result + ((extension == null) ? 0 : extension.hashCode());
        result = prime * result + ((subscriberNubmer == null) ? 0 : subscriberNubmer.hashCode());
        return result;
    }

    /**
     * @param obj
     * @return
     *
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        PhoneNumber other = (PhoneNumber) obj;
        if (areaCode == null) {
            if (other.areaCode != null) {
                return false;
            }
        } else if (!areaCode.equals(other.areaCode)) {
            return false;
        }
        if (countryCode == null) {
            if (other.countryCode != null) {
                return false;
            }
        } else if (!countryCode.equals(other.countryCode)) {
            return false;
        }
        if (extension == null) {
            if (other.extension != null) {
                return false;
            }
        } else if (!extension.equals(other.extension)) {
            return false;
        }
        if (subscriberNubmer == null) {
            if (other.subscriberNubmer != null) {
                return false;
            }
        } else if (!subscriberNubmer.equals(other.subscriberNubmer)) {
            return false;
        }
        return true;
    }
}

@Remote
@Local
public interface IPersonService {
    public Collection<Person> getAllPeople();
    Person getPerson(String idNum);
    public void removePerson(Person p);
}


@Stateless(name = "personService")
public class PersonServiceImpl implements IPersonService {
    @PersistenceContext
    EntityManager em;

    public Collection<Person> getAllPeople(){
        Query query = em.createQuery("SELECT p FROM Person p");
        return (Collection<Person>)query.getResultList();
    }

    public Person getPerson(String idNum) {
        Person p = new Person();
        p.setFirstName("John");
        p.setLastName("Doe");
        p.setIdNum(idNum);
        p.setPhoneNumber(PhoneNumber.HOME, new PhoneNumber());
        em.persist(p);
        return p;
    }

    public void removePerson(Person p) {
        em.remove(p);
    }
}

Here is the stack trace, too:

Warning:   StandardWrapperValve[net.somepackage.demo.web.servlet.BasicServlet]: Servlet.service() for servlet net.somepackage.demo.web.servlet.BasicServlet threw exception
javax.ejb.EJBException
........
Caused by: java.lang.IllegalStateException: This web container has not yet been started
    at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1674)
    at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1633)
    at sun.misc.Unsafe.defineClass(Native Method)
    at sun.reflect.ClassDefiner.defineClass(ClassDefiner.java:63)
    at sun.reflect.MethodAccessorGenerator$1.run(MethodAccessorGenerator.java:399)
    at sun.reflect.MethodAccessorGenerator$1.run(MethodAccessorGenerator.java:394)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.reflect.MethodAccessorGenerator.generate(MethodAccessorGenerator.java:393)
    at sun.reflect.MethodAccessorGenerator.generateSerializationConstructor(MethodAccessorGenerator.java:112)
    at sun.reflect.ReflectionFactory.newConstructorForSerialization(ReflectionFactory.java:340)
    at java.io.ObjectStreamClass.getSerializableConstructor(ObjectStreamClass.java:1376)
    at java.io.ObjectStreamClass.access$1500(ObjectStreamClass.java:72)
    at java.io.ObjectStreamClass$2.run(ObjectStreamClass.java:493)
    at java.io.ObjectStreamClass$2.run(ObjectStreamClass.java:468)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.io.ObjectStreamClass.<init>(ObjectStreamClass.java:468)
    at java.io.ObjectStreamClass.lookup(ObjectStreamClass.java:365)
    at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:602)
    at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1623)
    at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1518)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1774)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)
    at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:225)
    at org.hibernate.internal.util.SerializationHelper.deserialize(SerializationHelper.java:287)
    at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.fromBytes(SerializableTypeDescriptor.java:138)
    at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:113)
    at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:27)
    at org.hibernate.type.descriptor.sql.VarbinaryTypeDescriptor$2.doExtract(VarbinaryTypeDescriptor.java:53)
    at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:47)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:241)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:237)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:227)
    at org.hibernate.persister.collection.AbstractCollectionPersister.readElement(AbstractCollectionPersister.java:833)
    at org.hibernate.collection.internal.PersistentMap.readFrom(PersistentMap.java:263)
    at org.hibernate.loader.plan.exec.process.internal.CollectionReferenceInitializerImpl.finishUpRow(CollectionReferenceInitializerImpl.java:77)
    at org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.readRow(AbstractRowReader.java:108)
    at org.hibernate.loader.plan.exec.process.internal.ResultSetProcessorImpl.extractResults(ResultSetProcessorImpl.java:112)
    at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:121)
    at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:85)
    at org.hibernate.loader.collection.plan.AbstractLoadPlanBasedCollectionInitializer.initialize(AbstractLoadPlanBasedCollectionInitializer.java:82)
    at org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:682)
    at org.hibernate.event.internal.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:75)
    at org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:1922)
    at org.hibernate.collection.internal.AbstractPersistentCollection.forceInitialization(AbstractPersistentCollection.java:709)
    at org.hibernate.engine.internal.StatefulPersistenceContext.initializeNonLazyCollections(StatefulPersistenceContext.java:885)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:341)
    at org.hibernate.loader.Loader.doList(Loader.java:2611)
    at org.hibernate.loader.Loader.doList(Loader.java:2594)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2423)
    at org.hibernate.loader.Loader.list(Loader.java:2418)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:501)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:371)
    at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:220)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1268)
    at org.hibernate.internal.QueryImpl.list(QueryImpl.java:87)
    at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:567)
    at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:436)
    at net.somepackage.demo.service.PersonServiceImpl.getAllPeople(PersonServiceImpl.java:27)
    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.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
    at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
    at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4786)
    at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:656)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
    at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:46)
    at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
    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 com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
    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 com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
    at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
    at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4758)
    at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4746)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
    ... 33 more

Answer:

As far as I could determine, there was an issue with classloading. I'm not sure what it was, but when I downgraded to Hibernate 4.3.11.Final things started working properly.

I'm not sure why, and got tired of trying to figure it out. Once I switched the version of Hibernate everything worked.

Question:

Using GlassFish 4 Stack trace looks like this

Caused by: java.lang.AbstractMethodError
at com.sun.enterprise.container.common.impl.EntityManagerWrapper._getDelegate(EntityManagerWrapper.java:197)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.createQuery(EntityManagerWrapper.java:455)
at com.wellpoint.mobility.aggregation.core.configuration.impl.ConfigurationManagerImpl.loadConfiguration(ConfigurationManagerImpl.java:262)

Here are the hibernate jars, which from googling this problem I gather are relevant.

hibernate-commons-annotations-4.0.2.Final.jar
hibernate-core-4.2.15.Final.jar
hibernate-entitymanager.4.2.15.Final.jar
hibernate-jpa-2.0-api.1.0.1.Final.jar

According to another question I saw on this same exception hibernate JPA 2.0 should work with hibernate versions > 3.5. Vague recollections of math classes tell me that 4.2.15 > 3.5, so presumably I shouldn't be having these problems. Any thoughts?


Answer:

GlassFish 4 uses Java EE 7, so therefore you should use JPA 2.1 instead of JPA 2.0.

According to Hibernate docs this is the compatibility suite:

  • JPA 1.0: ORM 3.2+

  • JPA 2.0: ORM 3.5+

  • JPA 2.1: ORM 4.3+

So you should use Hibernate 4.3 with JPA 2.1:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.3.7.Final</version>
</dependency>

<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.1-api</artifactId>
    <version>1.0.0.Final</version>
</dependency>

Question:


Answer:

Problem solved. Glassfish has outdated jboss-logging jar in \glassfish\modules folder. Replacing jar with latest version helped.

Question:

I have the below persistence file -

<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="unit" >
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

<properties>
    <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
    <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
    <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/db" />
    <property name="hibernate.connection.username" value="user" />
    <property name="hibernate.connection.password" value="pwd" />

Now, when I deploy this on glassfish - generate logs as below -

HHH000204: Processing PersistenceUnitInfo [
name: application
...]
HHH000412: Hibernate Core {5.2.2.Final}
HHH000206: hibernate.properties not found
HHH000021: Bytecode provider name : javassist
HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Warning: RAR5038:Unexpected exception while creating resource for pool DerbyPool. Exception : javax.resource.spi.ResourceAllocationException: Connection could not be allocated because: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect.
Warning: RAR5117 : Failed to obtain/create connection from connection pool [ DerbyPool ]. Reason : com.sun.appserv.connectors.internal.api.PoolingException: Connection could not be allocated because: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect.
Warning: RAR5114 : Error allocating connection : [Error in allocating a connection. Cause: Connection could not be allocated because: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect.]
WARN: HHH000342: Could not obtain connection to query metadata : Error in allocating a connection. Cause: Connection could not be allocated because: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect.
Info: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Info: HHH000422: Disabling contextual LOB creation as connection was null
Info: HHH000397: Using ASTQueryTranslatorFactory
Info: Loading application [application] at [/application]
Info: application was successfully deployed in 14,905 milliseconds.

Why does glassfish complains about derby? I'm not using it.

And, when I try to access a rest service -which internally goes for entitymanager - I get the below stacktrace --

2016-10-03T12:41:03.337+0530|Info: HHH000204: Processing PersistenceUnitInfo [
name: unit
...]
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Info: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/db]
Info: HHH10001001: Connection properties: {user=user, password=****}
Info: HHH10001003: Autocommit mode: false
Info: HHH000115: Hibernate connection pool size: 20 (min=1)
Info: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Info: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Info: HHH000397: Using ASTQueryTranslatorFactory
Info: not null  <<<<<<---------- this is my EntityManager instance which is not null
Warning: RAR5038:Unexpected exception while creating resource for pool DerbyPool. Exception : javax.resource.spi.ResourceAllocationException: Connection could not be allocated because: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect.
Warning: RAR5117 : Failed to obtain/create connection from connection pool [ DerbyPool ]. Reason : com.sun.appserv.connectors.internal.api.PoolingException: Connection could not be allocated because: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect.
Warning: RAR5114 : Error allocating connection : [Error in allocating a connection. Cause: Connection could not be allocated because: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect.]
WARN: SQL Error: 0, SQLState: null
ERROR: Error in allocating a connection. Cause: Connection could not be allocated because: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect.
ERROR: HHH000337: Unable to mark for rollback on PersistenceException: 
org.hibernate.resource.transaction.backend.jta.internal.JtaPlatformInaccessibleException: Unable to access TransactionManager or UserTransaction to make physical transaction delegate
at org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorImpl.makePhysicalTransactionDelegate(JtaTransactionCoordinatorImpl.java:229)
at org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorImpl.getTransactionDriverControl(JtaTransactionCoordinatorImpl.java:203)
at org.hibernate.engine.transaction.internal.TransactionImpl.<init>(TransactionImpl.java:37)
at org.hibernate.internal.AbstractSharedSessionContract.accessTransaction(AbstractSharedSessionContract.java:372)
at org.hibernate.internal.AbstractSharedSessionContract.markForRollbackOnly(AbstractSharedSessionContract.java:342)
at org.hibernate.internal.ExceptionConverterImpl.handlePersistenceException(ExceptionConverterImpl.java:271)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:148)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:155)
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1407)
at org.hibernate.Query.getResultList(Query.java:417)
at org.hibernate.query.criteria.internal.compile.CriteriaQueryTypeQueryAdapter.getResultList(CriteriaQueryTypeQueryAdapter.java:72)
at com.sun.enterprise.container.common.impl.QueryWrapper.getResultList(QueryWrapper.java:84)
at com.sun.enterprise.container.common.impl.TypedQueryWrapper.getResultList(TypedQueryWrapper.java:73)
at RESTClass.findAll(RESTClass.java:76)
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.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:205)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:471)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:425)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:383)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:336)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:223)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1681)
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:466)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:169)
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:284)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:526)
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)

Warning: StandardWrapperValve[rest_servlet]: Servlet.service() for servlet rest_servlet threw exception
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at java.net.Socket.<init>(Socket.java:434)
at java.net.Socket.<init>(Socket.java:211)
at javax.net.DefaultSocketFactory.createSocket(SocketFactory.java:271)
at org.apache.derby.client.net.OpenSocketAction.run(Unknown Source)
at org.apache.derby.client.net.OpenSocketAction.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at org.apache.derby.client.net.NetAgent.<init>(Unknown Source)
at org.apache.derby.client.net.NetConnection.newAgent_(Unknown Source)
at org.apache.derby.client.am.Connection.initConnection(Unknown Source)
at org.apache.derby.client.am.Connection.<init>(Unknown Source)
at org.apache.derby.client.net.NetConnection.<init>(Unknown Source)
at org.apache.derby.client.net.NetConnection40.<init>(Unknown Source)
at org.apache.derby.client.net.ClientJDBCObjectFactoryImpl40.newNetConnection(Unknown Source)
at org.apache.derby.jdbc.ClientBaseDataSourceRoot.getConnectionX(Unknown Source)
at org.apache.derby.jdbc.ClientBaseDataSourceRoot.getConnection(Unknown Source)
at com.sun.gjc.spi.DSManagedConnectionFactory.createManagedConnection(DSManagedConnectionFactory.java:117)
at com.sun.enterprise.resource.allocator.LocalTxConnectorAllocator.createResource(LocalTxConnectorAllocator.java:87)
at com.sun.enterprise.resource.pool.ConnectionPool.createSingleResource(ConnectionPool.java:907)
at com.sun.enterprise.resource.pool.ConnectionPool.createResource(ConnectionPool.java:1189)
at com.sun.enterprise.resource.pool.datastructure.RWLockDataStructure.addResource(RWLockDataStructure.java:98)
at com.sun.enterprise.resource.pool.ConnectionPool.addResource(ConnectionPool.java:282)
at com.sun.enterprise.resource.pool.ConnectionPool.createResourceAndAddToPool(ConnectionPool.java:1512)
at com.sun.enterprise.resource.pool.ConnectionPool.createResources(ConnectionPool.java:944)
at com.sun.enterprise.resource.pool.ConnectionPool.initPool(ConnectionPool.java:230)
at com.sun.enterprise.resource.pool.ConnectionPool.internalGetResource(ConnectionPool.java:511)
at com.sun.enterprise.resource.pool.ConnectionPool.getResource(ConnectionPool.java:381)
at com.sun.enterprise.resource.pool.PoolManagerImpl.getResourceFromPool(PoolManagerImpl.java:245)
at com.sun.enterprise.resource.pool.PoolManagerImpl.getResource(PoolManagerImpl.java:171)
at com.sun.enterprise.connectors.ConnectionManagerImpl.getResource(ConnectionManagerImpl.java:360)
at com.sun.enterprise.connectors.ConnectionManagerImpl.internalGetConnection(ConnectionManagerImpl.java:307)
at com.sun.enterprise.connectors.ConnectionManagerImpl.allocateConnection(ConnectionManagerImpl.java:196)
at com.sun.enterprise.connectors.ConnectionManagerImpl.allocateConnection(ConnectionManagerImpl.java:171)
at com.sun.enterprise.connectors.ConnectionManagerImpl.allocateConnection(ConnectionManagerImpl.java:166)
at com.sun.gjc.spi.base.AbstractDataSource.getConnection(AbstractDataSource.java:147)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
at org.hibernate.internal.NonContextualJdbcConnectionAccess.obtainConnection(NonContextualJdbcConnectionAccess.java:35)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:99)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:129)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.connection(StatementPreparerImpl.java:47)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:146)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:172)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:148)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1940)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1909)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1887)
at org.hibernate.loader.Loader.doQuery(Loader.java:932)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:349)
at org.hibernate.loader.Loader.doList(Loader.java:2615)
at org.hibernate.loader.Loader.doList(Loader.java:2598)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2430)
at org.hibernate.loader.Loader.list(Loader.java:2425)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:502)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:371)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1458)
at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1426)
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1398)
at org.hibernate.Query.getResultList(Query.java:417)
at org.hibernate.query.criteria.internal.compile.CriteriaQueryTypeQueryAdapter.getResultList(CriteriaQueryTypeQueryAdapter.java:72)
at com.sun.enterprise.container.common.impl.QueryWrapper.getResultList(QueryWrapper.java:84)
at com.sun.enterprise.container.common.impl.TypedQueryWrapper.getResultList(TypedQueryWrapper.java:73)
at com.accountpro.entity.service.AbstractFacade.findAll(AbstractFacade.java:43)
at com.accountpro.entity.service.CityFacadeREST.findAll(CityFacadeREST.java:76)
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.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:205)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:471)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:425)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:383)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:336)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:223)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1681)
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:466)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:169)
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:284)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:526)
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)

Can someone hazard a guess...like what could be wrong? I am trying to use built in connection pooling which comes with hibernate.

Update - Below is how am injecting the EntityManager in one of my service class

@PersistenceContext(unitName = "unit")
private EntityManager em;

Answer:

Looking at the following line in the stacktrace

ERROR: Error in allocating a connection. Cause: Connection could not be allocated because: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect.

you can guess what the problem can be. The first problem is the database driver issue I think. 1527 is the default port number of derby database which is shipped with the Glassfish application server.

As you haven't provided any datasource in your configuration the server is trying to find the default database which is derby in this case; but you cannot connect to that database as you haven't provided any connection informations for this database.

So you have to do the following in your META-INF/persistence.xml:

  • Provide the transaction-type (in your config it is assumed to be JTA because you're deploying your application on JEE environment per specification) as

    <persistence-unit name="unit" transaction-type="JTA">
    
  • Provide the jta-data-source element as a child of persistence-unit

    <persistence-unit name="unit" transaction-type="JTA">
        ...
        <jta-data-source>your_data_source_name</jta-data-source>
        ...
    </persistence-unit>
    

In order for the above configuration to work you have to configure your application server (Glassfish) frist. To do so you have to download the MySQL jdbc driver, unpack it and copy the jar file into <glassfish_installation_directory>/glassfish/domains/domain1/lib (I am assuming here Glassfish 3.1). The reason for this is that Glassfish is not shipped with MySQL driver, so you have to do this yourself.

After this start Glassfish and open the admin console (http://localhost:4848). On the left pane open

  1. Resources/JDBC/JDBC Connection Pools and create a new connection pool
  2. Resources/JDBC/JDBC Resources and create a new datasource. The name you give to your datasource is the one you have to in your persistence.xml as mentioned above.

Question:

By using CDI as shown in the next code:

@PersistenceUnit
EntityManagerFactory emf;

I want to inject my hibernate EntityManagerFactory

Currently if I execute the next line:

EntityManagerFactory emf = Persistence.createEntityManagerFactory("HibernatePersistanceProv");

It works just as expected, but if I do it using the first method it tries to use the Derby connection I know this because I get the next error message:

org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection

By the stack trace I know that it is caused because of this.

Error connecting to server localhost on port 1527 with message Connection refused.

Which I know it is because it is trying to connect to the (Java DB) Derby db.

My persistance.xml looks like this:

<?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="HibernatePersistanceProv" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <exclude-unlisted-classes>false</exclude-unlisted-classes>
        <properties>
            <property name="hibernate.connection.username" value="root"/>
            <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/aschema"/>
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
            <property name="hibernate.connection.username" value="root"/>
            <property name="hibernate.connection.password" value=""/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="false"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/aschema"/>
            <property name="javax.persistence.jdbc.user" value="root"/>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
        </properties>
    </persistence-unit>
</persistence>

I was reading that apparently I need to specify a standalone.xml to provide a different <jta-data-source> but it seams to me a bit more complicated than what it should be (I do not want to chase the wrong rabbit), I have been from the Java EE world for a while so I consider my self as brand new to this (for dummies explanations are widely appreciated).

(If it helps) I am running on a GlassFish 4.1 server. Please ask if any other information is required.


Answer:

I think your problem is database related but for injecting EntityManager I usually go with this:

public class EntityManagerFactoryProducer {

        @Produces
        @ApplicationScoped
        public EntityManagerFactory create() {
            return Persistence.createEntityManagerFactory("HibernatePersistanceProv");
        }

        public void destroy(@Disposes EntityManagerFactory factory) {
            factory.close();
        }

    }

    public class EntityManagerProducer {

        @Inject
        private EntityManagerFactory emf;

        @Produces
        @RequestScoped
        public EntityManager create() {
            return emf.createEntityManager();
        }

        public void destroy(@Disposes EntityManager em) {
            em.close();
        }
    }

Than just simply inject it where ever you want. If you have more database use qualifier combined with inject.

@Inject
private EntityManager entityManager;

Question:

When my Struts app on Glassfish queries for first time, such error occurs:

Severe: Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: com/mchange/v2/c3p0/DataSources
Info: 2015-07-28 13:59:17 ERROR HibernateUtil:54 - Initial SessionFactory creation failed
java.lang.NoClassDefFoundError: com/mchange/v2/c3p0/DataSources
    at org.hibernate.connection.C3P0ConnectionProvider.configure(C3P0ConnectionProvider.java:176)
    at org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:143)
    at org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:84)
    at org.hibernate.cfg.SettingsFactory.createConnectionProvider(SettingsFactory.java:459)
    at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:91)
    at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2833)
    at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2829)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1840)
    [...]

I've tried to resolve this using this article, but still same error occurs..

My dependencies I use to run this app:

        <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-core</artifactId>
                <version>3.6.3.Final</version>
                <type>jar</type>
        </dependency>
        <!-- Hibernate c3p0 connection pool -->
        <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-c3p0</artifactId>
                <version>3.6.3.Final</version>
        </dependency>
        <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-tools</artifactId>
                <version>3.6.0.CR1</version>
        </dependency>
        <dependency>
                <groupId>com.mchange</groupId>
                <artifactId>mchange-commons-java</artifactId>
                <version>0.2.10</version>
        </dependency>
        <dependency>
                <groupId>c3p0</groupId>
                <artifactId>c3p0-oracle-thin-extras</artifactId>
                <version>0.9.0.2</version>
        </dependency>
        <dependency>
                <groupId>com.mchange AND c3p0</groupId>
                <artifactId>c3p0</artifactId>
                <version>0.9.2.1</version>
        </dependency>

This app worked perfectly without Maven..

Thanks for help! :)


Answer:

In

<dependency>
   <groupId>com.mchange AND c3p0</groupId>
   <artifactId>c3p0</artifactId>
   <version>0.9.2.1</version>
</dependency>

The AND c3p0 is superfluous.

It should be

<dependency>
   <groupId>com.mchange</groupId>
   <artifactId>c3p0</artifactId>
   <version>0.9.2.1</version>
</dependency>

Or better yet, use the current production version

<dependency>
   <groupId>com.mchange</groupId>
   <artifactId>c3p0</artifactId>
   <version>0.9.5.1</version>
</dependency>

Question:

Suppose I have a managed bean and I have defined an EntityManager. I was wondering how transactions work and how they behave in a variety of different situations. From the documentation I understood that flush() is actually used to overwrite the delay on the commit and do it immediatelly. So in the example bellow I was expecting demo to persist in the DB and demo2 not to. But it seems like it is all seen as a single transaction (from my understanding). Why is this happening? Why no further annotation or hibernate methods of begin() and commit() are needed to define the beginning and the end of the transaction? I feel like I am confusing different things here...

@Stateless
public class Testing {
    @PersistenceContext(unitName = "testDB")
    private EntityManager em;

    public void doSomeWork(){
        Demo demo = new Demo();
        em.persist(demo);
        em.flush();
        //some code that makes it crash
        Demo demo2 = new Demo();
        em.persist(demo2);
        em.flush();
    }
}

Answer:

When using Container managed transactions all session beans are by default run within transaction. That means, if some exception occurs that causes transaction to rollback the changes to demo are rolled back as well.

Here is some useful information about how flush() works: https://en.wikibooks.org/wiki/Java_Persistence/Persisting#Flush