Как создать базу данных, используя jpa, jetty и dao - PullRequest
0 голосов
/ 10 сентября 2018

Я новичок в JPA, Jetty и Dao. Я использую PostgreSQL для своей базы данных.

почему я не могу сгенерировать сущности в базу данных после запуска моего проекта.

моя ошибка

java.lang.NullPointerException в com.inventory.aset.controller.UserServlet.doGet (UserServlet.java:110)

и мои сущности не генерируются в базу данных.

это мои пом файлы

это мой класс сущности

  @Entity
    @Table(name = "tbl_users", catalog = "myDb", schema = "", uniqueConstraints = {
        @UniqueConstraint(columnNames = {"username"})})
    @XmlRootElement
@NamedQueries({
    @NamedQuery(name = "EntityUsers.findAll", query = "SELECT u FROM EntityUsers u")
    , @NamedQuery(name = "EntityUsers.findByUserId", query = "SELECT u FROM EntityUsers u WHERE u.userId = :userId")
    , @NamedQuery(name = "EntityUsers.findByEmail", query = "SELECT u FROM EntityUsers u WHERE u.email = :email")
    , @NamedQuery(name = "EntityUsers.findByUsername", query = "SELECT u FROM EntityUsers u WHERE u.username = :username")
    , @NamedQuery(name = "EntityUsers.findByPassword", query = "SELECT u FROM EntityUsers u WHERE u.password = :password")
})
        public class EntityUsers implements Serializable {

            private static final long serialVersionUID = 1L;
            @Id
            @GeneratedValue(strategy = GenerationType.IDENTITY)
            @Basic(optional = false)
            @Column(name = "user_id", nullable = false)
            private Long userId;
           @Pattern(regexp = "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message = "Invalid email Address")
            @Basic(optional = false)
            @Column(name = "email", nullable = false, length = 120, unique = true)
            private String email;
            @Basic(optional = false)
            @Column(name = "username", nullable = false, length = 120)//, unique = true
            private String username;
            @Basic(optional = false)
            @Column(name = "password", nullable = false, length = 65)
            private String password;
        }

это моя настойчивость. 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="inventoryAsetPU" transaction-type="RESOURCE_LOCAL">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <non-jta-data-source>java:app/jdbc/dbinventory</non-jta-data-source>
        <class>com.inventory.aset.entity.users.EntityUsers</class>
        <exclude-unlisted-classes>false</exclude-unlisted-classes>
        <shared-cache-mode>NONE</shared-cache-mode>
        <properties>
            <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/myDb"/>
            <property name="javax.persistence.jdbc.user" value="<users>"/>
            <property name="javax.persistence.jdbc.password" value="<password>"/>
            <property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
        </properties>
    </persistence-unit>
</persistence>

это мой Дао

@Stateless
public class EntityUsersDao extends AbstractFacade<EntityUsers> implements EntityUsersLocal {

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

    public EntityUsersDao() {
        super(EntityUsers.class);
    }

    protected EntityManager EntityCategoriesDao() {
        return em;
    }

    @Override
    public void createUser(EntityUsers dataUser) {
        em.persist(dataUser);
    }

    @Override
    public void updateUser(EntityUsers dataUser) {
        em.merge(dataUser);
    }

    @Override
    public void deleteUser(EntityUsers dataUser) {
        em.merge(dataUser);
    }

    @Override
    public void removeUser(long paramLong) {
        em.remove(getUsers(paramLong));
    }

    @Override
    public EntityUsers getUsers(long userId) {
        return em.find(EntityUsers.class, userId);
    }

    @Override
    public List<EntityUsers> getAllUsers() {
        return em.createNamedQuery("EntityUsers.findAll").getResultList();
    }

    @Override
    public List<EntityUsers> findByUsername(String username) {
        return em.createQuery("SELECT u FROM EntityUsers u WHERE u.username =  \"" + username + "\"").getResultList();
    }

    @Override
    public EntityUsers find(Object paramObject) {
        return (EntityUsers) em.find(EntityUsers.class, paramObject);
    }

    @Override
    public int count() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    protected EntityManager getEntityManager() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

}

это мой код сервлета

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("Inside doGet");
    PrintWriter out = response.getWriter();
    try {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        Date now = new Date();
        String tgl = sdf.format(now);

        String searchField = request.getParameter("searchField");
        String searchString = request.getParameter("searchString");
        System.out.println("isi searchField: " + searchField);
        System.out.println("isi searchString: " + searchString);
        String status = request.getParameter("status");

        String rows = request.getParameter("rows");
        String page = request.getParameter("page");

        System.out.println("rows" + rows);
        System.out.println("page" + page);

        int totalPages = 0;
        int totalCount = 0;

        if (totalCount > 0) {
            if (totalCount % Integer.parseInt(rows) == 0) {
                totalPages = totalCount / Integer.parseInt(rows);
            } else {
                totalPages = totalCount / Integer.parseInt(rows) + 1;
            }
        } else {
            totalPages = 0;
        }

        Date d2 = sdf.parse(tgl);
        String relation = "";
        Date tanggalMasuk = null;
        Date tanggalGaransi = null;

        JSONArray jsonArray = new JSONArray();

        //This line error code//
        **List<EntityUsers> usersList = usersDao.getAllUsers();**

Я пробовал это много раз, но безуспешно. Пожалуйста, помогите!

...