Why EntityManager have null value in my dao layer? - jpa

I'm working on a Java EE 7 maven project I'm using wildfly 8.2 everything is okey the problem is when I create an entity manager using #PersistenceContext inside managedbeans (backing beans) that I use with my jsf the contanier create a entit manager object and it's work but when I try to use the entity maanger inside my DAO Layer it's not work the em stay have a null value and I don't know why this my code in my dao layer can someone helpe me ? .
dao interface :
public interface ICategoryDao {
Category addCategory(Category category);
void deleteCategory(Long codeCategory);
Set<Category> getAllCategories();
Category updateCategory(Category category);
}
dao impl :
#Named("categoryDao")
public class CategoryDao implements ICategoryDao{
private Logger log = Logger.getLogger(CategoryDao.class);
#PersistenceContext(unitName="BooksStore")
private EntityManager em ;
#Override
public Category addCategory(Category category) {
if(em==null)
{
log.info("em is null ");
return category;
}
em.getTransaction().begin();
em.persist(category);
em.getTransaction().commit();
log.info("CategoryDao : Object persisted." );
return category;
}
#Override
public void deleteCategory(Long codeCategory) {
// TODO Auto-generated method stub
}
#Override
public Set<Category> getAllCategories() {
// TODO Auto-generated method stub
return null;
}
#Override
public Category updateCategory(Category category) {
// TODO Auto-generated method stub
return null;
}
}
this is my beans.xml
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd" bean-discovery-mode="all">
</beans>
My persistance.xml file :
<?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="BooksStore" transaction-type="JTA">
<jta-data-source>java:/bookstore</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
</persistence>

Do you have a persistence.xml file ?
This is an example for persistence.xml file :
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" 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">
<persistence-unit name="School_Manager" transaction-type="RESOURCE_LOCAL">
<class>YourEntityFQN</class>
<properties>
attribute name on persistence.xml file must be "BooksStore" in your case .
In class tag you need to specify all entity that you want use for this persistence-unit .

Related

Unable to build entity manager factory - Rest Tomcat Jpa

I'm making a Restful web service using netbeans, tomcat, jpa and jax-rs. I have this error since I've add the <class /> tags to my persistence.xml for all of my classes (And I need them to make a select).
The error is : https://gist.github.com/anonymous/bb37c28cdb3dbdf721c5206bfa6369c3
And my persistence.xml is :
<?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="NataRestServicePU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>model.Media</class>
<class>model.MediaTypeDB</class>
<class>model.Message</class>
<class>model.Observation</class>
<class>model.Session</class>
<class>model.Species</class>
<class>model.User</class>
<class>model.UserType</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3307/natagora?zeroDateTimeBehavior=convertToNull"/>
<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="password"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
</properties>
</persistence-unit>
</persistence>
And this is the main dao (that worked before, didn't change anything) but without all the CRUD methods (just the read for example)
package dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
public class MainDAO<T> implements IMainDAO<T> {
protected Class<T> clazz;
private final EntityManagerFactory factory;
private static final String PERSISTENCE_UNIT_NAME = "NataRestServicePU";
#PersistenceContext(unitName = "NataRestServicePU")
protected EntityManager entityManager;
public MainDAO(Class<T> type){
clazz = type;
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
}
public void setClazz(Class<T> clazzToSet) {
this.clazz = clazzToSet;
}
#Override
public T read(int id){
try{
newEntityManager();
return entityManager.find(clazz,id);
}finally{
closeEntityManager();
}
}
protected void closeEntityManager(){
entityManager.close();
}
protected void newEntityManager(){
entityManager = factory.createEntityManager();
}
}

Declaring non-default JNDI connection for JPA access in Play for Scala

The following snippet works in Play for Scala:
class MyDAO #Inject() (jpaApi: JPAApi) {
#Transactional
def someMethod = {
jpaApi.withTransaction { // ....
In application.conf I defined db.default.jndiName=DefaultDS and jpa.default=defaultPersistenceUnit.
Now, I also need to define another JNDI connection db.another.jndiName=AnotherDS with jpa.another=anotherPersistenceUnit.
Where the persistence.xml is:
<persistence 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"
version="2.1">
<persistence-unit name="defaultPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<non-jta-data-source>DefaultDS</non-jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HANAColumnStoreDialect"/>
</properties>
</persistence-unit>
<persistence-unit name="anotherPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<non-jta-data-source>AnotherDS</non-jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HANAColumnStoreDialect"/>
</properties>
</persistence-unit>
</persistence>
How to inject AnotherDS in the application so it can be used with JPAApi?
You can specify multiple JPA configurations in application.conf:
db.default.jndiName=DefaultDS
... // other configuration for db.default
jpa.default=defaultPersistenceUnit
db.another.jndiName=AnotherDS
... // other configuration for db.another
jpa.another=anotherPersistenceUnit
In your DAO, inject JPAApi as you're currently doing. Use JPAApi#em(String) to get the EntityManager for a specific persistence unit name:
class MyDAO #Inject() (jpaApi: JPAApi) {
def someMethodWithDefault = {
val em = jpaApi.em("default") // em is an EntityManager
jpaApi.withTransaction {
...
}
}
def someMethodWithAnother = {
val em = jpaApi.em("another") // em is an EntityManager
jpaApi.withTransaction {
...
}
}
Also, the #Transactional annotation is unnecessary if you're using JPAApi#withTransaction.

Large MIME attachment & SOAP

I have simple web service server which receive SOAP with MIME attachment, store it to the HashMap and send back message with this mime attachment:
Java 1.7.0_13-b20
Spring WS 2.1.3
MOXy implementation of JAXB (EclipseLink 2.4.1)
Glassfish 3.1.1
MIME attachment & SOAP
enabled SAAJ MimePull to save to the hard drive
based on Enabling large file transfers through SOAP with Spring WS, MTOM/XOP and JAXB2 and Spring WS "mtom" sample
tested by SoapUI
If I send Request with small attachment (<80MB) everything is OK but when I send Request with >80 MB attachment the DataHandler object is null. So it is not parsed from Request and not stored to the HashMap. Does not matter if I have enabled mimepull, if yes the large attachment is stored to the temporary folder on hard drive.
Enabled MimePull:
-Dsaaj.use.mimepull=true
-Djava.io.tmpdir=/path/to/tmpdir
Enlarged GlassFish Thread Pools:
"Max Thread Pool Size" from 5 to 32
"Min Thread Pool Size" from 2 to 16
ImageRequest.java
package sample.mtom.schema;
#XmlRootElement
#XmlType(propOrder = {"fileName", "data"})
public class ImageRequest {
protected String fileName;
protected DataHandler data;
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
#XmlMimeType("*/*")
public DataHandler getData() {
return data;
}
public void setData(DataHandler data) {
this.data = data;
}
}
ImageResponse.java
package sample.mtom.schema;
#XmlRootElement
#XmlType(propOrder = {"fileName", "data"})
public class ImageResponse {
// the same as ImageRequest
}
package-info.java
#XmlSchema(namespace = "http://www.example.org/Image",
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package sample.mtom.schema;
import javax.xml.bind.annotation.XmlSchema;
StubRepository.java
package sample.mtom.service;
public class StubRepository implements Repository {
private Map<String, DataHandler> files = new HashMap();
public DataHandler readFile(String name) throws IOException {
return files.get(name);
}
public void storeFile(String name, DataHandler file) throws IOException {
files.put(name, file);
}
}
ImageRepositoryEndpoint.java
package sample.mtom.ws;
#Endpoint
public class ImageRepositoryEndpoint {
private static Repository repository;
static {
repository = new StubRepository();
}
#PayloadRoot(localPart = "imageRequest", namespace = "http://www.example.org/Image")
#ResponsePayload
public ImageResponse handleRequest(#RequestPayload ImageRequest request) throws IOException {
repository.storeFile(request.getFileName(), request.getData());
ImageResponse response = new ImageResponse();
response.setFileName(request.getFileName());
response.setData(repository.readFile(request.getFileName()));
return response;
}
}
schema.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xmime="http://www.w3.org/2005/05/xmlmime"
targetNamespace="http://www.example.org/Image"
elementFormDefault="qualified">
<xsd:element name="imageRequest">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="fileName" type="xsd:string"/>
<xsd:element name="data" type="xsd:base64Binary" xmime:expectedContentTypes="*/*"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="imageResponse">
<!-- the same as imageRequest -->
</xsd:element>
</xsd:schema>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>MyCompany HR Holiday Service</display-name>
<servlet>
<servlet-name>spring-ws</servlet-name>
<servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring-ws</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
spring-ws-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:sws="http://www.springframework.org/schema/web-services"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/web-services http://www.springframework.org/schema/web-services/web-services-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="sample.mtom.ws"/>
<bean id="defaultMethodEndpointAdapter"
class="org.springframework.ws.server.endpoint.adapter.DefaultMethodEndpointAdapter">
<property name="methodArgumentResolvers" ref="marshallingPayloadMethodProcessor"/>
<property name="methodReturnValueHandlers" ref="marshallingPayloadMethodProcessor"/>
</bean>
<bean id="marshallingPayloadMethodProcessor"
class="org.springframework.ws.server.endpoint.adapter.method.MarshallingPayloadMethodProcessor">
<constructor-arg ref="jaxb2Marshaller"/>
</bean>
<bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="packagesToScan" value="sample.mtom.schema"/>
<property name="mtomEnabled" value="true"/>
</bean>
<sws:dynamic-wsdl id="image"
portTypeName="ImageResource"
locationUri="/">
<sws:xsd location="/WEB-INF/schema.xsd"/>
</sws:dynamic-wsdl>
</beans>

Cannot use an EntityTransaction while using JTA

I'm receiving this error:
javax.servlet.ServletException: java.lang.IllegalStateException:
Exception Description: Cannot use an EntityTransaction while using JTA.
While trying to use JPA and JAVAEE, Glassfish.
My persistence.xml file is as follow:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" 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">
<persistence-unit name="acmeauction">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/MySQLJDBCResource</jta-data-source>
<class>it.uniroma3.acme.auction.model.User</class>
<class>it.uniroma3.acme.auction.model.Auction</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/acmeauction"/>
<property name="javax.persistence.jdbc.user" value="user"/>
<property name="javax.persistence.jdbc.password" value="password"/>
</properties>
</persistence-unit>
</persistence>
What i'm trying to do is to persist an object (User), in this way:
#ManagedBean
public class UserRepository implements Serializable{
#PersistenceUnit
EntityManagerFactory emf;
#PersistenceContext
private EntityManager em;
private static UserRepository instance;
/**
* Gives back the singleton UserRepository singleton.
*/
public static UserRepository getInstance() {
if (instance==null) {
instance = new UserRepository();
}
return instance;
}
private UserRepository() {
emf = Persistence.createEntityManagerFactory("acmeauction");
em = emf.createEntityManager();
}
/**
* Save and persist a new User.
*/
public void save(User user) {
em.getTransaction().begin();
em.persist(user);
em.getTransaction().commit();
}
}
While if it try to use UserRepository from a simple Java application, it works correctly.
Thanks in advance,
AN
You are not supposed to use em.getTransaction().begin(); nor em.getTransaction().commit();, these instructions are to be used with RESOURCE_LOCAL transaction type.
In your case the transaction is managed by the container, in the first use of the EntitiyManager in your method, the container checks whether there is an active transaction or not, if there is no transaction active then it creates one, and when the method call ends, the transaction is committed by the container. So, at the end your method should look like this:
public void save(User user) {
em.persist(user);
}
The container takes care of the transaction, that is JTA.
As the error states, if you are using JTA for transactions, you need to use JTA.
Either use JTA UserTransaction to begin/commit the transaction, or use a RESOURCE_LOCAL persistence unit and non-jta DataSource.
See,
http://en.wikibooks.org/wiki/Java_Persistence/Transactions

Why could <exclude-unlisted-classes>false</exclude-unlisted-classes> fail to work?

With this persistence.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<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_1_0.xsd"
version="1.0">
<persistence-unit name="ODP_Server_Test"
transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<!-- <non-jta-data-source>osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=jdbc/ODPServerDataSource)</non-jta-data-source> -->
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver" />
<property name="javax.persistence.jdbc.url" value="jdbc:derby:memory:unit-testing;create=true" />
<property name="javax.persistence.jdbc.user" value="" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
<property name="eclipselink.target-database" value="DERBY" />
</properties>
</persistence-unit>
</persistence>
and a simple test:
public class RepositoryTest {
private static Logger logger = LoggerFactory
.getLogger(RepositoryTest.class);
private static EntityManagerFactory emf;
private EntityManager em;
private RepositoryImpl repo = new RepositoryImpl();
#BeforeClass
public static void setUp() {
try {
logger.info("Starting in-memory DB for unit tests");
#SuppressWarnings("unused")
Class<?> cls = org.apache.derby.jdbc.EmbeddedDriver.class;
DriverManager.getConnection(
"jdbc:derby:memory:unit-testing;create=true").close();
} catch (Exception ex) {
ex.printStackTrace();
fail("Exception during database startup.");
}
try {
logger.info("Building JPA EntityManager for unit tests");
emf = Persistence.createEntityManagerFactory("ODP_Server_Test");
} catch (Exception ex) {
ex.printStackTrace();
fail("Exception during JPA EntityManager instantiation.");
}
}
#AfterClass
public static void tearDown() throws SQLException {
logger.info("Shutting down JPA");
if (emf != null) {
emf.close();
}
try {
DriverManager.getConnection(
"jdbc:derby:memory:unit-testing;drop=true").close();
} catch (SQLException ex) {
if (ex.getSQLState().equals("08006")) {
logger.info("DB shut down");
} else {
throw ex;
}
}
fail("DB didn't shut down");
}
#Before
public void setEM() {
em = emf.createEntityManager();
repo.setEntityManager(em);
}
#After
public void flushEM() {
if (em != null) {
em.flush();
em.close();
em = null;
}
}
#Test
public void noBlocksInEmptyDB() {
assertThat(repo.findFunBlock(1), is((FunctionalBlock) null));
}
}
I get
[EL Warning]: 2012-04-17 15:08:18.476--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
After replacing <exclude-unlisted-classes>false</exclude-unlisted-classes> with a lot of <class> elements, the problem can be fixed, but I'd prefer not to have to remember to edit persistence.xml every time I need to add a new entity or remove an old one. Why doesn't the version with <exclude-unlisted-classes> work?
I had faced similar situation
If I generate JPA metamodel, copy paste it in correct pacakge and check it in to svn, and disable metamodel generation, all junit tests were fine
if i generate metamodel with every build, at junit time - embedded glassfish will find all ejb and metamodel fine, but non ejb junit will fail
I had to do this in my src/test/resources/META-INF/persistence.xml
<persistence-unit name="test-xxx" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<jar-file>file:../classes</jar-file>
<shared-cache-mode>ALL</shared-cache-mode>
<properties>
<property name="eclipselink.target-database" value="org.eclipse.persistence.platform.database.oracle.Oracle11Platform"/>
<property name="eclipselink.logging.timestamp" value="true"/>
<property name="eclipselink.logging.thread" value="true"/>
<property name="eclipselink.logging.level" value="FINE"/>
<property name="eclipselink.logging.parameters" value="true"/>
<property name="eclipselink.logging.logger" value="JavaLogger"/>
<property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:#localhost:1521:xxx"/>
<property name="javax.persistence.jdbc.password" value="xxx"/>
<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
<property name="javax.persistence.jdbc.user" value="xxx"/>
</properties>
</persistence-unit>