JPA not receiving updated data - java

I use a managedBean that goes into the db and defines the bean properties with db data. However when I update the db the data I receive in my bean is not updated.
The query in db is like this:
private static final String JPQL_FIND_BY_ID = "SELECT c FROM Category c WHERE c.idcategory=:id";
#Override
public Category findCatById(int id) {
Query query = em.createQuery(JPQL_FIND_BY_ID, Category.class);
query.setParameter("id", id);
Category cat = null;
try {
cat = (Category) query.getSingleResult();
} catch (Exception e) {
e.printStackTrace();
}
return cat;
}
The managed bean I use to get the category asks the ejb to make a lookup in the db:
#ManagedBean
public class CategoryBean {
private String idCategoryStr;
private Category category;
private int id;
#EJB
private CategoryLookUp categoryService;
#PostConstruct
public void init() {
this.category = categoryService.findCatById(id); //id defined in constructor
System.out.println(this.category.getName());//this will give the same
//name before and after db update
}
public CategoryBean() {
FacesContext fc = FacesContext.getCurrentInstance();
Map<String, String> paramsMap = fc.getExternalContext()
.getRequestParameterMap();
this.idCategoryStr = paramsMap.get("id");
try {
id = Integer.parseInt(idCategoryStr);
} catch (Exception e) {
}
}
//get&set
}
If I change the Title of the category in my db, it's gonna be unchanged in my bean even though #PostConstruct is called and the id is correct.
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="my-pu" transaction-type="JTA">
<jta-data-source>jdbc/forumcsDS</jta-data-source>
<class>main.java.entities.Category</class>
<class>main.java.entities.Country</class>
<class>main.java.entities.Forum</class>
<class>main.java.entities.Message</class>
<class>main.java.entities.Post</class>
<class>main.java.entities.Thethread</class>
<class>main.java.entities.Usercfg</class>
<class>main.java.entities.Usercredential</class>
<class>main.java.entities.Userinfo</class>
<class>main.java.entities.User</class>
<class>main.java.entities.Friend</class>
</persistence-unit>
</persistence>

Reason that you get old value is that your entity is stored in second level cache. And when you request it second time no database call is executed, but value from memory is returned.
You can disable cache by adding <property name="eclipselink.cache.shared.default" value="false"/> to property section of your persistence.xml

Related

REST Service with NetBeans JPA

I have some difficulties with my first experiments with Web Applications.
I’m using
jdk15.0.1
NetBeans 12.0
MySQL 5.7.19
Payara Server 5.201
Windows 10 build 19041.685
When I create a project Web Application ( Java with Maven > Web Application ), I write my Entity Class, but when I try to generate Persistence unit it does not allow me to use the JTA.
Book.java
#XmlRootElement
#Entity
#NamedQueries({
#NamedQuery(name = "Book.findAll", query = "SELECT d FROM Book d")
})
public class Book implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
private String author;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.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 Book)) {
return false;
}
Book other = (Book) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.mycompany.test201.Book[ id=" + id + " ]";
}
}
I add New>RESTful Web Services from Patterns...
BookResource.java
#RequestScoped
#Path("book")
public class BookResource {
#PersistenceContext(unitName = "test201pu")
private EntityManager em;
// #Context
// private UriInfo context;
/**
* Creates a new instance of BookResource
*/
public BookResource() {
}
#POST
#Transactional
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void addBook(#FormParam("aut")String autr, #FormParam("titl")String til) {
Book b=new Book();
b.setAuthor(autr);
b.setTitle(til);
em.persist(b);
}
/**
* Retrieves representation of an instance of com.mycompany.test201.BookResource
* #return an instance of java.lang.String
*/
#GET
#Produces(MediaType.APPLICATION_XML)
public List<Book> getXml() {
Query q=em.createNamedQuery("Book.findAll", Book.class);
return q.getResultList();
}
/**
* PUT method for updating or creating an instance of BookResource
* #param content representation for the resource
*/
#PUT
#Consumes(MediaType.APPLICATION_XML)
public void putXml(String content) {
}
}
I am forced to correct by hand the XML from
transaction-type="RESOURCE_LOCAL" to transaction-type="JTA" .
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="test201pu" transaction-type="JTA">
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test201?zeroDateTimeBehavior=CONVERT_TO_NULL"/>
<property name="javax.persistence.jdbc.user" value="piero"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="javax.persistence.jdbc.password" value="my_password"/>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>
Also the checkbox "Include All Entity Classes in ... Module" is always disabled (and the same the other checkbox “Use Java Transaction APIs”)
Finally when I try some transaction, obviously using like JDBC a connection to database MySQL, there’s no tables in database, so I don’t know where the data was stored.

Exception in thread "main" java.lang.IllegalArgumentException: java.lang.Object is not an indexed entity or a subclass of an indexed entity

Am trying to configure HibernateSearch for ElasticSearch Integration.
I have Product table in my oracle database. From that table am trying to search based on product name.
For that am trying to integrate HibernateSearch (ElasticSearch) along with oracle database.
Am getting the below error from HibernateSearch :
Am using Oracle database and added the required dependencies in my pom.xml file
Exception in thread "main" java.lang.IllegalArgumentException: java.lang.Object is not an indexed entity or a subclass of an indexed entity
at org.hibernate.search.batchindexing.impl.MassIndexerImpl.toRootEntities(MassIndexerImpl.java:87)
at org.hibernate.search.batchindexing.impl.MassIndexerImpl.<init>(MassIndexerImpl.java:63)
at org.hibernate.search.batchindexing.impl.DefaultMassIndexerFactory.createMassIndexer(DefaultMassIndexerFactory.java:33)
at org.hibernate.search.impl.FullTextSessionImpl.createIndexer(FullTextSessionImpl.java:175)
at com.test.webservice.elasticsearch.App.doIndex(App.java:36)
at com.test.webservice.elasticsearch.App.main(App.java:109)
Am using all the latest dependencies.
hibernate-search-orm ->5.9.1.Final
hibernate-core ->5.2.16.Final`
ojdbc14 -> 10.2.0.4.0
App.java
public class App
{
private static void doIndex() throws InterruptedException {
Session session = HibernateUtil.getSession();
FullTextSession fullTextSession = Search.getFullTextSession(session);
fullTextSession.createIndexer().startAndWait(); // Error occuring on this line
fullTextSession.close();
}
private static List<Product> search(String queryString) {
Session session = HibernateUtil.getSession();
FullTextSession fullTextSession = Search.getFullTextSession(session);
QueryBuilder queryBuilder = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Product.class).get();
org.apache.lucene.search.Query luceneQuery = queryBuilder.keyword().onFields("name").matching(queryString).createQuery();
// wrap Lucene query in a javax.persistence.Query
org.hibernate.Query fullTextQuery = fullTextSession.createFullTextQuery(luceneQuery, Product.class);
List<Product> productList = fullTextQuery.list();
fullTextSession.close();
return productList;
}
private static void displayContactTableData() {
Session session = null;
PropertiesFile propertiesFile= PropertiesFile.getInstance();
String driverClass = propertiesFile.extractPropertiesFile().getProperty("hibernate.connection.driver_class");
String connectionURL = propertiesFile.extractPropertiesFile().getProperty("hibernate.connection.url");
String userName = propertiesFile.extractPropertiesFile().getProperty("hibernate.connection.username");
String password = propertiesFile.extractPropertiesFile().getProperty("hibernate.connection.password");
String dialect = propertiesFile.extractPropertiesFile().getProperty("hibernate.dialect");
String showSQL = propertiesFile.extractPropertiesFile().getProperty("hibernate.show_sql");
try {
//session = HibernateUtil.getSession();
// Fetching saved data
String hql = "from Product";
#SuppressWarnings("unchecked")
Configuration cfg=new Configuration()
.setProperty("hibernate.connection.driver_class", driverClass)
.setProperty("hibernate.connection.url", connectionURL)
.setProperty("hibernate.connection.username", userName)
.setProperty("hibernate.connection.password", password)
.setProperty("hibernate.dialect", dialect)
.setProperty("hibernate.show_sql", showSQL)
.addAnnotatedClass(com.test.webservice.model.Product.class);
SessionFactory factory=cfg.buildSessionFactory();
session=factory.openSession();
Transaction t=session.beginTransaction();
List<Product> productList = session.createQuery(hql).list();
for (Product product : productList) {
System.out.println("Product Name --->"+product.getName());
}
} catch(HibernateException exception){
System.out.println("Problem creating session factory");
exception.printStackTrace();
}finally{
if(session != null) {
session.close();
}
}
}
public static void main(String[] args) throws InterruptedException {
System.out.println("\n\n******Data stored in Contact table******\n");
displayContactTableData();
// Create an initial Lucene index for the data already present in the database
doIndex(); // Error occuring on this line
Scanner scanner = new Scanner(System.in);
String consoleInput = null;
while (true) {
// Prompt the user to enter query string
System.out.println("\n\nEnter search key (To exit type 'X')");
System.out.println();
consoleInput = scanner.nextLine();
if("X".equalsIgnoreCase(consoleInput)) {
System.out.println("End");
System.exit(0);
}
List<Product> result = search(consoleInput);
System.out.println("\n\n>>>>>>Record found for '" + consoleInput + "'");
for (Product product : result) {
System.out.println(product);
}
}
}
}
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#localhost:1521:xe</property>
<property name="hibernate.connection.username">vb</property>
<property name="hibernate.connection.password">123456</property>
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<property name="show_sql">false</property>
<property name="format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.search.default.directory_provider">filesystem</property>
<property name="hibernate.search.default.indexBase">C:\lucene\indexes</property>
<mapping class="com.test.webservice.model.Product" />
</session-factory>
</hibernate-configuration>
Product.java
#Entity
#Indexed
#Table(name = "PRODUCT")
public class Product {
private String name;
private long id;
#Field(index = Index.YES, analyze = Analyze.YES, store = Store.NO)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setId(long id) {
this.id = id;
}
#Id
public long getId() {
return id;
}
}
The error message is wrong, it should be "java.lang.Object is not an indexed entity or a superclass of an indexed entity". I created a ticket, we'll fix the error message ASAP.
Regarding your problem, this exception means neither Object nor any of its subclasses is indexed. In short, there isn't any indexed class.
I can see that your Product class is annotated with #Indexed, so this probably means there is a problem with how you start Hibernate ORM in HibernateUtil.
The simple fact that you commented your line session = HibernateUtil.getSession(); in displayContactTableData() makes me think you already knew that, though.
You should have a look at the getting started guide to make sure you start Hibernate ORM correctly.
I had the same problem and I changed my import from import org.springframework.stereotype.Indexed; to import org.hibernate.search.annotations.Indexed; and it worked!!

Only one entity generated in database [jee]

i am new in jee
i create two entities with different namedquery.
when i run my application on wildfly 10, only one entity generated in the data base despite when i check my console i find my two entities in jndi.
this is my two classes:
models:
#Entity
#NamedQuery(name="ClientBanque.findAll", query="SELECT client FROM ClientBanque client")
public class ClientBanque implements Serializable {
#Id
int cin;
String prenom;
String nom;
String adress;
//getters and setters
// constructor using fields
}
#NamedQuery(name="CompteBancair.findAll", query="SELECT c FROM CompteBancair c")
public class CompteBancair implements Serializable {
#Id
long rib;
float solde;
// getters, setters, constructor
}
dao:
#Stateless
public class ClientBanqueDAO {
#PersistenceContext
private EntityManager em;
public void persist(ClientBanque client) {
em.persist(client);
}
public List<ClientBanque> getAllCustomers() {
Query q = em.createNamedQuery("ClientBanque.findAll", ClientBanque.class);
List<ClientBanque> resultList = q.getResultList();
return resultList;
}
}
#Stateless
public class CompteBancaireDAO {
#PersistenceContext
private EntityManager em;
public void persistAcount(CompteBancair compte) {
em.persist(compte);
}
public List<CompteBancair> getAllAcount() {
Query q = em.createNamedQuery("CompteBancair.findAll", CompteBancair.class);
List<CompteBancair> resultList = q.getResultList();
return resultList;
}
}
the persistant.xml contains :
<?xml version="1.0" encoding="UTF-8"?>
<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_1_0.xsd"
version="1.0">
<persistence-unit name="bank">
<jta-data-source>java:jboss/mysql/bank</jta-data-source>
<properties>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
what i can do to fix this problem ?

Configuring Kundera with HBase

I currently have an HBase/Hadoop cluster running without issues, and I am fairly familiar with these products. I recently heard about Kundera, and it looks to be a very powerful tool that I would like to use.
However, I cannot seem to find any documentation/tutorials/examples for setting up Kundera with HBase. I have tried some of the materials I happened to come across, but they have failed so egregiously that I am under the impression that it wasn't relevant.
Essentially I don't know where to begin. I'm not worried about somebody explaining to me any kind of advanced level stuff, but I just cannot get this thing configured.
If anybody can point me in the right direction I would greatly appreciate it.
TLDR: I have an HBase cluster running and want to use Kundera with it and I have no clue where to begin whatsoever. Thanks.
You can start here https://github.com/impetus-opensource/Kundera and https://github.com/impetus-opensource/Kundera/wiki
Kundera is JPA compliant , it's pretty easy and straight forward to setup. wiki has enough documentation / examples to get you started. Kundera dev team is very active here as well.
Just create your persistence.xml as shown
https://github.com/impetus-opensource/Kundera/wiki/Common-Configuration
and hbase specific options
https://github.com/impetus-opensource/Kundera/wiki/HBase-Specific-Features
Kundera + Hbase Configuration in Eclipse
Start your Hbase configuration on linux or others
create Dynamic web project
Add the following jar into Libraries of the project
1)asm-4.0.jar
2)cglib-2.1.jar
3)commons-lang-2.5.jar
4)commons-logging-1.1.1.jar
5)hadoop-core-1.0.0.jar
6)hbase-0.94.4.jar
7)jts-1.11.jar
8)kundera-core-2.5.1.jar
9)kundera-hbase-2.5.jar
10)log4j-1.2.16.jar
11)lucene-core-3.5.0.jar
12)xstream-1.3.1.jar
13)zookeeper-3.3.2.jar
Add the persistence.xml file as following
<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="hbase_pu">
<provider>com.impetus.kundera.KunderaPersistence</provider>
<class>com.fvrl.MyObject</class>
<properties>
<property name="kundera.nodes" value="your host ip"/>
<property name="kundera.port" value="port"/>
<property name="kundera.keyspace" value="KunderaExamples"/>
<property name="kundera.dialect" value="hbase"/>
<property name="kundera.client.lookup.class" value="com.impetus.client.hbase.HBaseClientFactory" />
<property name="kundera.client.property" value="yourxmlfilepath" />
<property name="kundera.ddl.auto.prepare" value="update" />
</properties>
</persistence-unit>
</persistence>
Above xml file path must be place in proper place.
Make your Entity Class as below
#Entity
#Table(name = "MyObject", schema = "KunderaExamples#hbase_pu")
#NamedQueries({
#NamedQuery(name="findAll", query="select c from MyObject c")
})
public class MyObject
{
#Id
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getSecondname() {
return secondname;
}
public void setSecondname(String secondname) {
this.secondname = secondname;
}
private String firstname;
private String secondname;
}
Run Your Project through main method
public static void main(String[] args) {
MyObject myObject = new MyObject();
myObject.setId("0006");
myObject.setFirstname("Nirav");
myObject.setSecondname("shah");
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hbase_pu");
EntityManager em = emf.createEntityManager();
//Save
HBaseJPAImpl hBaseJPAImpl =new HBaseJPAImpl(em);
hBaseJPAImpl.save(myObject);
//retrive
List<MyObject> list= hBaseJPAImpl.findAllDetails();
for(MyObject myObject1 : list){
System.out.println("Row Id : "+myObject1.getId());
System.out.println("First Name : "+myObject1.getFirstname());
System.out.println("Last Name : "+myObject1.getSecondname());
}
}
HBaseJPAImpl Class is following
public class HBaseJPAImpl implements IHBaseJPA
{
public HBaseJPAImpl(EntityManager em) {
// TODO Auto-generated constructor stub
this.em = em;
}
#Inject protected EntityManager em;
#Transactional
public void save(MyObject myObject)
{
// em.persist(myObject));
EntityTransaction entityTransaction = this.em.getTransaction();
entityTransaction.begin();
em.persist(myObject));
entityTransaction.commit();
}
#SuppressWarnings("unchecked")
#Override
#Transactional
public List<MyObject> findAllDetails()
{
Query query = em.createNamedQuery("findAll");
List<MyObject> results = (List<MyObject>) query.getResultList();
return results;
}
}
interface IHBaseJPA is below
public interface IHBaseJPA
{
void save(MyObject contact);`enter code here`
List<MyObject> findAllDetails();
}
if find any queries on the above then contact me

JPA reads but doesn't persists

My Java Web App reads data from database but when I try to write something, JPA says ok, but the database does not change. I call "merge" method and the data are not being saved on database, only in memory. I can do a SELECT direct into database and see old data. But the Java Console does not throw any Exception as you can see above.
Java Console:
INFO: [EL Finest]: 2011-10-14 15:02:41.847--UnitOfWork(13027895)--Thread(Thread[http-thread-pool-8080-(6),10,Grizzly])--Merge clone with references user1
Change Password's method that is being called:
public static User changePassword(String username, String oldPassword, String newPassword){
User user = userFacade.find(username);
if(user != null && user.getPassword().equals(oldPassword)){
user.setPassword(newPassword);
userFacade.edit(user); // supposed to save the new password on database, but it's not
// at this point, the user has a new password on memory, but on database the password is still the old one
return user;
}
return null;
}
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="APP1PU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.company.User</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/app1"/>
<property name="javax.persistence.jdbc.password" value="12345"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="eclipselink.logging.level" value="FINEST"/>
</properties>
</persistence-unit>
</persistence>
User.java:
#Entity
#Table(name = "user")
#Cache (
type=CacheType.NONE
)
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
private String username;
#Basic(optional = false)
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
UserFacade.java
public class UserFacade {
private EntityManagerFactory emf = Persistence.createEntityManagerFactory("APP1PU");
private EntityManager em;
protected EntityManager getEntityManager() {
if( em == null ){
em = emf.createEntityManager();
}
return em;
}
public void create(User entity) {
getEntityManager().persist(entity);
}
public void edit(User entity) {
getEntityManager().merge(entity);
}
public void remove(User entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public User find(Object id) {
return getEntityManager().find(entityClass, id);
}
}
Anyone can figure why this behavior? Or has some suggestion of a test I could do?
Thanks in advance!
Try entityManager.flush() after a write operation. Or start a transaction (entityManager.getTransaction().begin()) before your write operation, and then close it at the end (entityManager.getTransaction().commit())

Categories