简体   繁体   中英

How to persist object using Entity Manager and GenericDao Bean and Tomee

I m in the beginning with Java EJB. :) I have Dynamic web project in eclipse and I want to save object to mysql database. Don't understand why it is not working since i do not have exceptions in my console. I m using Apache Tomee server which i had installed in eclipse.

My Entity class:

package entities;
import static javax.persistence.GenerationType.IDENTITY;
import java.io.Serializable;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

@Entity
@Table(name="books")
public class Book implements Serializable{

private static final long serialVersionUID = -9009670426767476684L;

@Id 
@GeneratedValue   
private int id;

@Column(name="name")
private String name;

public Book(){        
}

public Book(String name) {
    super();
    this.name = name;
}


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;
}    
}

GenericDaoBean:

package beans;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

public abstract class GenericDaoBean<T, ID extends Serializable> implements GenericDaoLocal<T, ID> {

private Class<T> entityType;

@PersistenceContext(unitName = "facebook")
protected EntityManager em;

@SuppressWarnings("unchecked")
public GenericDaoBean() {
    entityType = (Class<T>) ((ParameterizedType) getClass()
            .getGenericSuperclass()).getActualTypeArguments()[0];
}

public Class<T> getEntityType() {
    return entityType;
}

public T findById(ID id) {
    T entity;
    entity = em.find(entityType, id);
    return entity;
}

@SuppressWarnings("unchecked")
public List<T> findAll() {
    Query q = em.createQuery("SELECT x FROM " + entityType.getSimpleName()
            + " x");
    List<T> result = q.getResultList();
    return result;
}

@SuppressWarnings("unchecked")
public List<T> findBy(String query) {
    Query q = em.createQuery(query);
    List<T> result = q.getResultList();
    return result;
}

public T persist(T entity) {
    em.persist(entity);
    return entity;
}

public T merge(T entity) {
    entity = em.merge(entity);
    return entity;
}

public void remove(T entity) {
    entity = em.merge(entity);
    em.remove(entity);
}

public void flush() {
    em.flush();
}

public void clear() {
    em.clear();
}

}

GenericDaoBeanLocal:

package beans;

import java.io.Serializable;
import java.util.List;

public interface GenericDaoLocal<T, ID extends Serializable> {

public Class<T> getEntityType();

public T findById(ID id);

public List<T> findAll();

public List<T> findBy(String query);

public T persist(T entity);

public T merge(T entity);

public void remove(T entity);

public void flush();

public void clear();

}

Conroller:

package controllers;

import java.io.IOException;
import java.util.Calendar;
import javax.ejb.EJB;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import beans.BookDaoLocal;
import entities.Book;

public class RegistrationController extends HttpServlet {
private static final long serialVersionUID = 381026218072249234L;

@EJB
private BookDaoLocal bookDao;

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    String name = req.getParameter("name");
    Book b = new Book();
    b.setName(name);
    bookDao.persist(b);

}
}

In WebContent under META_INF folder I have persistance.xml and file:

Persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.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_1_0.xsd">


<persistence-unit name="facebook" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<jta-data-source>facebook</jta-data-source>
<class>entities.Book</class>

<properties>
        <property name="openjpa.Log" value="DefaultLevel=WARN, Runtime=INFO, Tool=INFO, SQL=TRACE"/>

        <property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)"/>
        <property name="openjpa.jdbc.SchemaFactory" value="native(ForeignKeys=true)" />

        <property name="openjpa.jdbc.EagerFetchMode" value="join"/>
        <!--<property name ="openjpa.RuntimeUnenhancedClasses" value="unsupported" />-->
</properties>      

In my src I have jndi.properties file:

 java.naming.factory.initial=org.apache.openejb.client.RemoteInitialContextFactory
java.naming.provider.url=http://127.0.0.1:8080/tomee/ejb

In my console I have:

INFO: Server startup in 4161 ms
10092  facebook  INFO   [http-bio-8080-exec-7] openjpa.Runtime - Starting OpenJPA 2.4.0-nonfinal-1598334
11626  facebook  TRACE  [http-bio-8080-exec-7] openjpa.jdbc.SQL - <t 1249135181, conn 2120544240> executing prepstmnt 598104600 SELECT   SEQUENCE_SCHEMA, SEQUENCE_NAME FROM INFORMATION_SCHEMA.SYSTEM_SEQUENCES
11626  facebook  TRACE  [http-bio-8080-exec-7] openjpa.jdbc.SQL - <t 1249135181, conn 2120544240> [0 ms] spent
11645  facebook  TRACE  [http-bio-8080-exec-7] openjpa.jdbc.SQL - <t 1249135181, conn 2120544240> executing prepstmnt 726242714 SELECT SEQUENCE_SCHEMA, SEQUENCE_NAME FROM INFORMATION_SCHEMA.SYSTEM_SEQUENCES
11646  facebook  TRACE  [http-bio-8080-exec-7] openjpa.jdbc.SQL - <t 1249135181, conn 2120544240> [1 ms] spent
11794  facebook  TRACE  [http-bio-8080-exec-7] openjpa.jdbc.SQL - <t 1249135181, conn 811560660> executing prepstmnt 1999826151 SELECT SEQUENCE_VALUE FROM PUBLIC.OPENJPA_SEQUENCE_TABLE WHERE ID = ? [params=?]
11794  facebook  TRACE  [http-bio-8080-exec-7] openjpa.jdbc.SQL - <t 1249135181, conn 811560660> [0 ms] spent
11795  facebook  TRACE  [http-bio-8080-exec-7] openjpa.jdbc.SQL - <t 1249135181, conn 811560660> executing prepstmnt 344473922 UPDATE PUBLIC.OPENJPA_SEQUENCE_TABLE SET SEQUENCE_VALUE = ? WHERE ID = ? AND SEQUENCE_VALUE = ? [params=?, ?, ?]
11797  facebook  TRACE  [http-bio-8080-exec-7] openjpa.jdbc.SQL - <t 1249135181, conn 811560660> [2 ms] spent
11813  facebook  TRACE  [http-bio-8080-exec-7] openjpa.jdbc.SQL - <t 1249135181, conn 1798001212> executing prepstmnt 1563539472 INSERT INTO PUBLIC.books (ID, NAME) VALUES (?, ?) [params=?, ?]
11814  facebook  TRACE  [http-bio-8080-exec-7] openjpa.jdbc.SQL - <t 1249135181, conn 1798001212> [1 ms] spent

And in tomee.xml (datasource for tomee):

<Resource id="facebook" type="DataSource">
  JdbcDriver com.mysql.jdbc.Driver
  JdbcUrl jdbc:mysql://127.0.0.1:3306/facebook?autoReconnect=true
  UserName root
  Password root
  JtaManaged true
</Resource> 

What should I add or remove to make code from controller work? (persist object in my database)

2)Second situation i have with this is: Since nothing is persist in database it is very strange for me when i try to query records from the same table in which i tried to persist, as a result i got the list of all names that i have tried to save in table. (All the names I tried to save in dbase, which are not in dbase are listed now in my jsp) My test.jsp is:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<sql:query var="rs" dataSource="jdbc/facebook">
    select name from books
</sql:query>

<html>
  <head>
    <title>DB Test</title>
  </head>
  <body>

  <h2>Results</h2>

 <c:forEach var="row" items="${rs.rows}">
    Name ${row.name}<br/>
 </c:forEach>

   </body>
</html> 

This means than datasource contain these data? Why is this happening? How to make my data be saved to database? Any help... I m new to this and all help will be precious :)

Open your server.xml file of your server and add the below content into your GlobalNamingResources section:

 <Resource name="facebook"
 auth="Container" 
 type="javax.sql.DataSource"
 driverClassName="com.mysql.jdbc.Driver"
 url="jdbc:mysql://localhost:3306/facebook" 
 factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
 username="root"
 password=""
 maxActive="100"
 maxIdle="20"
 minIdle="5"
 maxWait="10000"
/>

Then remove the resource definition from your application context.xml file and add the following xml to context.xml

<ResourceLink
        name="jdbc/facebook"
        global="facebook"
        type="javax.sql.DataSource"
        factory="org.apache.naming.factory.DataSourceLinkFactory"/>

And open your persistence.xml file and update

<jta-data-source>jdbc/facebook</jta-data-source>

Restart the server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM