Eclipse JPA project (eclipselink, derby) -- "create tables from entities" produces tables in schema. yet not for SELECT * FROM TABLE_NAME; - eclipse

I'm using eclipse JPA project to create entities in Apache Derby. I'm using the JPA Tools:
"generate tables from entities.."
command. When I use this command, the tables are put into the database. I can see the tables, and that they have columns from the Eclipse "Data Source Explorer". When I log in to Derby through ij.
I type:
'show tables in schema x';
I get a list of the table names that correspond to the entities.
I type:
'select * from <table in x>'
I get:
ERROR 42X05: Table/View 'ADDRESS' does not exist.
Why do my tables not stick..? When I use the CREATE TABLE commands that are being entered in during use of the "generate tables from entities.." command, they produce tables there. When I type 'select * .." I get a table.
Second, probably related problem. I have a class. I use the following commands to obtain an entity manager:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("DataModelAccess");
EntityManager em = emf.createEntityManager();
If I run a test on my entities, such as this:
public void runTest()
{
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("DataModelAccess");
EntityManager em = emf.createEntityManager();
System.out.println(emf == null);
Address address = new Address();
address.setAddressID("1");
address.setAddressNumber(1746);
address.setStreetName("Howard");
address.setStreetType("Court");
address.setCity("Lennyville");
address.setState("CT");
address.setZipcode(73625);
em.persist(address);
em.close();
emf.close();
// reassign:
emf = Persistence.createEntityManagerFactory("DataModelAccess");
em = emf.createEntityManager();
Address address2 = em.find(Address.class, "1");
System.out.println(address2.getCity());
I get a NullPointerException on the last line.
If I do not re-assign to emf and em, It will print the city to the console.
So,
1. Why do tables not appear for SELECT * FROM <TABLE_NAME>?
But do appear for SHOW TABLES IN <SCHEMA>?
2. Why is my data not persistent across sessions?
I'm running this in Eclipse, from a plain old Java SE object. There is no Java EE container. It's an Eclipse JPA project. There is a persistence.xml file. There is a connection called 'derby' that is managed by eclipse. Maybe I have a persistence.xml file problem? Maybe this is a common problem for everyone. Maybe JPA and eclipselink do this by default because of some differing access protocol? Maybe not having a Java EE Container is making it difficult?
========
As requested:
the address class is totally irrelevant. I've tried both field and property based access also. It makes no difference to IJ. Both attempts fail equally well. This is a summary:
#Entity
#Table(name="ADDRESS")
public class Address
implements Serializable
...
#Id
public String getAddressID()
every thing else is fields, constructor, getters and setters. No annotations. I just added a new JPA entity by right-clicking on my package and selecting
New --> JPA Entity
I put the fields in it using the eclipse wizard. I made it property-based. I thought maybe field-based access would change things, so I tried field-based, but it made no difference.
where you see this: address.setStreetName("Howard");
there is the field:
private String streetName;
and two corresponding methods
setStreetName(String x);
and
String getStreetName();
The same formula exists for all fields in the class. Each field has a getter and a setter. There are no more methods than the getters and the setters. 1 field per each getter/setter method pair. There are no more annotations than I mentioned.
Just for information: I do not set all of the properties for the Address class. The fields in the table were all entered into the database as NULLABLE. Yet, IJ does not find any TABLE. – user1405870 11 hours ago
=========
Here's the Address and Address_ classes:
package dataAccess.customer;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
#Generated(value="Dali", date="2012-05-18T21:44:02.229-0500")
#StaticMetamodel(Address.class)
public class Address_
{
public static volatile SingularAttribute<Address, String> addressID;
public static volatile SingularAttribute<Address, Integer> addressNumber;
public static volatile SingularAttribute<Address, String> streetName;
public static volatile SingularAttribute<Address, String> streetType;
public static volatile SingularAttribute<Address, String> building;
public static volatile SingularAttribute<Address, String> floor;
public static volatile SingularAttribute<Address, String> unit;
public static volatile SingularAttribute<Address, String> landmarkName;
public static volatile SingularAttribute<Address, String> city;
public static volatile SingularAttribute<Address, String> state;
public static volatile SingularAttribute<Address, Integer> zipcode;
}
package dataAccess.customer;
import java.io.Serializable;
import java.lang.Integer;
import java.lang.String;
import javax.persistence.*;
/**
* Entity implementation class for Entity: Address
*
*/
#Entity
#Table(name="ADDRESS")
public class Address
implements Serializable
{
private String addressID;
private Integer addressNumber;
private String streetName;
private String streetType;
private String building;
private String floor;
private String unit;
private String landmarkName;
private String city;
private String state;
private Integer zipcode;
private static final long serialVersionUID = 1L;
public Address()
{
}
#Id
public String getAddressID()
{
return addressID;
}
public void setAddressID(String addressID)
{
this.addressID = addressID;
}
public Integer getAddressNumber()
{
return this.addressNumber;
}
public void setAddressNumber(Integer addressNumber)
{
this.addressNumber = addressNumber;
}
public String getStreetName()
{
return this.streetName;
}
public void setStreetName(String streetName)
{
this.streetName = streetName;
}
public String getStreetType()
{
return this.streetType;
}
public void setStreetType(String streetType)
{
this.streetType = streetType;
}
public String getBuilding()
{
return this.building;
}
public void setBuilding(String building)
{
this.building = building;
}
public String getFloor()
{
return this.floor;
}
public void setFloor(String floor)
{
this.floor = floor;
}
public String getUnit()
{
return this.unit;
}
public void setUnit(String unit)
{
this.unit = unit;
}
public String getLandmarkName()
{
return this.landmarkName;
}
public void setLandmarkName(String landmarkName)
{
this.landmarkName = landmarkName;
}
public String getCity()
{
return this.city;
}
public void setCity(String city)
{
this.city = city;
}
public String getState()
{
return this.state;
}
public void setState(String state)
{
this.state = state;
}
public Integer getZipcode()
{
return this.zipcode;
}
public void setZipcode(Integer zipcode)
{
this.zipcode = zipcode;
}
}
Here's the 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="DataModelAccess" transaction-type="RESOURCE_LOCAL">
<class>dataAccess.customer.Person</class>
<class>dataAccess.customer.Address</class>
<class>dataAccess.customer.PhoneNumber</class>
<class>dataAccess.customer.Customer</class>
<class>dataAccess.customer.TwoFieldTest</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="eclipselink.ddl-generation.output-mode" value="database"></property>
<property name="eclipselink.target-database" value="derby"/>
<property name="eclipselink.target-server" value="None"/>
<property name="eclipselink.exclude-eclipselink-orm" value="true"/>
<property name="eclipselink.jdbc.batch-writing" value="JDBC"/>
<property name="eclipselink.jdbc.cache-statements" value="true"/>
<property name="eclipselink.jdbc.native-sql" value="true"/>
<property name="javax.persistence.jdbc.url" value="jdbc:derby://localhost:1527/sample;create=true"/>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="eclipselink.jdbc.bind-parameters" value="false"/>
<property name="eclipselink.jdbc.exclusive-connection.mode" value="Transactional"/>
<property name="eclipselink.orm.validate.schema" value="true"/>
<property name="eclipselink.orm.throw.exceptions" value="true"/>
<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
</properties>
</persistence-unit>
</persistence>
Comments:
calling
em.flush();
is exactly what I did, in order to check if the data was persisting across sessions (which it does not). In other words, when I run the method "runTest()" I get the correct print statements, under the original runTest() method. I have posted the altered "runTest()" method (see the: //reassign "comment"). Now, when I have a customer, which I build out of three entities: address, phoneNumber, and, person, the customer can instantiated through finding the other three entities "in the database", with the entity manager. However, if I comment out everything, except for the code that looks up the three entities in the database and creates a new customer, then I find that I cannot get the data out of the database.
that looks like this:
Customer c = new Customer();
c.setAddress(em.find(Address.class, "1"));
c.setPhoneNumber(em.find(PhoneNumber.class, "1"));
c.setName(em.find(Person.class, "1"));
c.setCustomerID("123");
em.persist(c);
*/
Customer actual = em.find(Customer.class, "123");
and when I comment out everything until after em.persist(c), I do not get any Customer actual.
normally, I get this:
Customer:
Name:
Mr. Howard T Stewart III
Address:
1746 Howard Court
Lennyville, CT 73625
Phone:
(215) 256-4563
But when I comment out everything until
Customer actual = em.find(Customer.class, "123");
(now.. I instantiated the em in a previous line, but I did not now create person, phone_number, or address.)
Then, .. I get,
(actual == null)
evaluates to true.
Am I misusing the "find()" command? Am I supposed to do something else to load a current connection to the database or something (in terms of commands through em (em.method())?
Remember that there is no Java EE container here. I'm just doing this in eclipse, running main methods in j2se programs, in a JPA project in eclipse, using eclipselink 2.3. But this is not EJB, nor is it ManagedBeans or etc.
So..
I found this:
#Resource
UserTransaction utx;
...
try {
utx.begin();
bookDBAO.buyBooks(cart);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception exe) {
System.out.println("Rollback failed: "+exe.getMessage());
}
...
Unfortunately, I didn't find anything about UserTransaction until I got to the Web portion of the java ee tutorial, so, as such, I was unable to find the sentence that said "user transaction" amidst all the implication that em.persist() is all that it takes. Also, #Resource might not work outside of a Java EE Container.
Daniel: thank you for the comment, it gave me the answer that I needed.
Even though I had found the above items, and although I was doing this:
em.getTransaction().begin();
// .. set fields of address ..
em.persist(address);
em.getTransaction().commit();
em.close();
It still wasn't working. When I changed the persistence.xml file to only CREATE tables, the test method runs correctly, and, when I comment out everything but retrieve the customer from the database, that returns correctly as well.
I have also tried:
SELECT * FROM <SCHEMA>.ADDRESS;
and that works fine as well. Thank you so much, as finding out what the entity manager is actually doing because of the "DROP AND CREATE TABLES" directive would likely be a very hard thing to track down amongst tutorials.

In your persistence.xml you have,
<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
This means every time you create a new EntityManagerFactory you will recreate your database, loosing all of the data.
Either remove this, or change it to "create-tables" to only create.
For your first issue, try ., i.e. x.address

since you are using Eclipselink JPA, it will not follow standard syntax of SQL query if you are using standard "createQuery" method
You need to use this:
select t from table1 t
instead of
select * from table1
It follows syntax of JPQL. See this link for more info.
But if you want to use native sql method, use "createNativeMethod" from manager instance

Related

Update in Database not reflected in JPA Entity

I'm using EclipseLink for JPA Persistence and I'm very new to this technology. I was in a situation I had to update an entry in the table in oracle database and I did commit for this update successfully in the database but It is not reflected in JPA Entity means I can't see the data in Front end but once i restart the tomcat server, I can see the data in the front end. Someone please help me what is happening from back end.
Thanks in advance!
SDS.java
import java.util.Date;
#Entity
#Table(name="SDS")
#XmlRootElement
public class SDS {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long sdsId;
#Column
private String sdsNumber;
#Column
private String sdsName;
#Column
private String sapId;
#Column(name = "DATE_FIELD")
#Temporal(TemporalType.TIMESTAMP)
private Date sdsDate;
public SDS() {}
public Long getSdsId() {
return sdsId;
}
public void setSdsId(Long sdsId) {
this.sdsId = sdsId;
}
public String getSdsNumber() {
return sdsNumber;
}
public void setSdsNumber(String sdsNumber) {
this.sdsNumber = sdsNumber;
}
public String getSdsName() {
return sdsName;
}
public void setSdsName(String sdsName) {
this.sdsName = sdsName.substring(0, Math.min(sdsName.length(), 254));
//this.sdsName = sdsName;
}
public Date getSdsDate() {
return sdsDate;
}
public void setSdsDate(Date sdsDate) {
this.sdsDate = sdsDate;
}
}
DB Update:
update SDS set date_field='10-FEB-2017' where sdsid=1102
Update may be not reflected because when you get your Entity with EntityManager's "find" method EntityManager finds it in the persistence context, not in the database.
If the entity instance is contained in the persistence context, it is returned from there
entityManager.refresh(entity) synchronized the entity with the database for me.
entityManager.flush() did not work (even with committing everything).
entityManager.clear() or obtaining a new EntityManager from EntityManagerFactory also did not help.
And it seems that the same happens when you use "createNativeQuery" with SQL SELECT instead of the "find" method.
Oh! Look what I found.
By default EclipseLink uses a shared object cache, that caches a subset of all objects read and persisted for the persistence unit. The EclipseLink shared cache differs from the local EntityManager cache. The shared cache exists for the duration of the persistence unit (EntityManagerFactory, or server) and is shared by all EntityManagers and users of the persistence unit. The local EntityManager cache is not shared, and only exists for the duration of the EntityManager or transaction.
The shared cache can also be disabled.
property name="eclipselink.cache.shared.default" value="false"

Don't changed data on jsp after update data in postgresql

I have class to get data from db and servlet for send this data to jsp. If i insert or delete row in the table (using pgAdmin), data on jsp is updated (with new data), but if i update existing date in table, it's not updated on the jsp (only after restart glassfish).
Class using for ORM:
package db_classes;
#Entity
public class heading {
private Integer id;
private String name;
private Long themeCount;
private Collection<topic> topicsById;
#Id
#Column(name = "id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Basic
#Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Basic
#Column(name = "theme_count")
public Long getThemeCount() {
return themeCount;
}
public void setThemeCount(Long themeCount) {
this.themeCount = themeCount;
}
#OneToMany(mappedBy = "headingByIdHeading")
public Collection<topic> getTopicsById() {
return topicsById;
}
public void setTopicsById(Collection<topic> topicsById) {
this.topicsById = topicsById;
}
}
servlet:
package controllers;
/**
* Created by Otani on 25.02.2015.
*/
#WebServlet(name = "Heading_parser")
#Stateful
public class Heading_parser extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Heading_processes heading_processes = new Heading_processes();
getServletContext().setAttribute("headings",heading_processes.getAllHeading());
request.getRequestDispatcher("/WEB-INF/views/index.jsp").forward(request, response);
}
#Override
public void init() throws ServletException {
}
}
Method of Heading_processes for get data:
public List<heading> getAllHeading() {
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
try {
Query query = entityManager.createQuery("SELECT h FROM heading h");
entityManager.getTransaction().commit();
return query.getResultList();
} catch (Exception e) {
entityManager.getTransaction().rollback();
} finally {
entityManager.close();
}
return null;
}
And fragment of index.jsp:
<table class="table-border">
<tbody>
<c:forEach var = "heading" items = "${headings}">
<tr>
<td class="msg-img"><img src="image/message.png" width="32" height="32" alt="theme"></td>
<td><a href="showtopic.jsp?topic?id=${heading.id}" title=${heading.name}>${heading.name}</a></td>
<td class="count">${heading.themeCount} Тем <br> Сообщений:</td>
</tr>
</c:forEach>
</tbody>
</table>
UPD:
Add pesistance.xml:
<persistence-unit name="forum">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>db_classes.heading</class>
<class>db_classes.message</class>
<class>db_classes.topic</class>
<class>db_classes.uncensoredWords</class>
<class>db_classes.users</class>
<properties>
<property name="eclipselink.jdbc.url" value="jdbc:postgresql://localhost:5432/forum"/>
<property name="eclipselink.jdbc.driver" value="org.postgresql.Driver"/>
<property name="eclipselink.jdbc.user" value="****"/>
<property name="eclipselink.jdbc.password" value="*****"/>
</properties>
</persistence-unit>
</persistence>
This is most likely a caching issue.
See the following documentation:
https://wiki.eclipse.org/EclipseLink/Examples/JPA/Caching
By default EclipseLink uses a shared object cache, that caches a
subset of all objects read and persisted for the persistence unit. The
EclipseLink shared cache differs from the local EntityManager cache.
The shared cache exists for the duration of the persistence unit
(EntityManagerFactory, or server) and is shared by all EntityManagers
and users of the persistence unit. The local EntityManager cache is
not shared, and only exists for the duration of the EntityManager or
transaction.
The benefit of the shared cache, is that once an object has been read,
if it is read again using the find operation, the database does not
need to be accessed. Also if the object is read through any Query, it
will not need to be rebuilt, and its relationships will not need to be
re-fetched.
The limitation of the shared cache, is that if the database is changed
directly through JDBC, or by another application or server, the
objects in the shared cache will be stale.
You can quickly verify this by adding the following to your JPA config and seeing if the problem goes away:
<property name="eclipselink.cache.shared.default" value="false"/>
Whether or not you want to disable the cache permanently depends on your use case i.e. will other applications be updating these entities in the real world.

Cache JPA Entities with EJB

[The real question is marked in bold down. Here follows an as short as possible explanation of my situation]
I have the following JPA Entities:
#Entity Genre{
private String name;
#OneToMany(mappedBy = "genre", cascade={CascadeType.MERGE, CascadeType.PERSIST})
private Collection<Novel> novels;
}
#Entity
class Novel{
#ManyToOne(cascade={CascadeType.MERGE, CascadeType.PERSIST})
private Genre genre;
private String titleUnique;
#OneToMany(mappedBy="novel", cascade={CascadeType.MERGE, CascadeType.PERSIST})
private Collection<NovelEdition> editions;
}
#Entity
class NovelEdition{
private String publisherNameUnique;
private String year;
#ManyToOne(optional=false, cascade={CascadeType.PERSIST, CascadeType.MERGE})
private Novel novel;
#ManyToOne(optional=false, cascade={CascadeType.MERGE, CascadeType.PERSIST})
private Catalog appearsInCatalog;
}
#Entity
class Catalog{
private String name;
#OneToMany(mappedBy = "appearsInCatalog", cascade = {CascadeType.MERGE, CascadeType.PERSIST})
private Collection<NovelEdition> novelsInCatalog;
}
The idea is to have several Novels, belonging each to a specific Genre, for which can exist more than an edition (different publisher, year, etc). For semplicity a NovelEdition can belong to just
one Catalog, being such a Catalog represented by such a text file:
Catalog: Name Of Catalog 1
-----------------------
"Title of Novel 1", "Genre1 name","Publisher1 Name", 2009
"Title of Novel 2", "Genre1 name","Pulisher2 Name", 2010
.....
Catalog: Name Of Catalog 2
-----------------------
"Title of Novel 1", "Genre1 name","Publisher2 Name", 2011
"Title of Novel 2", "Genre1 name","Pulisher1 Name", 2011
.....
Each entity has associated a Stateless EJB that acts as a DAO, using a Transaction Scoped EntityManager. For example:
#Stateless
public class NovelDAO extends AbstractDAO<Novel> {
#PersistenceContext(unitName = "XXX")
private EntityManager em;
protected EntityManager getEntityManager() {
return em;
}
public NovelDAO() {
super(Novel.class);
}
//NovelDAO Specific methods
}
I am interested at when the catalog files are parsed and the corresponding entities are built (I usually read a whole batch of Catalogs at a time).
Being the parsing a String-driven procedure, I don't want to repeat actions like novelDAO.getByName("Title of Novel 1") so I would like to use a centralized cache for mappings of type String-Identifier->Entity object.
Currently I use 3 Objects:
1) The file parser, which does something like:
final CatalogBuilder catalogBuilder = //JNDI Lookup
//for each file:
String catalogName = parseCatalogName(file);
catalogBuilder.setCatalogName(catalogName);
//For each novel edition
String title= parseNovelTitle();
String genre= parseGenre();
...
catalogBuilder.addNovelEdition(title, genre, publisher, year);
//End foreach
catalogBuilder.build();
2) The CatalogBuilder is a Stateful EJB which uses the Cache and gets re-initialized each time a new Catalog file is parsed and gets "removed" after a catalog is persisted.
#Stateful
public class CatalogBuilder {
#PersistenceContext(unitName = "XXX", type = PersistenceContextType.EXTENDED)
private EntityManager em;
#EJB
private Cache cache;
private Catalog catalog;
#PostConstruct
public void initialize() {
catalog = new Catalog();
catalog.setNovelsInCatalog(new ArrayList<NovelEdition>());
}
public void addNovelEdition(String title, String genreStr, String publisher, String year){
Genre genre = cache.findGenreCreateIfAbsent(genreStr);//**
Novel novel = cache.findNovelCreateIfAbsent(title, genre);//**
NovelEdition novEd = new NovelEdition();
novEd.setNovel(novel);
//novEd.set publisher year catalog
catalog.getNovelsInCatalog().add();
}
public void setCatalogName(String name) {
catalog.setName(name);
}
#Remove
public void build(){
em.merge(catalog);
}
}
3) Finally, the problematic bean: Cache. For CatalogBuilder I used an EXTENDED persistence context (which I need as the Parser executes several succesive transactions) together with a Stateful EJB;
but in this case I am not really sure what I need. In fact, the cache:
Should stay in memory until the parser is finished with its job,
but not longer (should not be a singleton) as the parsing is just a
very particular activity which happens rarely.
Should keep all of
the entities in context, and should return managed entities form
methods marked with *, otherwise the attempt to persist the catalog
should fail (duplicated INSERTs)..*
Should use the same
persistence context as the CatalogBuilder.
What I have now is :
#Stateful
public class Cache {
#PersistenceContext(unitName = "XXX", type = PersistenceContextType.EXTENDED)
private EntityManager em;
#EJB
private sessionbean.GenreDAO genreDAO;
//DAOs for other cached entities
Map<String, Genre> genreName2Object=new TreeMap<String, Genre>();
#PostConstruct
public void initialize(){
for (Genre g: genreDAO.findAll()) {
genreName2Object.put(g.getName(), em.merge(g));
}
}
public Genre findGenreCreateIfAbsent(String genreName){
if (genreName2Object.containsKey(genreName){
return genreName2Object.get(genreName);
}
Genre g = new Genre();
g.setName();
g.setNovels(new ArrayList<Novel>());
genreDAO.persist(t);
genreName2Object.put(t.getIdentifier(), em.merge(t));
return t;
}
}
But honestly I couldn't find a solution which satisfies these 3 points at the same time. For example, using another stateful bean with an extended persistence context would work for the 1st parsed file, but I have
no idea what should happen from the 2nd file on.. Indeed for the first file the PC will be created and propagated from CatalogBuilder to Cache, which will then use the same PC. But after build() returns,
the PC of CatalogBuilder should (I guess) be removed and re-created during the successive parsing, although the PC of Cache should stay "alive": shouldn't in this case an exception being thrown? Another problem is
what to do when the Cache bean is passivated. Currently I get the exception:
"passivateEJB(), Exception caught ->
java.io.IOException: java.io.IOException
at com.sun.ejb.base.io.IOUtils.serializeObject(IOUtils.java:101)
at com.sun.ejb.containers.util.cache.LruSessionCache.saveStateToStore(LruSessionCache.java:501)"
Hence, I have no idea how to implement my cache. How would you solve the problem?
EclipseLink configuration :
You can have specify property in configuration file for all entites.
<property name="eclipselink.cache.shared.default" value="true"/>
At entity level with #Cache annotation, specifying different attributes.
General JPA configuration :
At entity level by using #Cacheable annotation with value attribute as true.
Specifying the retrieval mode by CacheRetrieveMode, attribute USE to enable else BYPASS.
entityManager.setProperty("javax.persistence.cache.retrieveMode", CacheRetrieveMode.USE);
Configuring the storage in cache by CacheStoreMode with attribute BYPASS, USE or REFRESH.
entityManager.setProperty("javax.persistence.cache.storeMode",CacheStoreMode.REFRESH);
Cache interface represents shared cache. To remove all or some cached entity, you can call one of the evict methods. You can get reference of cache interface from EntityManagerFactory.

Simple local JPA2HBase App with DataNucleus

I want to build a minimalistic local app that reads/writes HBase via JPA2 without orm.xml and without maven2.
Thereby I use Eclipse with the DataNucleus Plugin whose Enhancer is enabled for the project.
Inspired by
http://matthiaswessendorf.wordpress.com/2010/03/17/apache-hadoop-hbase-plays-nice-with-jpa/
I got the following Entities:
#Entity
#Table(name="account_table")
public class Account
{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private String id;
String firstName = null;
String lastName = null;
int level = 0;
#Embedded
Login login = null;
public Account() { }
public Account(String firstName, String lastName, int level, Login login) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.level = level;
this.login = login;
}
and
#Embeddable
public class Login
{
private String login = null;
private String password = null;
public Login() {
// TODO Auto-generated constructor stub
}
public Login(String login, String password) {
super();
this.login = login;
this.password = password;
}
}
The src/META-INF/persistence.xml
<persistence
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="hbase-addressbook"
transaction-type="RESOURCE_LOCAL">
<class>de.syrtec.jpa2hbase.entities.Login</class>
<class>de.syrtec.jpa2hbase.entities.Account</class>
<properties>
<property name="datanucleus.ConnectionURL" value="hbase" />
<property name="datanucleus.ConnectionUserName" value="" />
<property name="datanucleus.ConnectionPassword" value="" />
<property name="datanucleus.autoCreateSchema" value="true" />
<property name="datanucleus.validateTables" value="false" />
<property name="datanucleus.Optimistic" value="false" />
<property name="datanucleus.validateConstraints" value="false" />
</properties>
</persistence-unit>
</persistence>
the DAO:
public class TestDAO {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hbase-addressbook");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = null;
Account a1 = new Account("myPre", "mySur", 1, new Login("a", "b"));
tx = em.getTransaction();
tx.begin();
em.persist(a1);
tx.commit();
}
}
But when first line of the test DAO is executed...
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hbase-addressbook");
..I get:
11/09/01 06:57:05 INFO DataNucleus.MetaData: Class "de.syrtec.jpa2hbase.entities.Account" has been specified with JPA annotations so using those.
11/09/01 06:57:05 INFO DataNucleus.MetaData: Class "de.syrtec.jpa2hbase.entities.Login" has been specified with JPA annotations so using those.
Exception in thread "main" javax.persistence.PersistenceException: Explicit persistence provider error(s) occurred for "hbase-addressbook" after trying the following discovered implementations: org.datanucleus.api.jpa.PersistenceProviderImpl from provider: org.datanucleus.api.jpa.PersistenceProviderImpl
at javax.persistence.Persistence.createPersistenceException(Persistence.java:242)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:184)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:70)
at de.syrtec.jpa2hbase.start.TestDAO.main(TestDAO.java:15)
Caused by: org.datanucleus.exceptions.NucleusUserException: Errors were encountered when loading the MetaData for the persistence-unit "hbase-addressbook". See the nested exceptions for details
at org.datanucleus.metadata.MetaDataManager.loadPersistenceUnit(MetaDataManager.java:879)
at org.datanucleus.api.jpa.JPAEntityManagerFactory.initialiseNucleusContext(JPAEntityManagerFactory.java:745)
at org.datanucleus.api.jpa.JPAEntityManagerFactory.<init>(JPAEntityManagerFactory.java:422)
at org.datanucleus.api.jpa.PersistenceProviderImpl.createEntityManagerFactory(PersistenceProviderImpl.java:91)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:150)
... 2 more
Caused by: org.datanucleus.exceptions.ClassNotResolvedException: Class "−
de.syrtec.jpa2hbase.entities.Login" was not found in the CLASSPATH. Please check your specification and your CLASSPATH.
at org.datanucleus.JDOClassLoaderResolver.classForName(JDOClassLoaderResolver.java:247)
at org.datanucleus.JDOClassLoaderResolver.classForName(JDOClassLoaderResolver.java:412)
at org.datanucleus.metadata.MetaDataManager.loadPersistenceUnit(MetaDataManager.java:859)
... 6 more
Before I ran the DAO I triggered class enhancing by datanucleus succesfully:
DataNucleus Enhancer (version 3.0.0.release) : Enhancement of classes
DataNucleus Enhancer completed with success for 2 classes. Timings : input=623 ms, enhance=101 ms, total=724 ms. Consult the log for full details
Although I don't understand that enhancing isn't triggered automatically (referring to the logs) despite of having auto-enhancement for the project activated..
Does anybody know why my entities aren't found?
And that minus sign in persistence.xml ?

Create JPA EntityManager without persistence.xml configuration file

Is there a way to initialize the EntityManager without a persistence unit defined? Can you give all the required properties to create an entity manager? I need to create the EntityManager from the user's specified values at runtime. Updating the persistence.xml and recompiling is not an option.
Any idea on how to do this is more than welcomed!
Is there a way to initialize the EntityManager without a persistence unit defined?
You should define at least one persistence unit in the persistence.xml deployment descriptor.
Can you give all the required properties to create an Entitymanager?
The name attribute is required. The other attributes and elements are optional. (JPA specification). So this should be more or less your minimal persistence.xml file:
<persistence>
<persistence-unit name="[REQUIRED_PERSISTENCE_UNIT_NAME_GOES_HERE]">
SOME_PROPERTIES
</persistence-unit>
</persistence>
In Java EE environments, the jta-data-source and non-jta-data-source elements are used to specify the global JNDI name of the JTA and/or non-JTA data source to be used by the persistence provider.
So if your target Application Server supports JTA (JBoss, Websphere, GlassFish), your persistence.xml looks like:
<persistence>
<persistence-unit name="[REQUIRED_PERSISTENCE_UNIT_NAME_GOES_HERE]">
<!--GLOBAL_JNDI_GOES_HERE-->
<jta-data-source>jdbc/myDS</jta-data-source>
</persistence-unit>
</persistence>
If your target Application Server does not support JTA (Tomcat), your persistence.xml looks like:
<persistence>
<persistence-unit name="[REQUIRED_PERSISTENCE_UNIT_NAME_GOES_HERE]">
<!--GLOBAL_JNDI_GOES_HERE-->
<non-jta-data-source>jdbc/myDS</non-jta-data-source>
</persistence-unit>
</persistence>
If your data source is not bound to a global JNDI (for instance, outside a Java EE container), so you would usually define JPA provider, driver, url, user and password properties. But property name depends on the JPA provider. So, for Hibernate as JPA provider, your persistence.xml file will looks like:
<persistence>
<persistence-unit name="[REQUIRED_PERSISTENCE_UNIT_NAME_GOES_HERE]">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>br.com.persistence.SomeClass</class>
<properties>
<property name="hibernate.connection.driver_class" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="hibernate.connection.url" value="jdbc:derby://localhost:1527/EmpServDB;create=true"/>
<property name="hibernate.connection.username" value="APP"/>
<property name="hibernate.connection.password" value="APP"/>
</properties>
</persistence-unit>
</persistence>
Transaction Type Attribute
In general, in Java EE environments, a transaction-type of RESOURCE_LOCAL assumes that a non-JTA datasource will be provided. In a Java EE environment, if this element is not specified, the default is JTA. In a Java SE environment, if this element is not specified, a default of RESOURCE_LOCAL may be assumed.
To insure the portability of a Java SE application, it is necessary to explicitly list the managed persistence classes that are included in the persistence unit (JPA specification)
I need to create the EntityManager from the user's specified values at runtime
So use this:
Map addedOrOverridenProperties = new HashMap();
// Let's suppose we are using Hibernate as JPA provider
addedOrOverridenProperties.put("hibernate.show_sql", true);
Persistence.createEntityManagerFactory(<PERSISTENCE_UNIT_NAME_GOES_HERE>, addedOrOverridenProperties);
Yes you can without using any xml file using spring like this inside a #Configuration class (or its equivalent spring config xml):
#Bean
public LocalContainerEntityManagerFactoryBean emf(){
properties.put("javax.persistence.jdbc.driver", dbDriverClassName);
properties.put("javax.persistence.jdbc.url", dbConnectionURL);
properties.put("javax.persistence.jdbc.user", dbUser); //if needed
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setPersistenceProviderClass(org.eclipse.persistence.jpa.PersistenceProvider.class); //If your using eclipse or change it to whatever you're using
emf.setPackagesToScan("com.yourpkg"); //The packages to search for Entities, line required to avoid looking into the persistence.xml
emf.setPersistenceUnitName(SysConstants.SysConfigPU);
emf.setJpaPropertyMap(properties);
emf.setLoadTimeWeaver(new ReflectiveLoadTimeWeaver()); //required unless you know what your doing
return emf;
}
Here's a solution without Spring.
Constants are taken from org.hibernate.cfg.AvailableSettings :
entityManagerFactory = new HibernatePersistenceProvider().createContainerEntityManagerFactory(
archiverPersistenceUnitInfo(),
ImmutableMap.<String, Object>builder()
.put(JPA_JDBC_DRIVER, JDBC_DRIVER)
.put(JPA_JDBC_URL, JDBC_URL)
.put(DIALECT, Oracle12cDialect.class)
.put(HBM2DDL_AUTO, CREATE)
.put(SHOW_SQL, false)
.put(QUERY_STARTUP_CHECKING, false)
.put(GENERATE_STATISTICS, false)
.put(USE_REFLECTION_OPTIMIZER, false)
.put(USE_SECOND_LEVEL_CACHE, false)
.put(USE_QUERY_CACHE, false)
.put(USE_STRUCTURED_CACHE, false)
.put(STATEMENT_BATCH_SIZE, 20)
.build());
entityManager = entityManagerFactory.createEntityManager();
And the infamous PersistenceUnitInfo
private static PersistenceUnitInfo archiverPersistenceUnitInfo() {
return new PersistenceUnitInfo() {
#Override
public String getPersistenceUnitName() {
return "ApplicationPersistenceUnit";
}
#Override
public String getPersistenceProviderClassName() {
return "org.hibernate.jpa.HibernatePersistenceProvider";
}
#Override
public PersistenceUnitTransactionType getTransactionType() {
return PersistenceUnitTransactionType.RESOURCE_LOCAL;
}
#Override
public DataSource getJtaDataSource() {
return null;
}
#Override
public DataSource getNonJtaDataSource() {
return null;
}
#Override
public List<String> getMappingFileNames() {
return Collections.emptyList();
}
#Override
public List<URL> getJarFileUrls() {
try {
return Collections.list(this.getClass()
.getClassLoader()
.getResources(""));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
#Override
public URL getPersistenceUnitRootUrl() {
return null;
}
#Override
public List<String> getManagedClassNames() {
return Collections.emptyList();
}
#Override
public boolean excludeUnlistedClasses() {
return false;
}
#Override
public SharedCacheMode getSharedCacheMode() {
return null;
}
#Override
public ValidationMode getValidationMode() {
return null;
}
#Override
public Properties getProperties() {
return new Properties();
}
#Override
public String getPersistenceXMLSchemaVersion() {
return null;
}
#Override
public ClassLoader getClassLoader() {
return null;
}
#Override
public void addTransformer(ClassTransformer transformer) {
}
#Override
public ClassLoader getNewTempClassLoader() {
return null;
}
};
}
I was able to create an EntityManager with Hibernate and PostgreSQL purely using Java code (with a Spring configuration) the following:
#Bean
public DataSource dataSource() {
final PGSimpleDataSource dataSource = new PGSimpleDataSource();
dataSource.setDatabaseName( "mytestdb" );
dataSource.setUser( "myuser" );
dataSource.setPassword("mypass");
return dataSource;
}
#Bean
public Properties hibernateProperties(){
final Properties properties = new Properties();
properties.put( "hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect" );
properties.put( "hibernate.connection.driver_class", "org.postgresql.Driver" );
properties.put( "hibernate.hbm2ddl.auto", "create-drop" );
return properties;
}
#Bean
public EntityManagerFactory entityManagerFactory( DataSource dataSource, Properties hibernateProperties ){
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource( dataSource );
em.setPackagesToScan( "net.initech.domain" );
em.setJpaVendorAdapter( new HibernateJpaVendorAdapter() );
em.setJpaProperties( hibernateProperties );
em.setPersistenceUnitName( "mytestdomain" );
em.setPersistenceProviderClass(HibernatePersistenceProvider.class);
em.afterPropertiesSet();
return em.getObject();
}
The call to LocalContainerEntityManagerFactoryBean.afterPropertiesSet() is essential since otherwise the factory never gets built, and then getObject() returns null and you are chasing after NullPointerExceptions all day long. >:-(
It then worked with the following code:
PageEntry pe = new PageEntry();
pe.setLinkName( "Google" );
pe.setLinkDestination( new URL( "http://www.google.com" ) );
EntityTransaction entTrans = entityManager.getTransaction();
entTrans.begin();
entityManager.persist( pe );
entTrans.commit();
Where my entity was this:
#Entity
#Table(name = "page_entries")
public class PageEntry {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String linkName;
private URL linkDestination;
// gets & setters omitted
}
With plain JPA, assuming that you have a PersistenceProvider implementation (e.g. Hibernate), you can use the PersistenceProvider#createContainerEntityManagerFactory(PersistenceUnitInfo info, Map map) method to bootstrap an EntityManagerFactory without needing a persistence.xml.
However, it's annoying that you have to implement the PersistenceUnitInfo interface, so you are better off using Spring or Hibernate which both support bootstrapping JPA without a persistence.xml file:
this.nativeEntityManagerFactory = provider.createContainerEntityManagerFactory(
this.persistenceUnitInfo,
getJpaPropertyMap()
);
Where the PersistenceUnitInfo is implemented by the Spring-specific MutablePersistenceUnitInfo class.
DataNucleus JPA that I use also has a way of doing this in its docs. No need for Spring, or ugly implementation of PersistenceUnitInfo.
Simply do as follows
import org.datanucleus.metadata.PersistenceUnitMetaData;
import org.datanucleus.api.jpa.JPAEntityManagerFactory;
PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
pumd.addClassName("mydomain.test.A");
pumd.setExcludeUnlistedClasses();
pumd.addProperty("javax.persistence.jdbc.url", "jdbc:h2:mem:nucleus");
pumd.addProperty("javax.persistence.jdbc.user", "sa");
pumd.addProperty("javax.persistence.jdbc.password", "");
pumd.addProperty("datanucleus.schema.autoCreateAll", "true");
EntityManagerFactory emf = new JPAEntityManagerFactory(pumd, null);