Najm Alzorqah
Najm Alzorqah

Reputation: 1

Object: najm.Customer[ customerid=null ] is not a known Entity type. but entity specified in persistence.xml

I have tried Multiple ways in connecting to a database using JPA but all the ways have been faild. I am using Jakarta EE. So please give me a full step by step guide in how to connect it and what are the required jar files that I should install and provide the link to them please. And Please tell me what type of project should i create to pervent further errors java with ant or java with maven. I am also do not mind if the steps are descriped using NetBeans IDE or Eclips IDE.

Note: I'm using Apatche Tomcat 11.0 and 21 JDK. Thanks a lot.

my pom.xml file is :

<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>com.najmladeen</groupId>
    <artifactId>JPA-Maven-Test</artifactId>
    <version>1</version>
    <packaging>war</packaging>
    <name>JPA-Maven-Test-1</name>
    
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <jakartaee>11.0.0-M1</jakartaee>
    </properties>
    
    <dependencies>
        <dependency>
            <groupId>jakarta.platform</groupId>
            <artifactId>jakarta.jakartaee-api</artifactId>
            <version>${jakartaee}</version>
            <scope>provided</scope>
        </dependency>
        
    <!-- Jakarta Persistence API -->
    <dependency>
        <groupId>jakarta.persistence</groupId>
        <artifactId>jakarta.persistence-api</artifactId>
        <version>3.1.0</version>
    </dependency>

    <!-- SQLite JDBC Driver -->
    <dependency>
        <groupId>org.xerial</groupId>
        <artifactId>sqlite-jdbc</artifactId>
        <version>3.36.0.3</version>
    </dependency>

    <!-- EclipseLink JPA Implementation -->
    <dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>org.eclipse.persistence.jpa</artifactId>
        <version>3.0.0</version>
    </dependency>

    <!-- Jakarta Servlet API -->
    <dependency>
        <groupId>jakarta.servlet</groupId>
        <artifactId>jakarta.servlet-api</artifactId>
        <version>5.0.0</version>
        <scope>provided</scope>
    </dependency>


        
        
    </dependencies>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.12.1</version>
                <configuration>
                    <source>17</source>
                    <target>17</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.4.0</version>
            </plugin>
        </plugins>
    </build>
</project>

I have connected to a sqlite datbase , and created this TestServlet servlet also I created the Entity from tables java calss called Customer , I am also providing the persistence file
and this Error message shows in my Browser :

An error occurred: Object: najm.Customer[ customerid=null ] is not a known Entity type.
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import najm.Customer;

import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.EntityManager;
import jakarta.persistence.Persistence;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * Servlet implementation class TestServlet
 */
@WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private static final EntityManagerFactory ENTITY_MANAGER_FACTORY = 
            Persistence.createEntityManagerFactory("najm");

    public TestServlet() {
        super();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter pw = response.getWriter();

        EntityManager entityManager = null;

        try {
            entityManager = ENTITY_MANAGER_FACTORY.createEntityManager();
            var transaction = entityManager.getTransaction();

            transaction.begin();

            // Creating and persisting a Customer entity
            Customer customer = new Customer();
            customer.setCustomerid(35);
            customer.setFirstname("Sarah");
            customer.setLastname("Polley");
            entityManager.persist(customer);

            transaction.commit();

            // Successful response
            pw.println("<html>");
            pw.println("<head><title>Success</title></head>");
            pw.println("<body>");
            pw.println("<h1>Record has been inserted successfully.</h1>");
            pw.println("</body>");
            pw.println("</html>");
        } catch (Exception ex) {
            if (entityManager != null && entityManager.getTransaction().isActive()) {
                entityManager.getTransaction().rollback();
            }
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            pw.println("<html>");
            pw.println("<head><title>Error</title></head>");
            pw.println("<body>");
            pw.println("<h1>An error occurred: " + ex.getMessage() + "</h1>");
            pw.println("</body>");
            pw.println("</html>");
        } finally {
            if (entityManager != null) {
                entityManager.close();
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    public void destroy() {
        if (ENTITY_MANAGER_FACTORY != null && ENTITY_MANAGER_FACTORY.isOpen()) {
            ENTITY_MANAGER_FACTORY.close();
        }
    }
}
/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package najm;

import java.io.Serializable;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.NamedQueries;
import jakarta.persistence.NamedQuery;
import jakarta.persistence.Table;

/**
 *
 * @author Najmaldeen
 */
@Entity
@Table(name = "Customer")
@NamedQueries({
    @NamedQuery(name = "Customer.findAll", query = "SELECT c FROM Customer c"),
    @NamedQuery(name = "Customer.findByCustomerid", query = "SELECT c FROM Customer c WHERE c.customerid = :customerid"),
    @NamedQuery(name = "Customer.findByFirstname", query = "SELECT c FROM Customer c WHERE c.firstname = :firstname"),
    @NamedQuery(name = "Customer.findByLastname", query = "SELECT c FROM Customer c WHERE c.lastname = :lastname")})
public class Customer implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "customerid")
    private Integer customerid;
    @Column(name = "firstname")
    private String firstname;
    @Column(name = "lastname")
    private String lastname;

    public Customer() {
    }

    public Customer(Integer customerid) {
        this.customerid = customerid;
    }

    public Integer getCustomerid() {
        return customerid;
    }

    public void setCustomerid(Integer customerid) {
        this.customerid = customerid;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (customerid != null ? customerid.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 Customer)) {
            return false;
        }
        Customer other = (Customer) object;
        if ((this.customerid == null && other.customerid != null) || (this.customerid != null && !this.customerid.equals(other.customerid))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "najm.Customer[ customerid=" + customerid + " ]";
    }
    
}
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="3.1" 
    xmlns="https://jakarta.ee/xml/ns/persistence" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_1.xsd">

  <persistence-unit name="najm" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>najm.Customer</class>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
      <!-- SQLite JDBC URL pointing to your local SQLite database -->
      <property name="jakarta.persistence.jdbc.url" value="jdbc:sqlite:C:\\Users\\najma\\OneDrive\\Desktop\\test.db"/>
      
      <!-- User credentials for SQLite (empty since SQLite does not require user/password) -->
      <property name="jakarta.persistence.jdbc.user" value=""/>
      <property name="jakarta.persistence.jdbc.password" value=""/>
      
      <!-- Define the JDBC driver for SQLite -->
      <property name="jakarta.persistence.jdbc.driver" value="org.sqlite.JDBC"/>
      
      <!-- Schema generation action (drop and recreate the schema) -->
      <property name="jakarta.persistence.schema-generation.database.action" value="drop-and-create"/>
      
      <!-- EclipseLink specific logging settings -->
      <property name="eclipselink.logging.level" value="FINE"/>
      <property name="eclipselink.logging.parameters" value="true"/>
    </properties>
  </persistence-unit>
</persistence>

Upvotes: 0

Views: 15

Answers (0)

Related Questions