i want to query a mongodb here my code
Persistence.xml
<?xml version="1.0"?>
<persistence 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"
version="2.0">
<persistence-unit name="primary" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>
<properties>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossStandAloneJtaPlatform"/>
<property name="hibernate.ogm.datastore.provider" value="mongodb" />
<property name="hibernate.ogm.datastore.database" value="******" />
<property name="hibernate.ogm.datastore.host" value="******" />
<property name="hibernate.ogm.datastore.port" value="******" />
<property name="hibernate.ogm.datastore.username" value="******" />
<property name="hibernate.ogm.datastore.password" value="******" />
</properties>
</persistence-unit>
</persistence>
Flux.java
@Entity
@Table(catalog="f12", schema="public", name="enl_flux_f12_entry")
public class enl_flux_f12_entry{
@Id
public String id;
public String SYS_FluxName;
public byte[] SYS_ReadDateTime;
public String SYS_BaseNameZip;
public Long SYS_Status;
public String SYS_DateCreaERDF;
}
main
public static void main(String[] args) throws ClassNotFoundException{
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory( "primary" );
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
enl_flux_f12_entry f = entityManager.find(Flux.class, "*id*");
System.out.println(f.id);
entityManager.flush();
entityManager.close();
}
mongodb
{
"_id" : ObjectId("rzerzer"),
"SYS_FluxName" : "zerzerze.xml",
"SYS_ReadDateTime" : Timestamp(6300883749567463, 83),
"SYS_BaseNameZip" : "rferfer.zip",
"SYS_Status" : NumberLong(1),
"SYS_DateCreaERDF" : "2016-03-01T20:38:48Z"
}
The problem is that entityManager.find return always null. Is there any problem in my code?
I think it returns null because something odd in the mapping or in the JSON object and it cannot find the entity you are looking for.
The JSON object you want to get has
_id: ObjectId("rzerzer")
, this doesn't look right because an ObjectId in MongoDB should be:Even if the object in the DB is right, it is mapped as a String, so Hibernate OGM does not expect an ObjectId.
The mapping of the id on the entity should be:
or
Another strange thing is the way you are using find:
the
find
method requires the exact id of the entity. If the mapping is right, this should workentityManager.find(Flux.class, "rzerzer");
If you are not sure about the id value in the db you can also use HQL: