Cannot upload my Web Applicartion in Jboss7 EAP7 EAP - java

I must to test this web app, but when I try to deploy on JBoss 7 EAP this is the error, maybe I forgot something?
This is the exception that the application throws:
Cannot upload deployment: {"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"WebAppGuestbooks.war\".INSTALL" =>
"org.jboss.msc.service.StartException in service jboss.deployment.unit.\"WebAppGuestbooks.war\".INSTALL: WFLYSRV0153:
Failed to process phase INSTALL of deployment \"WebAppGuestbooks.war\" Caused by:
org.jboss.as.server.deployment.DeploymentUnitProcessingException: WFLYEE0041: Component class it.matteo.nesea.ejb.GuestDao for
component GuestDao has errors:
WFLYJPA0033: Can't find a persistence unit named null in deployment
\"WebAppGuestbooks.war\""},"WFLYCTL0180: Services with missing/unavailable dependencies" =>
["jboss.deployment.unit.\"WebAppGuestbooks.war\".weld.weldClassIntrospector is missing
[jboss.deployment.unit.\"WebAppGuestbooks.war\".beanmanager]","jboss.deployment.unit.\"WebAppGuestbooks.war\".batch.environment
is missing [jboss.deployment.unit.\"WebAppGuestbooks.war\".beanmanager]"]}
This is my persistence.xml:
<?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="GuestbookPU" transaction-type="JTA">
<class>it.matteo.nesea.dao.jpa</class>
<properties>
<property name="javax.persistence.jdbc.url" value="$objectdb/db/guests.odb"/>
<property name="javax.persistence.jdbc.user" value="admin"/>
<property name="javax.persistence.jdbc.password" value="admin"/>
</properties>
</persistence-unit>
</persistence>
this is the Ejb GuestDAO:
package it.matteo.nesea.ejb;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import it.matteo.nesea.dao.jpa.Guest;
#Stateless
public class GuestDao {
// Injected database connection:
#PersistenceContext private EntityManager em;
// Stores a new guest:
public void persist(Guest guest) {
em.persist(guest);
}
// Retrieves all the guests:
public List<Guest> getAllGuests() {
TypedQuery<Guest> query = em.createQuery(
"SELECT g FROM Guest g ORDER BY g.id", Guest.class);
return query.getResultList();
}
}
this is Jpa POJO Class Guest:
package it.matteo.nesea.dao.jpa;
import java.io.Serializable;
import java.sql.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Guest implements Serializable {
private static final long serialVersionUID = 1L;
// Persistent Fields:
#Id
#GeneratedValue
Long id;
private String name;
private Date signingDate;
// Constructors:
public Guest() {
}
public Guest(String name) {
this.name = name;
this.signingDate = new Date(System.currentTimeMillis());
}
// String Representation:
#Override
public String toString() {
return name + " (signed on " + signingDate + ")";
}
}
This is a Servlet GuestServlet:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import it.matteo.nesea.dao.jpa.Guest;
import it.matteo.nesea.ejb.GuestDao;
#WebServlet(name="GuestServlet", urlPatterns={"/guest"})
public class GuestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// Injected DAO EJB:
#EJB GuestDao guestDao;
#Override
protected void doGet(
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Display the list of guests:
request.setAttribute("guests", guestDao.getAllGuests());
request.getRequestDispatcher("/guest.jsp").forward(request, response);
}
#Override
protected void doPost(
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Handle a new guest:
String name = request.getParameter("name");
if (name != null)
guestDao.persist(new Guest(name));
// Display the list of guests:
doGet(request, response);
}
}
This is a JSP Page:
<%#page contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%#page import="java.util.*,it.matteo.nesea.dao.jpa.Guest"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>JPA Guest Book Web Application</title>
</head>
<body>
<form method="POST" action="guest">
Name: <input type="text" name="name" />
<input type="submit" value="Add" />
</form>
<hr><ol> <%
#SuppressWarnings("unchecked")
List<Guest> guests = (List<Guest>)request.getAttribute("guests");
if (guests != null) {
for (Guest guest : guests) { %>
<li> <%= guest %> </li> <%
}
} %>
</ol></hr>
</body>
This is the path of Project

Your persistence.xml file is in the wrong place. The JPA uses a convention to find your persistence.xml so you have put the file in the right place.
According to the Oracle docs:
The JAR file or directory whose META-INF directory contains persistence.xml is called the root of the persistence unit.
If you package the persistent unit as a set of classes in an EJB JAR file, persistence.xml should be put in the EJB JAR’s META-INF directory.
If you package the persistence unit as a set of classes in a WAR file, persistence.xml should be located in the WAR file’s WEB-INF/classes/META-INF directory.
In your case when the persistence.xml file is in src/META-INF/ (if you use MAVEN the path is src/resources/META-INF) its going to be packaged in your war in the WEB-INF/classes/META-INF folder, funcioning as the root of the persistence unit.

Related

Tomcat doesn't connect to db Error Status 500 java.lang.ClassNotFoundException

When I try to connect to the db I get a 500 error and closes my eclipse/tomcat. Does anyone know how could I fix it?
Confirm Servlet
package be.pxl.tafelboeker.servlets;
import be.pxl.tafelboeker.dao.BoekingDAO;
import be.pxl.tafelboeker.domain.Boeking;
import be.pxl.tafelboeker.services.BoekingService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
#WebServlet(value = "/Confirm", initParams = {
#WebInitParam(name = "ConfirmPage",
value = "/confirm.jsp") })
public class ConfirmServlet extends HttpServlet {
private String ConfirmPage;
private String geluktPage;
private String misluktPage;
private BoekingService service = new BoekingService();
#Override
public void init() throws ServletException {
// TODO Auto-generated method stub
super.init();
ConfirmPage = getInitParameter("ConfirmPage");
geluktPage ="gelukt.jsp";
misluktPage = "mislukt.jsp";
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Boeking bean = new Boeking();
HttpSession sess = request.getSession();
bean = (Boeking)sess.getAttribute("bean");
request.setAttribute("bean", bean);
request.getRequestDispatcher(ConfirmPage).forward(request,response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO STUDENT : boek tafel, toon gelukt.jsp indien de boeking gelukt is en toon mislukt.jsp indien de tafel niet geboekt kan worden
Boeking bean = new Boeking();
HttpSession sess = request.getSession();
bean = (Boeking)sess.getAttribute("bean");
BoekingDAO dao = new BoekingDAO("jdbc:mysql://localhost/survey", "root", "");
BoekingService serv = new BoekingService();
serv.setDao(dao);
if (serv.boekTafel(bean)) {
request.getRequestDispatcher(geluktPage).include(request,response);
} else {
request.getRequestDispatcher(misluktPage).include(request,response);
}
//Krijg een error bij het aanroepen van mijn Persistence krijg deze pas vandaag als ik mijn oefeningen van gister wil openen die werkte krijg ik het nu ook
//Dit is zeer vervelend. Kan nu niet testen of mijn query en de rest wel klopt.
//Heb mijn best gedaan om het zo goed mogelijk in te zullen
//Hetzelfde geld voor overzichtservlet & overzicht.jsp die ook dezelfde fout krijgen
}
}
Boeking Dao
package be.pxl.tafelboeker.dao;
import be.pxl.tafelboeker.domain.Boeking;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class BoekingDAO {
private String url;
private String user;
private String password;
EntityManagerFactory emf;
public BoekingDAO(String url, String user, String password) {
this.url = url;
this.user = user;
this.password = password;
}
public void setDriver(String driver)
throws ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
}
private EntityManager getEntityManager() {
emf = Persistence.createEntityManagerFactory("booking");
EntityManager em = emf.createEntityManager();
return em;
}
// TIP : Gebruik TemporalType.DATE voor je query parameter
public boolean isTafelBeschikbaar(LocalDate dag, int uur) {
EntityManager em = getEntityManager();
Query q1 = em.createQuery("select b from booking as b where (b.dag=?1 AND b.uur =?2) ");
q1.setParameter(1, dag);
q1.setParameter(2, uur);
if (q1.getMaxResults() == 0) {
return true;
} else {
return false;
}
}
public void boekTafel(Boeking bean) {
EntityManager em = getEntityManager();
em.persist(bean);
em.close();
emf.close();
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
DriverLoader
package be.pxl.tafelboeker.dao;
public class DriverLoader {
static{
System.out.print("loading database");
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("nope");
e.printStackTrace();
}
}
}
Boeking Service
package be.pxl.tafelboeker.services;
import be.pxl.tafelboeker.dao.BoekingDAO;
import be.pxl.tafelboeker.domain.Boeking;
import java.time.LocalDate;
import java.util.Date;
public class BoekingService {
private BoekingDAO dao;
public BoekingService(){
}
public BoekingDAO getDao() {
return dao;
}
public void setDao(BoekingDAO dao) {
this.dao = dao;
}
private boolean isTafelBeschikbaar(LocalDate dag, int uur){
return dao.isTafelBeschikbaar(dag, uur) ;
}
public boolean boekTafel(Boeking boeking){
LocalDate dag = boeking.getDag();
int uur = boeking.getUur();
if(isTafelBeschikbaar(dag, uur)){
dao.boekTafel(boeking);
return true;
}
return false;
}
}
pom
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>be.pxl</groupId>
<artifactId>HerexamensOef</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>HerexamensOef Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<finalName>HerexamensOef</finalName>
</build>
</project>
persistance
<?xml version="1.0" encoding="UTF-8"?>
<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="booking" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/booking" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="javax.persistence.schema-generation.database.action"
value="none" />
<!-- Hibernate specific -->
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
Error
HTTP Status 500 - Servlet execution threw an exception
type Exception report
message Servlet execution threw an exception
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Servlet execution threw an exception
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.NoClassDefFoundError: javax/persistence/Persistence
be.pxl.tafelboeker.dao.BoekingDAO.getEntityManager(BoekingDAO.java:35)
be.pxl.tafelboeker.dao.BoekingDAO.isTafelBeschikbaar(BoekingDAO.java:43)
be.pxl.tafelboeker.services.BoekingService.isTafelBeschikbaar(BoekingService.java:28)
be.pxl.tafelboeker.services.BoekingService.boekTafel(BoekingService.java:34)
be.pxl.tafelboeker.servlets.ConfirmServlet.doPost(ConfirmServlet.java:59)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache Tomcat/8.0.33 logs.
SQL of booking
-- phpMyAdmin SQL Dump
-- version 4.4.10
-- http://www.phpmyadmin.net
--
-
- Host: localhost
-- Generation Time: Jun 03, 2016 at 06:50 PM
-- Server version: 5.5.42
-- PHP Version: 7.0.0
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
--
-- Database: `boekingdb`
--
-- --------------------------------------------------------
--
-- Table structure for table `BOOKING`
--
CREATE TABLE `BOOKING` (
`id` bigint(20) NOT NULL,
`DAY` date DEFAULT NULL,
`NAME` varchar(255) DEFAULT NULL,
`CITY` varchar(255) DEFAULT NULL,
`STREET` varchar(255) DEFAULT NULL,
`HOUR` int(11) DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
--
-- Indexes for table `BOOKING`
--
ALTER TABLE `BOOKING`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `BOOKING`
--
ALTER TABLE `BOOKING`
MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=4;
Your persistence file use the JPA schema for the 2.1 version :
<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">
so you should use a matching hibernate version : min Hibernate 4.3.X.
I guess that you use Hibernate because of it in your persistence.xml
<property name="hibernate.show_sql" value="true" />
So if you want use JPA as interface, you should add this dependency in your pom.xml :
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.2.Final</version>
</dependency>
This dependency includes hibernate-jpa-2.1-api which contains the class javax.persistence.Persistence
else if you want to use Hibernate directly without JPA as interface, you could use this dependency (or + 4.3.X):
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.2.Final</version>
</dependency>
More details here : http://hibernate.org/orm/downloads/
You have to add the javax.persistence-api.jar as a dependency:
<!-- https://mvnrepository.com/artifact/javax.persistence/persistence-api -->
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0.2</version>
</dependency>

HTTP Status 500 - javax.servlet.ServletException: java.lang.NoClassDefFoundError: org/hibernate/Session [duplicate]

This question already has answers here:
How to add JAR libraries to WAR project without facing java.lang.ClassNotFoundException? Classpath vs Build Path vs /WEB-INF/lib
(5 answers)
Closed 7 years ago.
Here I am creating a simple Registration form using JSP and Hibernate in Eclipse Mars. And as I run a jsp page I am getting an exception:
HTTP Status 500 - javax.servlet.ServletException:
java.lang.NoClassDefFoundError: org/hibernate/Session.
Here I put required files and directory structure.
1)User.java
package com.nick.mypack;
public class User {
private int id;
private String name,password,email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
2)UserDao.java
package com.nick.mypack;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class UserDao {
public static int register(User u){
int i=0;
Session session=new Configuration().
configure().buildSessionFactory().openSession();
Transaction t=session.beginTransaction();
t.begin();
i=(Integer)session.save(u);
t.commit();
session.close();
return i;
}
}
3)index.jsp
<html>
<form action="register.jsp" method="post">
Name:<input type="text" name="name"/><br><br/>
Password:<input type="password" name="password"/><br><br/>
Email ID:<input type="text" name="email"/><br><br/>
<input type="submit" value="register"/>"
</form>
</html>
4)register.jsp
<%#page import="com.nick.mypack.UserDao" %>
<jsp:useBean id="obj" class="com.nick.mypack.User">
</jsp:useBean>
<jsp:setProperty property="*" name="obj"/>
<%
int i=UserDao.register(obj);
if(i>0)
out.print("You are successfully registered");
%>
Please help me to solve this.
Thanks in advance!
Well, your error is:
java.lang.NoClassDefFoundError: org/hibernate/Session.
This means that your container (Tomcat or whatever server you are using) cannot load the class. You are probably not packaging your deployment right.
You need the Hibernate jars in WEB-INF/lib. It looks empty here, so they are not on the classpath when your app is running.
Make sure that the configuration is correct
Configuration
Download Hibernate 5 from [here][1].
Extract the Required jars from the folder inside and add it to the build path in following hibernate-release-5.0.7.Final.zip\hibernate-release-5.0.7.Final\lib\required.
Make sure the following jars are added to the classpath (this should be in your lib folder in WebApp) of the project:
antlr-2.7.7.jar
commons-dbcp2-2.1.1.jar
dom4j-1.6.1.jar
geronimo-jta_1.1_spec-1.1.1.jar
hibernate-commons-annotations-5.0.1.Final.jar
hibernate-core-5.0.7.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
jandex-2.0.0.Final.jar
javassist-3.18.1-GA.jar
javax.servlet.jsp.jstl-api-1.2.1-sources.jar
jboss-logging-3.3.0.Final.jar
sqljdbc4-3.0.jar //or whatever database you use
hibernate-entitymanager-5.0.7.Final
HibernateUtil.java :
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}

openSession(), getCurrentSession(), beginTransaction(), lazy load

I have a simple java web application that receive some information from database and display that information in web browser. Hibernate is used to interact with database in servlets and jsp files. All work as I want, but I don't understand some things.
Database is simple - 2 tables: Question and Answer. Relationship between tables is one-to-many: one Question can have many Answers.
This is code of java classes Question and Answer:
Question.java
package app;
import java.util.Set;
public class Question {
Long id = null;
String text = "";
Set<Answer> answers = null;
public Question() {
}
public void setId(Long id) {
this.id = id;
}
public void setText(String text) {
this.text = text;
}
public void setAnswers(Set<Answer> answers) {
this.answers = answers;
}
public Long getId() {
return id;
}
public String getText() {
return text;
}
public Set<Answer> getAnswers() {
return answers;
}
}
Answer.java
package app;
public class Answer {
Long id = null;
String text = "";
Question question = null;
public Answer() {
}
public void setId(Long id) {
this.id = id;
}
public void setText(String text) {
this.text = text;
}
public void setQuestion(Question question) {
this.question = question;
}
public Long getId() {
return id;
}
public String getText() {
return text;
}
public Question getQuestion() {
return question;
}
}
And this is configuration of Hibernate:
hibernate.cfg.xml
<?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="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://localhost;databaseName=Test</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping resource="question.hbm.xml"/>
<mapping resource="answer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
question.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="app">
<class name="app.Question" table="Question">
<id column="id" name="id" type="java.lang.Long">
<generator class="native"/>
</id>
<property column="text" name="text" not-null="true" type="java.lang.String"/>
<set name="answers">
<key column="question_id"/>
<one-to-many class="app.Answer"/>
</set>
</class>
</hibernate-mapping>
answer.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="app">
<class name="app.Answer" table="Answer">
<id column="id" name="id" type="java.lang.Long">
<generator class="native"/>
</id>
<property column="text" name="text" not-null="true" type="java.lang.String"/>
<many-to-one class="app.Question" column="question_id" name="question" not-null="true"/>
</class>
</hibernate-mapping>
So in Question there is a collection of Answers. Because of this there would be a lazy load of Answers. I want to use Hibernate objects in my jsp files, so I use this technique: the filter is used to create a session, and this session is used in both servlet and coresponding jsp file.
This is code of that my filter:
HibernateFilter.java
package app;
import java.io.IOException;
import javax.servlet.*;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateFilter implements Filter {
private SessionFactory sessionFactory;
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
try {
sessionFactory.getCurrentSession().beginTransaction();
chain.doFilter(request, response);
sessionFactory.getCurrentSession().getTransaction().commit();
} catch (Exception ex) {
sessionFactory.getCurrentSession().getTransaction().rollback();
ex.printStackTrace();
}
}
public void init(FilterConfig filterConfig) throws ServletException {
sessionFactory = new Configuration().configure().buildSessionFactory();
}
public void destroy() {
}
}
There are two servlets and two coresponding jsp files in my application - first ones display question with ID = 1, second ones display all questions. This is code of this servlets, coresponding jsp files and configuration of tomcat:
GetOneQuestion.java
package app;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
public class GetOneQuestion extends HttpServlet {
#Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
try {
Session session = new Configuration().configure()
.buildSessionFactory().getCurrentSession();
session.beginTransaction();
Question question = (Question)session.load(Question.class, 1L);
//session.getTransaction().commit();
request.setAttribute("oneQuestion", question);
} catch (Exception ex) {
ex.printStackTrace();
request.setAttribute("oneQuestion", null);
}
RequestDispatcher view = request.getRequestDispatcher("/oneQuestion.jsp");
view.forward(request, response);
}
}
oneQuestion.jsp
<%#page import="app.Answer"%>
<%#page import="app.Question"%>
<html>
<body>
<%
Question question = (Question)request.getAttribute("oneQuestion");
out.print("<br>" + question.getText() + "<br><br>");
%>
</body>
</html>
GetAllQuestion.java
package app;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.List;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
public class GetAllQuestion extends HttpServlet {
#Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
try {
Session session = new Configuration().configure()
.buildSessionFactory().getCurrentSession();
session.beginTransaction();
Query query = session.createQuery("from Question");
List all = query.list();
request.setAttribute("allQuestion", all);
} catch (Exception ex) {
ex.printStackTrace();
request.setAttribute("allQuestion", null);
}
RequestDispatcher view = request.getRequestDispatcher("/allQuestion.jsp");
view.forward(request, response);
}
}
allQuestion.jsp
<%#page import="app.Answer"%>
<%#page import="app.Question"%>
<%#page import="java.util.List"%>
<html>
<body>
<%
List all = (List)request.getAttribute("allQuestion");
for (Object object : all) {
Question question = (Question)object;
out.print("<br>Question " + question.getId());
for (Answer answer : question.getAnswers()) {
out.print("<br>" + answer.getText() + "<br>");
}
}
%>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" 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/web-app_3_1.xsd">
<filter>
<filter-name>HibernateFilter</filter-name>
<filter-class>app.HibernateFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>getAllQuestion</servlet-name>
<servlet-class>app.GetAllQuestion</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getAllQuestion</servlet-name>
<url-pattern>/getAllQuestion</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>getOneQuestion</servlet-name>
<servlet-class>app.GetOneQuestion</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getOneQuestion</servlet-name>
<url-pattern>/getOneQuestion</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Question
1) Why I need to call "session.beginTransaction()" method in servlets even if I already call "session.beginTransaction()" in filter? If I call one servler from another I also have to call this method in second servlet? Or I have to call this method before every interaction with database?
2) I don't call "sessionFactory.getCurrentSession().openSession()" or "sessionFactory.getCurrentSession().getCurrentSession()" in filter but I call "sessionFactory.getCurrentSession().getCurrentSession()" in servlet and still obtain session which seem to be create in filter. How this can be?
3) If I uncomment line "session.getTransaction().commit();" in GetOneQuestion class from jsp file I receive LazyInitializationException: "could not initialize proxy - no Session" even if there is no lazy load in this jsp file because I don't use any Answer object there. What cause this Exception? Session must be open for any interaction with Hibernate object even if there is no lazy load?
You need to configure a session factory one time (!) on the application startup, not in an every servlet.
You need to close session in the filter after a transaction commit.
You don't need create a transaction in the servlet (or you don't need create a transaction in the filter).
You can store a session factory in the static field of the application initializer class and get current session from it in servlets.
About your questions
Because you do a mistake. You create a new session factory in the servlet.
You obtain a new session (because of your incorrect session factory creation). In the normal situation getCurrentSession() return a session bound to the current thread by ThreadLocal(Not always, It depends of configuration).
You have LazyInitializationException with question.getAnswers().

Jetty 9.3.6: No LoginService for org.eclipse.jetty.security.authentication.BasicAuthenticator

I am trying to provide HTTP BASIC authentication for my webapp running on Jetty 9.3.6. I followed the instructions in here and it appeared like my authentication mechanism should be based out of JAAS. But my auth fails for a No LoginService error (see details below).
I followed the instructions in here and ended up with this src/main/webapp/WEB-INF/web.xml in my gradle sources:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app
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/web-app_3_1.xsd"
metadata-complete="false"
version="3.1">
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>myRealm</realm-name>
</login-config>
</web-app>
And I had to also add a context descriptor which I place in src/main/webapp/myWebApp.xml (this unwraps in ${jetty.base}/webapp/ and the web.xml unwraps in ${jetty.base}/webapp/WEB-INF/ though they are unwrapped when I deploy this war even though I choose to extractWAR below):
<Configure id='wac' class="org.eclipse.jetty.webapp.WebAppContext">
<Set name="contextPath">/myWebApp</Set>
<Set name="war">/opt/jetty/someJettyBase/webapps/myWebApp.war</Set>
<Set name="extractWAR">true</Set>
<Set name="securityHandler">
<New class="org.eclipse.jetty.security.ConstraintSecurityHandler">
<Set name="loginService">
<New class="org.eclipse.jetty.jaas.JAASLoginService">
<Set name="name">myRealm</Set>
<Set name="loginModuleName">xyz</Set>
</New>
</Set>
</New>
</Set>
</Configure>
To tie the JAAS to my login module, I do this in ${jetty.base}/etc/login.conf in my jetty deployment:
xyz {
com.webapp.MyLoginService required debug=true;
};
And lastly, I added jaas as a service to jetty using
$ java -jar --add-to-startd=jaas
and confirmed that it worked (file in ${jetty.base}/startd/jaas.ini).
Unfortunately, when I start Jetty, I see that it has not correctly worked, as I see this:
19 Jan 2016 21:29:08.811 WARN org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:526) Failed startup of context o.e.j.w.WebAppContext#27c20538{/myWebApp,file:///tmp/jetty-0.0.0.0-443-myWebApp.war-_myWebApp-any-8865406277141986908.dir/webapp/,STARTING}{/myWebApp.war}
java.lang.IllegalStateException: No LoginService for org.eclipse.jetty.security.authentication.BasicAuthenticator#5762806e in org.eclipse.jetty.security.ConstraintSecurityHandler#17c386de
at org.eclipse.jetty.security.authentication.LoginAuthenticator.setConfiguration(LoginAuthenticator.java:76)
at org.eclipse.jetty.security.SecurityHandler.doStart(SecurityHandler.java:354)
at org.eclipse.jetty.security.ConstraintSecurityHandler.doStart(ConstraintSecurityHandler.java:448)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132)
at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:106)
at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
MyLoginService.java:
package com.webapp;
import javax.servlet.ServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.eclipse.jetty.security.LoginService;
import org.eclipse.jetty.security.IdentityService;
import org.eclipse.jetty.server.UserIdentity;
import org.eclipse.jetty.security.DefaultUserIdentity;
public class MyLoginService implements LoginService
{
private static final Logger log = LoggerFactory.getLogger (MyLoginService.class.getName ());
private IdentityService identityService;
public MyLoginService (IdentityService identityService)
{
this.identityService = identityService;
}
#Override
public String getName()
{
return "name";
}
#Override
public UserIdentity login(String username, Object credentials, ServletRequest request)
{
log.debug ("MyLoginService.login: username received {}", username);
return null;
}
#Override
public boolean validate(UserIdentity user)
{
return false;
}
#Override
public IdentityService getIdentityService()
{
return identityService;
}
#Override
public void setIdentityService(IdentityService service)
{
}
#Override
public void logout(UserIdentity user)
{
}
}
Any insights into this is deeply appreciated.
What am I missing?
Thanks!

java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName null

I'm new to JavaEE and currently learning JavaEE7. I have JavaEE7 installed and downloaded NetBeans 8.0.2 so I could follow allow with the Webinar published here:
https://www.youtube.com/watch?v=sCNslREYpD0&spfreload=10
This tutorial in the video uses JavaEE6 rather than JavaEE7.
I made it about 12 minutes into the Webinar before I encountered the java.lang.IllegalStateException mentioned in the title of my post. At 12:18 in the video, the presenter adds a #PersistenceUnit to the code, and then an EntityManagerFactory. Even though I have followed his tutorial very carefully, I'm having issues with persistence and keep getting the following Exception:
java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName null
at com.sun.enterprise.container.common.impl.EntityManagerFactoryWrapper.getDelegate(EntityManagerFactoryWrapper.java:103)
at com.sun.enterprise.container.common.impl.EntityManagerFactoryWrapper.createEntityManager(EntityManagerFactoryWrapper.java:114)
at org.glasssfish.samples.TestServlet.processRequest(TestServlet.java:79)
at org.glasssfish.samples.TestServlet.doGet(TestServlet.java:103)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
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:561)
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:565)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
at java.lang.Thread.run(Thread.java:745)
I have search StackOverflow and Google extensively, and the answer I keep coming across relates to the location of the persistence.xml file. I'm using NetBeans which automatically creates and places the persistence.xml file in a Configuration Files folder.
The project layout in NetBean 8.0.2 looks like the following:
Web Pages
WEB-INF
index.html
Source Packages
org.glassfish.samples
TestServlet.java
org.glassfish.samples.model
Friend.java
Libraries
JDK 1.8 (Default)
GlassFish Server 4.1
Configuration Files
MANIFEST.MF
persistence.xml
Here is Friend.java file that was automatically generated by NetBeans as part of the tutorial:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.glasssfish.samples.model;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author james
*/
#Entity
#Table(name = "FRIEND")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Friend.findAll", query = "SELECT f FROM Friend f"),
#NamedQuery(name = "Friend.findByName", query = "SELECT f FROM Friend f WHERE f.name = :name"),
#NamedQuery(name = "Friend.findByAge", query = "SELECT f FROM Friend f WHERE f.age = :age")})
public class Friend implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 30)
#Column(name = "NAME")
private String name;
#Column(name = "AGE")
private Integer age;
public Friend() {
}
public Friend(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
#Override
public int hashCode() {
int hash = 0;
hash += (name != null ? name.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Friend)) {
return false;
}
Friend other = (Friend) object;
if ((this.name == null && other.name != null) || (this.name != null && !this.name.equals(other.name))) {
return false;
}
return true;
}
#Override
public String toString() {
return "org.glasssfish.samples.model.Friend[ name=" + name + " ]";
}
}
Here is the TestServlet.java file:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.glasssfish.samples;
import java.io.IOException;
import java.io.PrintWriter;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.glasssfish.samples.model.Friend;
/**
*
* #author james
*/
#WebServlet(name = "TestServlet", urlPatterns = {"/TestServlet"})
public class TestServlet extends HttpServlet {
#PersistenceUnit
EntityManagerFactory emf;
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet TestServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet TestServlet at " + request.getContextPath() + "</h1>");
//
int count;
if (request.getSession().getAttribute("count") == null) {
count = 0;
} else {
count = (Integer)request.getSession().getAttribute("count");
}
request.getSession().setAttribute("count", ++count);
out.println("Accessed again: " + request.getSession().getAttribute("count"));
Friend f = (Friend)emf.createEntityManager().createNamedQuery("Friend.findAll").getResultList().get(0);
out.println("Friend name: " + f.getName());
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
And, of course, the seemingly infamous persistence.xml file that was automatically generated by NetBean 8.0.2:
<?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="JavaEE7WebinarPU" transaction-type="JTA">
<jta-data-source>jdbc/sample</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
</persistence-unit>
</persistence>
I tried a variety of things like:
injecting a PersistenceContext instead of a PersistenceUnit and getting an EntityManager directly from there instead of using an EntityManagerFactor (not sure if I did that correctly).
modifying my #PersistenceUnit to #PersistenceUnit(unitName="JavaEE7WebinarPU"). This didn't help much. It just changed my error from:
java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName null
to
java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName JavaEE7WebinarPU
I verified that my GlassFish server does, in fact, have a resource named jdbc/sample which is mapped to a pool named SamplePool. I also verified that my GlassFish server has a Connection pool named SamplePool. It is currently set as a javax.sql.DataSource resource type.
I was hoping someone with some more experience with JavaEE might be able to point out something obvious that I'm missing here. Or maybe something that has changed from JavaEE6 to JavaEE7 which may be the cause of my error.
Any help or suggestions would be greatly appreciated.
/
UPDATE: I just ran a Clean and Build in NetBeans and saw the following warning:
/
warning: Supported source version 'RELEASE_6' from annotation processor 'org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor' less than -source '1.8'`
I have JDK 1.8 installed (update 31), NetBeans 8.0.2, and GlassFish 4.1. Is this warning suggesting that eclipseLink won't work with JDK 1.8?
/
UPDATE #2: Ok, well this seems to be a very lame resolution. After trying to fix this for a couple of hours. I shut down my GlassFish server, Disconnected from my database, performed a 'Clean and Build', started everything back up again, and redeployed. Now everything seems to be working as I expect it to. I suppose something got a little wonky somewhere and only a 'clean' was able to resolve the issue. Ugh.
/
Apparently something in my build got a little funky. I shut down all my servers, did a Clean and Build and redeployed. Now, everything seems to be working.
Thanks all for your suggestions.
What I found missing in your persistence.xml is the provider. In your persistence-unit element add the following tag also
<provider> provider_name</provider>
check which provider you are using
You have specified entity manager in your post and you trying to access entity manager both are different please see
You should do like this
#PersistenceContext(name="entiyManager")
EntityManager entitymanager;
Also you need to initialized your entitymanager factory
James, I think it is a simple solution.
change from
#PersistenceUnit
to
#PersistenceUnit(unitName="JavaEE7WebinarPU")
also see https://docs.oracle.com/javaee/6/api/javax/persistence/PersistenceUnit.html
No problem buddy its very easy just add this in 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="JavaEE7WebinarPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/sample</jta-data-source>
<properties>
<property name="eclipselink.ddl-generation" value="create-tables"/>
</properties>
</persistence-unit>
</persistence>
You have an option at persistence class generated by netbeans to name your persistence unit. After naming it just do a clean and build and you will get your answer.

Categories