I'm working on REST server and learning EJB\hibernate at the same time. When service call DAO I faced with an issue that it can not find my persistence unit.
#Stateless
public class HotelDAO {
#PersistenceContext(unitName = Constants.PERSISTENCE_UNIT)
private EntityManager em;
public List<HotelsEntity> getAll() {
// TODO complete me
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<HotelsEntity> criteria = builder.createQuery(HotelsEntity.class);
Root<HotelsEntity> root = criteria.from(HotelsEntity.class);
criteria.select(root);
TypedQuery<HotelsEntity> resultQuery = em.createQuery(criteria);
return resultQuery.getResultList();
}
}
In this case I get "Unable to retrieve EntityManagerFactory for unitName persistenceUnit"
Then I try this:
#Stateless
public class HotelDAO {
public List<HotelsEntity> getAll() {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistenceUnit");
EntityManager em = emf.createEntityManager();
// TODO complete me
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<HotelsEntity> criteria = builder.createQuery(HotelsEntity.class);
Root<HotelsEntity> root = criteria.from(HotelsEntity.class);
criteria.select(root);
TypedQuery<HotelsEntity> resultQuery = em.createQuery(criteria);
return resultQuery.getResultList();
}
}
In this case I get "No Persistence provider for EntityManager named persistenceUnit".
I checl similar issues at the stackoverflow:
persitence.xml under META-INF
DAO is injected into EJB
provider is mentioned in persistence.xml
I don't use Spring
Do you have any gueses?
<?xml version="1.0" encoding="UTF-8"?>
<persistence-unit name="persistenceUnit" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>jdbc/HospitalityDataSource</jta-data-source>
<class>com.example.model.AmmenitiesEntity</class>
<class>com.example.model.HotelPropertyEntity</class>
<class>com.example.model.HotelsEntity</class>
<class>com.example.model.InventoriesEntity</class>
<class>com.example.model.ReservationEntity</class>
<class>com.example.model.RoomEntity</class>
<class>com.example.model.RoomPropertyEntity</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/mydb"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.username" value="dbroot"/>
<property name="hibernate.connection.password" value="password"/>
</properties>
</persistence-unit>
pom.xml
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>annotations-api</artifactId>
<version>6.0.29</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.ejb</artifactId>
<version>3.1</version>
</dependency>
</dependencies>
If I'm not wrong, I think persistence.xml must be in src/main/resources/META-INF/persistence.xml
Related
My application originally used only Hibernate and everything worked fine, but with Spring i'm getting an exception. It feels like Spring causes different behavior for Hibernate.
So with Spring & Hibernate i get this exception trace:
Stack trace photo_1
Stack trace photo_2
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/IndexingAndSearching?
serverTimezone=UTC</property>
<property name="connection.CharSet">utf8</property>
<property name="connection.characterEncoding">utf8</property>
<property name="connection.useUnicode">true</property>
<property name="connection.username">test</property>
<property name="connection.password">test</property>
<property name="connection.pool_size">20</property>
<property name="dialect">org.hibernate.dialect.MySQL57Dialect</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">false</property>
<property name="hbm2ddl.auto">validate</property>
</session-factory>
</hibernate-configuration>
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-
4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>IndexingAndSearching</groupId>
<artifactId>IndexingAndSearching</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- Lucene -->
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-core</artifactId>
<version>9.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-analyzers-common</artifactId>
<version>8.11.1</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-queryparser</artifactId>
<version>9.0.0</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.9.0</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.7.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.14.3</version>
</dependency>
<!-- Logger -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.36</version>
</dependency>
<!-- JUnit -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.1-jre</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
All of my DAO methods for mysql are written with sessionFactory
Links - my only table
#Entity(name = "links")
#Table(name = "links")
#DynamicInsert // To set initial value of fields, otherwise doesn't work
public class Links implements Serializable {
#Id
private String link;
#Enumerated
#Column(columnDefinition = "smallint")
private Status status;
#Version
private int version;
private int depth;
private long owner;
public Links() {
} // hibernate requirement
public Links(String link, Status status, int depth) throws URISyntaxException {
assert depth >= 0;
assert !LinkParser.isBlank(link);
this.link = link;
this.status = status;
this.depth = depth;
this.owner = 0;
}
public String getLink() {
return link;
}
private void setLink(String link) {
this.link = link;
}
public int getVersion() {
return version;
}
private void setVersion(int version) {
this.version = version;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public int getDepth() {
return depth;
}
private void setDepth(int depth) {
this.depth = depth;
}
public long getOwner() {
return owner;
}
public void setOwner(long owner) {
assert owner >= 0;
this.owner = owner;
}
application.properties
server.port=8080
server.servlet.context-path=/webcrawler
Only difference is when i start application with Spring, i dont get these exceptions when i dont use Spring.
I think the issue is from the fact that you setter is private and should be public
private void setLink(String link) {
this.link = link;
}
Should be
public void setLink(String link) {
this.link = link;
}
Same for setVersion and setDepth
I found out, I commented these maven dependencies
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-devtools</artifactId>-->
<!-- <scope>runtime</scope>-->
<!-- <optional>true</optional>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-test</artifactId>-->
<!-- <scope>test</scope>-->
<!-- </dependency>-->
And everything started working... I guess devtools are the reason, dont want to check, I tried so many other stuff, and this is the reason...
I have a microservice which is a scheduler. I get a timing job via REST json.
I followed some tutorials on how to add the persistence.xml but it doesn't seem to work. I don't get any failure messages but the NullpointerException from the EntityManager.
It doesn't create the tables etc. so i think there is a problem with adding the persistence.xml too?
There is no problem in connecting to the datasource. i tested it and it seems to work properly.
SchedulerMain:
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.ClassLoaderAsset;
import org.wildfly.swarm.Swarm;
import org.wildfly.swarm.container.Container;
import org.wildfly.swarm.datasources.DatasourceArchive;
import org.wildfly.swarm.jaxrs.JAXRSArchive;
public class SchedulerMain {
public static void main(String[] args) {
try {
Container container = new Container();
container.start();
container.deploy(Swarm.artifact("mysql:mysql-connector-java", "mysql"));
deployApp(container);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void deployApp(Container container) throws Exception {
JAXRSArchive app = ShrinkWrap.create(JAXRSArchive.class);
app.as(DatasourceArchive.class).dataSource("Scheduler", (ds) -> {
ds.connectionUrl("jdbc:mysql://localhost:3306/scheduler");
ds.driverName("mysql");
ds.userName("root");
ds.password("");
});
app.addAsWebInfResource(new ClassLoaderAsset("META-INF/persistence.xml", SchedulerMain.class.getClassLoader()),
"classes/META-INF/persistence.xml");
app.addAsLibrary(container.createDefaultDeployment());
app.addAllDependencies();
container.deploy(app);
}
}
ScheduleRESTResource:
#ApplicationScoped
#Path("/schedule")
public class ScheduleRESTResource {
#Inject
private SchedulerController schedulerController;
#Inject
private ScheduleBean scheduleBean;
#POST
#Path("/job")
#Consumes(MediaType.APPLICATION_JSON)
public void schedule(MySchedule schedule) throws IOException {
List<MySchedule> schedules = scheduleBean.getAllSchedules();
System.out.println(schedules.toString());
schedulerController.buildSchedule(schedule);
}
}
ScheduleBean:
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import de.fszm.scheduler.entities.MySchedule;
#Stateless
public class ScheduleBean {
#PersistenceContext(unitName = "Scheduler")
private EntityManager em;
public List<MySchedule> getAllSchedules() {
System.out.println("getAllSchedules");
List<MySchedule> schedules = new ArrayList<>();
if (em != null) {
schedules = em.createNamedQuery("Schedule.getAllSchedules", MySchedule.class).getResultList();
} else {
System.out.println("em is null");
}
return schedules;
}
}
persistence.xml:
<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="Scheduler" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:jboss/datasources/Scheduler</jta-data-source>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/scheduler"/>
<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.archive.autodetection" value="class"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="drop-and-create"/>
</properties>
</persistence-unit>
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>...</groupId>
<artifactId>scheduler</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>scheduler</name>
<packaging>jar</packaging>
<properties>
<version.swarm>1.0.0.Beta6</version.swarm>
<version.mysql>5.1.6</version.mysql>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.wildfly.swarm</groupId>
<artifactId>bom</artifactId>
<version>${version.swarm}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.wildfly.swarm</groupId>
<artifactId>undertow</artifactId>
</dependency>
<dependency>
<groupId>org.wildfly.swarm</groupId>
<artifactId>jaxrs</artifactId>
</dependency>
<dependency>
<groupId>org.wildfly.swarm</groupId>
<artifactId>ejb</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.wildfly.swarm</groupId>
<artifactId>jaxrs-weld</artifactId>
</dependency>
<dependency>
<groupId>org.wildfly.swarm</groupId>
<artifactId>datasources</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${version.mysql}</version>
</dependency>
<!-- <dependency>
<groupId>org.wildfly.swarm</groupId>
<artifactId>wildfly-swarm-ejb</artifactId>
<version>1.0.0.Alpha5</version>
</dependency> -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.wildfly.swarm</groupId>
<artifactId>wildfly-swarm-plugin</artifactId>
<version>${version.swarm}</version>
<configuration>
</configuration>
<executions>
<execution>
<id>package</id>
<goals>
<goal>package</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
I've a problem with connection to mysql. This is my code:
Dependencies:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.12</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Apache Database Connection Pool -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.10.Final</version>
</dependency>
<!-- MySQL JDBC Driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
</dependencies>
Context:
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<context:component-scan base-package="com.packt.app" />
<bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<property name="resourceLoaderPath" value="/WEB-INF/view/"/>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
<property name="cache" value="true"/>
<property name="prefix" value=""/>
<property name="suffix" value=".html"/>
<property name="exposeSpringMacroHelpers" value="true"/>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://ADMIN-PC:3306/data"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="/WEB-INF/hibernate.cfg.xml" />
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="testDAO" class="com.packt.app.DAO.Impl.TestDAOImpl">
<constructor-arg>
<ref bean="sessionFactory" />
</constructor-arg>
</bean>
Controller:
#Controller
#RequestMapping("/tests")
public class TestController {
#Autowired
TestService testService;
#RequestMapping("/testslist.json")
public #ResponseBody List<Test> getTestList() {
return testService.getTests();
}
#RequestMapping("/layout")
public String getTestPartialPage(ModelMap modelMap) {
return "tests/layout";
}
}
Model:
#Entity
#Table(name = "test")
public class Test{
#Id
#GeneratedValue
#Column(name = "id")
private int id;
#Column(name = "name")
private String name;
///gettters and setters
}
Impl:
#Repository
public class TestDAOImpl implements TestDAO {
#Autowired
private SessionFactory sessionFactory;
public TestDAOImpl() {
}
public TestDAOImpl(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
#Transactional
public List<Test> getTests() {
#SuppressWarnings("unchecked")
List<Test> tests = (List<Test>) sessionFactory.getCurrentSession()
.createCriteria(Test.class)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
return tests;
}
}
Angular Controller:
var TestsController = function($scope, $http) {
$scope.test = {};
$scope.editMode = false;
$scope.fetchTestList = function() {
$http.get('tests/testslist.json').success(function(testList){
$scope.tests = testList;
});
};
$scope.resetTestForm = function() {
$scope.resetError();
$scope.test = {};
$scope.editMode = false;
};
$scope.resetError = function() {
$scope.error = false;
$scope.errorMessage = '';
};
$scope.setError = function(message) {
$scope.error = true;
$scope.errorMessage = message;
};
$scope.fetchTestList()();
$scope.predicate = 'id';
};
Hibernate config:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping class="com.packt.app.model.Test"/>
</session-factory>
</hibernate-configuration>
Application runs without error, even when MySql Server off. In html view show me that list count "getTests" is 0. It looks like application not connection with MySQL Server. Whats wrong? Please help me.
The dialect in hibernate configuratiin is missing a L
Should be mysqlDialect i reckon.
I am creating a J2EE WebAPP with JSF Glassfish 4 and Eclipse
The weird thing is, I am doing the same things in two different applications anwhat works in one, leads to a NullPointerException in the other.
My ManagedBean is:
#ManagedBean(name = "showEntriesBean", eager = true)
#RequestScoped
public class ShowEntriesBean {
#EJB
EntryEAO eao;
public List<Entry> getEntries() {
return eao.getEntries();
}
EntriesEAO is:
#Stateless
#LocalBean
public class EntryEAO {
#PersistenceContext(unitName = "LBBBankingWeb")
EntityManager em;
public final List<Entry> getEntries() {
// This Line is leading to the NullPointerException an em is null
final TypedQuery<Entry> query = em.createQuery("select r from " + Entry.class.getName() + " r order by r.valutadate", Entry.class);
List<Entry> entries = query.getResultList();
return entries;
}
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="LBBBankingWeb">
<jta-data-source>jdbc/lbb</jta-data-source>
<class>de.docfaust.lbbweb.entity.Entry</class>
<class>de.docfaust.lbbweb.entity.Rule</class>
<class>de.docfaust.lbbweb.entity.Blockedrecipient</class>
<properties>
<property name="eclipselink.logging.level" value="FINE" />
</properties>
</persistence-unit>
</persistence>
When I put the getEntries() code directly in the ManagedBean it works. The configuration of the persistence thus seems to be correct, so I think it's an injection problem.
I have read the many questions here dealing with #PersistenceContext and CDI and some are about the right configuration of beans.xml.
I don't actually have a beans.xml but it's interesting that
in my other Webapp I don't have one either and it works;
other injections like the one of the EntryEAO do work.
Dependencies of POM
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0</version>
</dependency>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
Thank you for help
Finally found the answer:
It was in the EAO
public final List<Entry> getEntries() {
final TypedQuery<Entry> query = em.createQuery("select r from " + Entry.class.getName() + " r order by r.valutadate", Entry.class);
List<Entry> entries = query.getResultList();
return entries;
}
With removing the "final" modifier everything worked fine
public List<Entry> getEntries() {
TypedQuery<Entry> query = em.createQuery("select r from " + Entry.class.getName() + " r order by r.valutadate", Entry.class);
List<Entry> entries = query.getResultList();
return entries;
}
Message.java
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
#Entity
#Table(name="MESSAGES")
#Cache(region = "messages", usage = CacheConcurrencyStrategy.READ_WRITE)
public class Message {
Message(){
}
Message(String message){
message_text=message;
}
#Id #GeneratedValue
#Column(name="MESSAGE_ID")
public Long id;
#Column(name="MESSAGE_TEXT")
public String message_text;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMessage_text() {
return message_text;
}
public void setMessage_text(String message_text) {
this.message_text = message_text;
}
}
Ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<defaultCache eternal="true" maxElementsInMemory="100" overflowToDisk="false" />
<cache name="messages" maxElementsInMemory="10" eternal="true" overflowToDisk="false" />
</ehcache>
persistence.xml
<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="annotation">
<properties>
<property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver"/>
<property name="hibernate.connection.url" value="jdbc:oracle:thin:#ebiz-dev-db-esb:1521:esbd"/>
<property name="hibernate.connection.username" value="CUST_INFO"/>
<property name="hibernate.connection.password" value="POUND987"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle9Dialect"/>
<property name="hibernate.c3p0.min_size" value="5"/>
<property name="hibernate.c3p0.max_size" value="20"/>
<property name="hibernate.c3p0.timeout" value="300"/>
<property name="hibernate.c3p0.max_statements" value="50"/>
<property name="hibernate.c3p0.idle_test_period" value="3000"/>
<property name="show_sql" value="true"/>
<property name="format_sql" value="true"/>
<property name="hibernate.cache.region.factory_class" value="net.sf.ehcache.hibernate.EhCacheRegionFactory"/>
<property name="hibernate.cache.use_query_cache" value="true"/>
<property name="hibernate.cache.use_second_level_cache" value="true"/>
<property name="hibernate.cache.provider_class" value="net.sf.ehcache.hibernate.EhCacheProvider" />
<property name="hibernate.cache.provider_configuration_file_resource_path" value="ehcache.xml" />
</properties>
</persistence-unit>
</persistence>
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>HibernateWithAnnotation</groupId>
<artifactId>HibernateWithAnnotation</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>HibernateWithAnnotation</name>
<repositories>
<repository>
<id>codelds</id>
<url>https://code.lds.org/nexus/content/groups/main-repo</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.5.1-Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.5.1-Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.5.1-Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
<!-- logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.6.1</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.4.5</version>
</dependency>
</dependencies>
</project>
TestAnnotation class
package com.annotation;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;
public class TestAnnotation {
public static void main(String args[]){
EntityManagerFactory factory=Persistence.createEntityManagerFactory("annotation");
EntityManager manager=factory.createEntityManager();
EntityTransaction transaction=manager.getTransaction();
transaction.begin();
manager.persist(new Message("My Entity Test One More Example New"));
transaction.commit();
System.out.println("First time calling Message Object");
getMessage(manager,23);
System.out.println("Second time calling Message Object");
getMessage(manager,23);
factory.close();
}
public static void getMessage(EntityManager manager,long id){
EntityTransaction transaction1=manager.getTransaction();
transaction1.begin();
Query q=manager.createQuery("from Message m where m.id="+id);
Message m=(Message)q.getSingleResult();
System.out.println(m.getMessage_text());
transaction1.commit();
}
}
My problem is: When I run this code from TestAnnotation class via main method I get the following error:
Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named annotation
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:32)
at com.annotation.TestAnnotation.main(TestAnnotation.java:10)
Your persistence-unit is incomplete. See the documentation.
Add <class>com.annotation.TestAnnotation</class> to your persistence-unit node in your persistence.xml file before the properties node.
You likely also need transaction-type="RESOURCE_LOCAL" on you persistence-unit node.
For example, my working version uses:
pom.xml:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.5.4-Final</version>
<scope>runtime</scope>
</dependency>
persistenct.xml:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="MyPU" transaction-type="RESOURCE_LOCAL">
<class>com.myentities.MyEntity</class>
<properties>
<property name="hibernate.cache.use_query_cache" value="false"/>
<property name="hibernate.cache.use_second_level_cache" value="false"/>
<!-- These lines can be used for debugging -->
<!--<property name="show_sql" value="true"/>-->
<!--<property name="format_sql" value="true"/>-->
</properties>
</persistence-unit>
</persistence>
My DAO class:
private EntityManager m_entityManagerFactory;
// initializer (this is costly, do only 1x on post construct)
m_entityManager = createEntityManagerFactory( jdbcDriverName, jdbcURL, dbUserName, dbPassword );
// when needed (less costly, can do 1x or whenever you need the entity manager)
EntityManager entityManager = m_entityManagerFactory.createEntityManager();
private EntityManagerFactory createEntityManagerFactory (
#NotNull final String jdbcDriverName,
#NotNull final String jdbcURL,
#NotNull final String dbUserName,
#NotNull final String dbPassword )
{
final Properties properties = new Properties();
properties.put( "hibernate.connection.driver_class", jdbcDriverName );
properties.put( "hibernate.connection.url", jdbcURL );
properties.put( "hibernate.connection.username", dbUserName );
properties.put( "hibernate.connection.password", dbPassword );
return Persistence.createEntityManagerFactory( "AlertProcessorPU", properties );
}