Hibernate Test - Exception in thread "main" java.lang.NullPointerException - java

I've got this error.. Could someone help me ?
run: Exception in thread "main" java.lang.NullPointerException at
cidade.CidadeJpaController.getEntityManager(CidadeJpaController.java:24)
at cidade.CidadeJpaController.create(CidadeJpaController.java:30) at
Main.Main.main(Main.java:10) Java Result: 1
Cidade
package cidade;
import java.io.Serializable;
import javax.persistence.*;
#Entity
public class Cidade implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
private String nome;
private String uf;
public Cidade() {
}
public Cidade(String n, String u){
this.nome = n;
this.uf = u;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getUf() {
return uf;
}
public void setUf(String uf) {
this.uf = uf;
}
}
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="easyjavajpa" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>cidade.Cidade</class>
<validation-mode>NONE</validation-mode>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/thibernate"/>
<property name="javax.persistence.jdbc.password" value="1234"/>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
<property name="javax.persistence.jdbc.user" value="postgres"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>
CidadeJpaController
package cidade;
import cidade.exceptions.NonexistentEntityException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
public class CidadeJpaController implements Serializable {
public CidadeJpaController(EntityManagerFactory emf) {
this.emf = emf;
}
private EntityManagerFactory emf = null;
public CidadeJpaController() {
}
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(Cidade cidade) {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
em.persist(cidade);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(Cidade cidade) throws NonexistentEntityException, Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
cidade = em.merge(cidade);
em.getTransaction().commit();
} catch (Exception ex) {
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
long id = cidade.getId();
if (findCidade(id) == null) {
throw new NonexistentEntityException("The cidade with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void destroy(long id) throws NonexistentEntityException {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Cidade cidade;
try {
cidade = em.getReference(Cidade.class, id);
cidade.getId();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The cidade with id " + id + " no longer exists.", enfe);
}
em.remove(cidade);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}
public List<Cidade> findCidadeEntities() {
return findCidadeEntities(true, -1, -1);
}
public List<Cidade> findCidadeEntities(int maxResults, int firstResult) {
return findCidadeEntities(false, maxResults, firstResult);
}
private List<Cidade> findCidadeEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Cidade.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public Cidade findCidade(long id) {
EntityManager em = getEntityManager();
try {
return em.find(Cidade.class, id);
} finally {
em.close();
}
}
public int getCidadeCount() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<Cidade> rt = cq.from(Cidade.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
}
Main
package Main;
import java.util.*;
import cidade.*;
public class Main {
public static void main(String[] args) {
CidadeJpaController em = new CidadeJpaController();
Cidade cidade = new Cidade("Santarém", "PA");
em.create(cidade);
List cidades = em.findCidadeEntities();
System.out.println( cidades.size() + " cidade(s) encontradas" );
for (Object c : cidades) {
Cidade cid = (Cidade) c;
System.out.println(cid.getNome());
}
}
}

It seems that you are not setting the entityManagerFactory while instantiating your controller. Hence it is throwing a null pointer exception. As per your code
em = getEntityManager();
the getEntityManagerMethod():
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
Here emf is already null. As you used default constructor to initialize your code and I do not see any injection what so ever.
Regards
Himanshu

You have this constructor in CidadeJpaController which takes EntityManagerFactory object.
public CidadeJpaController(EntityManagerFactory emf) {
this.emf = emf;
}
private EntityManagerFactory emf = null;
While instantiating you're not providing EntityManagerFactory object resulting in null pointer error when trying to access. SO create an EntityManagerFactory object ans send it CidadeJpaController.Below is a sample solution change it in your Main class
public static void main(String[] args) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("easyjavajpa");
CidadeJpaController em = new CidadeJpaController(entityManagerFactory);
Cidade cidade = new Cidade("Santarém", "PA");
em.create(cidade);
List cidades = em.findCidadeEntities();

Related

cannot insert data to my table in database mysql

i have problem when insert to my database. here my setup for insert to my database.
First, I have method for getExecutionReport
first what i import
import com.dxtr.hibernate.DAOInsert;
import com.dxtr.hibernate.newOrderSingleEntity;
private void getExecutionReport(quickfix.Message message, String tipeMessage) {
// TODO Auto-generated method stub
try {
System.out.print("Message "+ message);
System.out.print("getExecutionReport "+tipeMessage);
newOrderSingleEntity newordersingleObj = new newOrderSingleEntity();
newordersingleObj.setSymbol(message.getString(Symbol.FIELD));
System.out.print(" symbol "+message.getString(Symbol.FIELD));
newordersingleObj.setMsgType(tipeMessage);
System.out.print(" tipeMessage "+tipeMessage);
newordersingleObj.setBodyLength(216);
System.out.print(" Body Length "+216);
newordersingleObj.setFixProtocol("FIX.4.2");
System.out.print("FixProtocol +FIX.4.2");
newordersingleObj.setTransactTime(message.getString(TransactTime.FIELD));
System.out.print(" time " +message.getString(TransactTime.FIELD));
newordersingleObj.setClOrdID(message.getString(ClOrdID.FIELD));
System.out.print(" ClOrdID "+message.getString(ClOrdID.FIELD));
newordersingleObj.setOrderID(message.getString(OrderID.FIELD));
System.out.print(" OrderID "+message.getString(OrderID.FIELD));
newordersingleObj.setExecID(message.getString(ExecID.FIELD));
System.out.print(" ExecID "+message.getString(ExecID.FIELD));
newordersingleObj.setExecTransType(message.getString(ExecTransType.FIELD));
System.out.print(" ExecTransType "+message.getString(ExecTransType.FIELD));
newordersingleObj.setOrdType(message.getString(OrdType.FIELD));
System.out.print(" OrdType "+message.getString(OrdType.FIELD));
newordersingleObj.setExecType(message.getString(ExecType.FIELD));
System.out.print(" ExecType "+message.getString(ExecType.FIELD));
newordersingleObj.setOrdStatus(message.getString(OrdStatus.FIELD));
System.out.print(" OrdStatus "+message.getString(OrdStatus.FIELD));
newordersingleObj.setSide(message.getInt(Side.FIELD));
System.out.print(" Side "+message.getInt(Side.FIELD));
newordersingleObj.setOrderQty(message.getDouble(OrderQty.FIELD));
System.out.print(" OrderQty "+message.getDouble(OrderQty.FIELD));
newordersingleObj.setLeavesQty(message.getDouble(LeavesQty.FIELD));
System.out.print(" LeavesQty "+message.getDouble(LeavesQty.FIELD));
newordersingleObj.setCumQty(message.getDouble(CumQty.FIELD));
System.out.print(" CumQty "+message.getDouble(CumQty.FIELD));
newordersingleObj.setLastShares(message.getInt(LastShares.FIELD));
System.out.print(" LastQty "+message.getInt(LastShares.FIELD));
System.out.print("sebelum insert ke db");
DAOInsert.newOrderSingleInsert(newordersingleObj);
} catch (FieldNotFound e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this code ok. but when i want to insert to my database my data cannot insert it.
here my entity
package com.dxtr.hibernate;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="New_Single_Order_Response",schema="dxtr_trades")
public class newOrderSingleEntity implements Serializable{
private static final long serialVersionUID = -1234424538928L;
#Id
#Column(name="response_id")
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
#Column(name="Fix_Protocol")
private String FixProtocol;
#Column(name="BodyLength")
private Integer BodyLength;
#Column(name="MsgSeqNum")
private Integer MsgSeqNum;
#Column(name="MsgType")
private String MsgType;
#Column(name="SenderCompId")
private String SenderCompId;
#Column(name="SendingTime")
private String SendingTime;
#Column(name="TargetCompID")
private String TargetCompID;
#Column(name="AveragePrice")
private Double AveragePrice;
#Column(name="ClOrdID")
private String ClOrdID;
#Column(name="CumQty")
private double CumQty;
#Column(name="Currency")
private String Currency;
#Column(name="ExecID")
private String ExecID;
#Column(name="LastShares")
private double LastShares;
#Column(name="OrderQty")
private Double OrderQty;
#Column(name="OrdStatus")
private String OrdStatus;
#Column(name="OrdType")
private String OrdType;
#Column(name="Side")
private Integer Side;
#Column(name="Symbol")
private String Symbol;
#Column(name="TransactTime")
private String TransactTime;
#Column(name="ExecType")
private String ExecType;
#Column(name="LeavesQty")
private double LeavesQty;
#Column(name="CheckSum")
private Integer CheckSum;
#Column(name="ExecTransType")
private String ExecTransType;
#Column(name="OrderID")
private String OrderID;
public Integer getResponse_ID() {
return this.id;
}
public void setResponse_ID(Integer id) {
this.id = id;
}
public String getFixProtocol() {
return this.FixProtocol;
}
public void setFixProtocol(String FixProtocol) {
this.FixProtocol = FixProtocol;
}
public Integer getBodyLength() {
return this.BodyLength;
}
public void setBodyLength(Integer BodyLength) {
this.BodyLength = BodyLength;
}
public Integer getMsgSeqNum() {
return this.MsgSeqNum;
}
public void setMsgSeqNum(Integer MsgSeqNum) {
this.MsgSeqNum = MsgSeqNum;
}
public String getMsgType() {
return this.MsgType;
}
public void setMsgType(String MsgType) {
this.MsgType = MsgType;
}
public String getSenderCompId() {
return this.SenderCompId;
}
public void setSenderCompId(String SenderCompId) {
this.SenderCompId = SenderCompId;
}
public String getSendingTime() {
return this.SendingTime;
}
public void setBodyLength(String SendingTime) {
this.SendingTime = SendingTime;
}
public String getTargetCompID() {
return this.TargetCompID;
}
public void setTargetCompID(String TargetCompID) {
this.TargetCompID = TargetCompID;
}
public Double getAveragePrice() {
return this.AveragePrice;
}
public void setAveragePrice(Double AveragePrice) {
this.AveragePrice = AveragePrice;
}
public String getClOrdID() {
return this.ClOrdID;
}
public void setClOrdID(String ClOrdID) {
this.ClOrdID = ClOrdID;
}
public double getCumQty() {
return this.CumQty;
}
public void setCumQty(double CumQty) {
this.CumQty = CumQty;
}
public String getCurrency() {
return this.Currency;
}
public void setCurrency(String Currency) {
this.Currency = Currency;
}
public String getExecID() {
return this.ExecID;
}
public void setExecID(String ExecID) {
this.ExecID = ExecID;
}
public double getLastShares() {
return this.LastShares;
}
public void setLastShares(double LastShares) {
this.LastShares = LastShares;
}
public Double getOrderQty() {
return this.OrderQty;
}
public void setOrderQty(Double OrderQty) {
this.OrderQty = OrderQty;
}
public String getExecType() {
return this.ExecType;
}
public void setExecType(String ExecType) {
this.ExecType = ExecType;
}
public String getOrdStatus() {
return this.OrdStatus;
}
public void setOrdStatus(String OrdStatus) {
this.OrdStatus = OrdStatus;
}
public String getOrdType() {
return this.OrdType;
}
public void setOrdType(String OrdType) {
this.OrdType = OrdType;
}
public Integer getSide() {
return this.Side;
}
public void setSide(Integer Side) {
this.Side = Side;
}
public String getSymbol() {
return this.Symbol;
}
public void setSymbol(String Symbol) {
this.Symbol = Symbol;
}
public String getTransactTime() {
return this.TransactTime;
}
public void setTransactTime(String TransactTime) {
this.TransactTime = TransactTime;
}
public double getLeavesQty() {
return this.LeavesQty;
}
public void setLeavesQty(double LeavesQty) {
this.LeavesQty = LeavesQty;
}
public Integer getCheckSum() {
return this.CheckSum;
}
public void setCheckSum(Integer CheckSum) {
this.CheckSum = CheckSum;
}
public String getExecTransType() {
return this.ExecTransType;
}
public void setExecTransType(String ExecTransType) {
this.ExecTransType = ExecTransType;
}
public String getOrderID() {
return this.OrderID;
}
public void setOrderID(String OrderID) {
this.OrderID = OrderID;
}
public String toString() {
return "OrderDetail?= Id: " + this.id + ", ClOrdID: " + this.ClOrdID + ", ExecID No.: " + this.ExecID + ", Symbol: " + this.Symbol;
}
}
and here my class for insert to database
package com.dxtr.hibernate;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import quickfix.StringField;
public class DAOInsert {
private DAOInsert dAOInsert;
static Session sessionObj;
static SessionFactory sessionFactoryObj;
public final static Logger logger = Logger.getLogger(DAOInsert.class);
// This Method Is Used To Create The Hibernate's SessionFactory Object
public static SessionFactory buildSessionFactory() {
// Creating Configuration Instance & Passing Hibernate Configuration File
Configuration configObj = new Configuration();
configObj.configure("hibernate.cfg.xml");
// Since Hibernate Version 4.x, ServiceRegistry Is Being Used
ServiceRegistry serviceRegistryObj = new StandardServiceRegistryBuilder().applySettings(configObj.getProperties()).build();
// Creating Hibernate SessionFactory Instance
sessionFactoryObj = configObj.buildSessionFactory(serviceRegistryObj);
return sessionFactoryObj;
}
public static void newOrderSingleInsert(newOrderSingleEntity newordersingleObj){
int count = 0;
try {
System.out.print("sudah di DAOInsert");
// Getting Session Object From SessionFactory
sessionObj = buildSessionFactory().openSession();
// Getting Transaction Object From Session Object
sessionObj.beginTransaction();
sessionObj.persist(newordersingleObj);
System.out.print(sessionObj.contains(newordersingleObj));
// Creating Transaction Entities
// newordersingleObj = new NewOrderSingle();
//newordersingleObj.setFixProtocol("FIX.4.2");
//newordersingleObj.setBodyLength(250);
//sessionObj.save(newordersingleObj);
//Committing The Transactions To The Database
sessionObj.getTransaction().commit();
//logger.info("\nSuccessfully Created '" + count + "' Records In The Database!\n");
} catch(Exception e) {
if(null != sessionObj.getTransaction()) {
logger.info("\n.......Transaction Is Being Rolled Back.......\n");
sessionObj.getTransaction().rollback();
}
e.printStackTrace();
} finally {
if(sessionObj != null) {
sessionObj.close();
}
}
}
}
i have also set 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="FastMatch" transaction-type="RESOURCE_LOCAL">
<class>com.dxtr.hibernate.newOrderSingleEntity</class>
<properties>
<property name="eclipselink.logging.level" value="INFO"/>
<property name="eclipselink.logging.level.sql" value="FINE"/>
<property name="eclipselink.logging.parameters" value="true"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://trades/tradesnew />
<property name="javax.persistence.jdbc.user" value="user" />
<property name="javax.persistence.jdbc.password" value="password" />
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="eclipselink.logging.level.connection" value="FINEST"/>
</properties>
</persistence-unit>
</persistence>
and also i have hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://url/trades</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.connection.username">user</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping class="com.dxtr.hibernate.newOrderSingleEntity"></mapping>
</session-factory>
</hibernate-configuration>
but when i want to insert to my database this data cannot insert it.. but i don't know where is the error... i have catch the error using
catch(Exception e) {
if(null != sessionObj.getTransaction()) {
logger.info("\n.......Transaction Is Being Rolled Back.......\n");
sessionObj.getTransaction().rollback();
}
e.printStackTrace();
} finally {
if(sessionObj != null) {
sessionObj.close();
}
but there is no error in my console print... so where is the problem from my code ?
for information i use mysql5.7 version and using aws
best regards,
Fuad
I would suggest you enable MySQL logs, then follow the instructions at https://dev.mysql.com/doc/refman/5.7/en/server-logs.html and be sure to flush the logs. The logs should be at /bar/log/MySQL

How to properly set up hibernate persistence with a java model

I am attempting to write a rest API to interface with a MariaDB. I feel like I am most of the way there however I am recieving the following error:
java.lang.IllegalArgumentException: Unknown entity: Models.User
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:808)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)
at test.Application.addUser(Application.java:40)
at test.Application.main(Application.java:18)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run(AbstractRunMojo.java:542)
at java.base/java.lang.Thread.run(Thread.java:834)
I imagine that this is because I have incorrectly configured the user class in the persistence.xml file in resources/META-INF. Below are the relavent inter relating files:
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="potholeAPI" transaction-
type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>Models.User</class>
<properties>
<property name="javax.persistence.jdbc.driver"
value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/PotholeDB?
useUnicode=true&useJDBCCompliantTimezoneShift
=true&useLegacyDate
timeCode=false&serverTimezone=UTC"/>
<property name="javax.persistence.jdbc.user" value="admin"/>
<property name="javax.persistence.jdbc.password" value="admin"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
</properties>
</persistence-unit>
User.java
package Models;
import org.hibernate.annotations.Entity;
import org.hibernate.annotations.Table;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
#Table(appliesTo = "Users")
public class User implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#Column(name = "id", unique = true)
private int id;
#Column(name = "name", unique = true)
private String name;
#Column(name = "created_date")
private int created_date;
getters and setters....
and the main and driver for my testing
Application.java
package test;
import Models.User;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
#SpringBootApplication
public class Application {
private static EntityManagerFactory ENTITY_MANAGER_FACTORY =
Persistence.createEntityManagerFactory("potholeAPI");
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
addUser(1, "jim");
addUser(2, "bob");
getUser(1);
getUsers();
ENTITY_MANAGER_FACTORY.close();
}
public static void addUser(int id, String name) {
EntityManager em = ENTITY_MANAGER_FACTORY.createEntityManager();
EntityTransaction et = null;
Date date = new Date();
try {
et = em.getTransaction();
et.begin();
User user = new User();
user.setId(id);
user.setName(name);
user.setCreated_date(date.getDate());
em.persist(user);
} catch (Exception ex) {
if (et != null) {
et.rollback();
}
ex.printStackTrace();
} finally {
em.close();
}
}
public static void getUser(int id) {
EntityManager em = ENTITY_MANAGER_FACTORY.createEntityManager();
String query = "SELECT u FROM User u WHERE u.id = :userID";
TypedQuery<User> tq = em.createQuery(query, User.class);
tq.setParameter("userID", id);
User user = null;
try {
user = tq.getSingleResult();
System.out.println(user.getName() + " ");
} catch (NoResultException e) {
System.out.println("ex");
e.printStackTrace();
} finally {
em.close();
}
}
public static void getUsers() {
EntityManager em = ENTITY_MANAGER_FACTORY.createEntityManager();
String query = "SELECT u FROM User u WHERE u.id IS NOT NULL";
TypedQuery<User> tq = em.createQuery(query, User.class);
List<User> users;
try {
users = tq.getResultList();
users.forEach(user-> System.out.println(user.getName()+ " "));
} catch (NoResultException e) {
System.out.println("ex");
e.printStackTrace();
} finally {
em.close();
}
}
}
My suspicion is that I screwed up the xml file however I am new to spinning up an API like this so I am not fully confident.
Tablename is 'User',so User.java->#Table(appliesTo = "Users") should be #Table(appliesTo = "User")

java hibernate the table not created even with <property name="hibernate.hbm2ddl.auto">update</property>

/**
* Description of bankbranchcontactdetailsBean
*
* #author Vishal Jain
*/
package com.beans;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
import javax.persistence.Id;
import javax.persistence.Column;
import javax.persistence.Temporal;
import javax.persistence.UniqueConstraint;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import java.io.Serializable;
import java.util.Date;
#Entity(name = "bankbranchcontactdetails")
#Table(name = "bankbranchcontactdetails", schema = "stserptest", uniqueConstraints = { #UniqueConstraint(columnNames = "BankBranchContactId") })
#TableGenerator(name = "bankbranchcontactdetailsgen", table = "bankbranchcontactdetails", pkColumnName = "BankBranchContactId")
public class bankbranchcontactdetailsBean extends SuperBeanClass implements SuperBeanInterface, Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(columnDefinition="mysql->int(10) unsigned", name = "BankBranchContactId", precision = 10, scale = 0, nullable = false, unique = true)
private Integer Id;
#Column(columnDefinition="mysql->int(10) unsigned", name = "BankBranchId", precision = 10, scale= 0, nullable = false)
private Integer _BankBranchId;
#Column(columnDefinition="mysql->enum('Phone','Mobile','Fax','Telex')", name = "ContactType", length = 6, nullable = false)
private String _ContactType;
#Column(columnDefinition="mysql->varchar(20)", name = "Contact", length = 20, nullable = false)
private String _Contact;
public bankbranchcontactdetailsBean() {
_BankBranchId = 0;
_ContactType = "";
_Contact = "";
}
public bankbranchcontactdetailsBean(Integer __BankBranchId, String __ContactType, String __Contact, Integer __MyCompanyId) {
_BankBranchId = __BankBranchId;
_ContactType = __ContactType;
_Contact = __Contact;
_MyCompanyId = __MyCompanyId;
}
public int getBankBranchContactId() {
return Id;
}
public Integer getBankBranchId() {
return _BankBranchId;
}
public String getContactType() {
return _ContactType;
}
public String getContact() {
return _Contact;
}
public void setBankBranchContactId(int NewValue) {
Id = NewValue;
}
public void setBankBranchId(Integer NewValue) {
_BankBranchId = NewValue;
}
public void setContactType(String NewValue) {
_ContactType = NewValue;
}
public void setContact(String NewValue) {
_Contact = NewValue;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">MimosaTorpedo</property>
<property name="hibernate.default_schema">stserptest</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<mapping class="com.stserp.beans.bankbranchcontactdetailsBean" />
</session-factory>
</hibernate-configuration>
/**
* Description of ManagerClass
*
* #author Vishal Jain
*/
package com.beans;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class ManagerClass {
private static SessionFactory factory = null;
private static ManagerClass _ManagerClass = null;
public static SessionFactory createSessionFactory() {
SessionFactory sessionFactory;
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
public static SessionFactory getSessionFactory() {
return factory;
}
public static ManagerClass getInstance() throws ExceptionInInitializerError {
try {
if (factory == null) {
factory = createSessionFactory();
}
if (_ManagerClass == null) {
_ManagerClass = new ManagerClass();
}
} catch (Throwable ex) {
JOptionPane.showMessageDialog(
null,
"Failed to create sessionFactory object...\n"
+ ex.getMessage(), "Error...", 0);
throw new ExceptionInInitializerError(ex);
} finally {
return _ManagerClass;
}
}
public ArrayList<Integer> SaveBeansList(Session session, String entityName,
ArrayList<? extends SuperBeanClass> BeansList)
throws HibernateException {
ArrayList<Integer> IDs = null;
try {
IDs = new ArrayList<Integer>();
for (SuperBeanClass element : BeansList) {
IDs.add((Integer) session.save(entityName, element));
}
} catch (HibernateException e) {
throw e;
}
return IDs;
}
public ArrayList<? extends SuperBeanClass> LoadTable(Session session,
String TableName) throws HibernateException {
ArrayList<? extends SuperBeanClass> beansList = null;
try {
beansList = (ArrayList<? extends SuperBeanClass>) session
.createQuery("FROM " + TableName).list();
} catch (HibernateException e) {
throw e;
}
return beansList;
}
public ArrayList<?> LoadConditional(Session session, String _query)
throws HibernateException {
ArrayList<?> beansList = null;
try {
beansList = (ArrayList<? extends SuperBeanClass>) session
.createQuery(_query).list();
} catch (HibernateException e) {
throw e;
}
return beansList;
}
public SuperBeanInterface LoadById(Session session, Class className,
Integer ID) throws HibernateException {
SuperBeanInterface BeanInterface = null;
try {
BeanInterface = (SuperBeanInterface) session.get(className, ID);
} catch (HibernateException e) {
throw e;
}
return BeanInterface;
}
public void DeleteById(Session session, Class className, Integer ID)
throws HibernateException {
try {
session.delete(session.get(className, ID));
} catch (HibernateException e) {
throw e;
}
}
}
/**
* Description of SuperBeanClass
*
* #author Vishal Jain
*/
package com.beans;
public class SuperBeanClass {
public SuperBeanClass() {
}
}
/**
* Description of SuperBeanInterface
*
* #author Vishal Jain
*/
package com.beans;
public interface SuperBeanInterface {
}
I dont know what wrong I am doing, but even though the code gets executed fine, the Table named 'bankbranchcontactdetails' does not get created, here. The database I am using is MySQL. Can anybody help me with that
Trying Changing Column Definitions here, is a good idea. The Problem was with the database specific directions 'mysql->'. I am might be using it wrongly. But for now I tried removing it and it worked.

Hibernate/JPA : IllegalArgumentException: Not an entity

I try to run a basic application with hibernate and jpa, but now I'm stuck on this exception when running app...Here's the code and erro below:
java.lang.IllegalArgumentException: Not an entity: class pka.EclipseJPAExample.domain.Employee
at org.hibernate.ejb.metamodel.MetamodelImpl.entity(MetamodelImpl.java:158)
at org.hibernate.ejb.criteria.QueryStructure.from(QueryStructure.java:136)
at org.hibernate.ejb.criteria.CriteriaQueryImpl.from(CriteriaQueryImpl.java:177)
at pka.EclipseJPAExample.jpa.JpaTest.createEmployees(JpaTest.java:47)
at pka.EclipseJPAExample.jpa.JpaTest.main(JpaTest.java:33)
JpaTest.java:
public class JpaTest {
private EntityManager manager;
public JpaTest(EntityManager manager) {
this.manager = manager;
}
/**
* #param args
*/
public static void main(String[] args) {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("persistenceUnit");
EntityManager manager = factory.createEntityManager();
JpaTest test = new JpaTest(manager);
EntityTransaction tx = manager.getTransaction();
tx.begin();
try {
test.createEmployees();
} catch (Exception e) {
e.printStackTrace();
}
tx.commit();
test.listEmployees();
System.out.println(".. done");
}
private void createEmployees() {
CriteriaBuilder builder = manager.getCriteriaBuilder();
CriteriaQuery<Employee> query = builder.createQuery(Employee.class);
query.from(Employee.class);
int numOfEmployees = manager.createQuery(query).getResultList().size();
if (numOfEmployees == 0) {
Department department = new Department("java");
manager.persist(department);
manager.persist(new Employee("Jakab Gipsz",department));
manager.persist(new Employee("Captain Nemo",department));
}
}
private void listEmployees() {
CriteriaBuilder builder = manager.getCriteriaBuilder();
CriteriaQuery<Employee> query = builder.createQuery(Employee.class);
query.from(Employee.class);
List<Employee> resultList = manager.createQuery(query).getResultList();
for (Employee next : resultList) {
System.out.println("next employee: " + next);
}
}
}
and persistence.xml:
....<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/testowa" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="enchantsql" />
<property name="hbm2ddl.auto" value="create" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
</properties>
</persistence-unit>....
Could you point where is the problem?
EDIT:
I forgot to paste Employee class...so here it is below:
#Entity
#Table(name="Employee")
public class Employee {
#Id
#GeneratedValue
private Long id;
private String name;
#ManyToOne
private Department department;
public Employee() {}
public Employee(String name, Department department) {
this.name = name;
this.department = department;
}
public Employee(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
#Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", department="
+ department.getName() + "]";
}
}
As you can see it is mapped.
Make sure #Entity annotation in your entity. You also need to configure an entity in persistence.xml
<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
<class>pka.EclipseJPAExample.domain.Employee</class>
If you have numerous ENTITY classes in your application, adding an entry for every entity in "persistence.xml" won't be a good choice.
Instead, create your own data source bean using Custom AutoConfiguration.
Use LocalContainerEntityManagerFactoryBean inside dataSource bean Creation method.
Here, you need to define
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new
LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setPackagesToScan("org.springframework.boot.entities");
This package is the location where all entity classes have been saved.
Thus no need to define every single entry for Entity classes at "persistence.xml".
Prefer Spring-based Scanning.

JUnit test; nullpointer exception

I am facing a NullPointerException.
I'm trying to perform a JUnit test and receive NullPointerException somehow.
The Test I wrote is the following;
package edu.city.set.eia.citypress.unittest.beans;
import edu.city.set.eia.citypress.model.RegisUser;
import edu.city.set.eia.citypress.beans.RegisUserFacade;
import org.junit.Test;
import static org.junit.Assert.*;
public class RegisUserUTest {
private static final String EMAIL = "test_email";
private static final String INVALID_EMAIL = "test_email_invalid";
#Test
public void testValidEmail() throws Exception {
TestEmail bean = new TestEmail();
RegisUser user = bean.findByEmail(EMAIL);
assertNotNull(user);
assertEquals(EMAIL, user.getEmail());
}
#Test(expected = Exception.class)
public void testInValidUser() throws Exception {
TestEmail bean = new TestEmail();
bean.findByEmail(INVALID_EMAIL);
}
private static class TestEmail extends RegisUserFacade {
private RegisUser user;
public TestEmail() {
user = new RegisUser();
user.setEmail(EMAIL);
}
#Override
public RegisUser findUser(String email) {
if (email.equals(user.getEmail())) {
return user;
}
return null;
}
}
}
On the other hand,
the session bean is as follows;
package edu.city.set.eia.citypress.beans;
import edu.city.set.eia.citypress.model.RegisUser;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
#Stateless
public class RegisUserFacade extends AbstractFacade<RegisUser> implements RegisUserFacadeLocal {
#PersistenceContext(unitName = "citypress_PU")
private EntityManager em;
#Override
public EntityManager getEntityManager() {
return em;
}
public void setEntityManager(EntityManager em) {
this.em = em;
}
public RegisUserFacade() {
super(RegisUser.class);
}
#Override
public RegisUser findByUsername(String username) {
Query query = this.getEntityManager().createQuery("select r from RegisUser r where username=:username");
query.setParameter("username", username);
RegisUser regisuser;
try {
regisuser = (RegisUser) query.getSingleResult();
}
catch (Exception e){
regisuser = null;
}
return regisuser;
}
#Override
public RegisUser findByUserPass(String username, String password){
Query query = this.getEntityManager().createNamedQuery("RegisUser.findByUserPass");
query.setParameter("username", username);
query.setParameter("password", password);
RegisUser regisuser;
try { // To prevent javax.persistence.NoResultException
regisuser = (RegisUser) query.getSingleResult();
}
catch (Exception e){
regisuser = null;
}
return regisuser;
}
#Override
public RegisUser findByEmail(String email) {
Query query = em.createQuery("select r from RegisUser r where r.email = :email");
query.setParameter("email", email);
RegisUser regisuser;
try {
regisuser = (RegisUser) query.getSingleResult();
}
catch (Exception e){
regisuser = null;
}
return regisuser;
}
}
When I run the test, it says NullPointerException.
java.lang.NullPointerException
at edu.city.set.eia.citypress.beans.RegisUserFacade.findByEmail(RegisUserFacade.java:63)
at edu.city.set.eia.citypress.unittest.beans.RegisUserUTest.testValidEmail(RegisUserUTest.java:16)
Seems like em is null in
Query query = em.createQuery("select r from RegisUser r where r.email = :email");
if this line is 63 (the line Number can be seen in the Stacktrace: RegisUserFacade.java:63)
It seems to be failing at the below code. The EntityManager is null and I doesn't see it being set on it by the Junit. I'd suggest you use Ejb3Unit if you want to test it out of the container or use an embedded glassfish.
Query query = this.getEntityManager().createQuery("select r from RegisUser r where username=:username");

Categories

Resources