I've been trying to get a hang of Java EE and EJB over the last week.
I've been able to create the entities, DAOs, persistance units and such, but I'm still running into some issues.
In my project, I have an Author and a Book class. These, in turn, have their respective DAOs. (Listed below)
The issue is, my EJBs are being created and added to the JNDI tree correctly, only I can't seem to be able to inject them into my AuthorAPI REST provider... When I call the AuthorAPI.getAllAuthors method, the server responds with a 500 error pointing to the AuthorDAO object being null.
Any help would be greatly appreciated!
TomEE log
INFO: PersistenceUnit(name=libraryPU, provider=org.hibernate.ejb.HibernatePersistence) - provider time 969ms
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.JndiBuilder bind
INFO: Jndi(name=BookDAOLocalBean) --> Ejb(deployment-id=BookDAO)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.JndiBuilder bind
INFO: Jndi(name=global/rest-web/BookDAO!org.ucll.rest.dao.BookDAO) --> Ejb(deployment-id=BookDAO)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.JndiBuilder bind
INFO: Jndi(name=global/rest-web/BookDAO) --> Ejb(deployment-id=BookDAO)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.JndiBuilder bind
INFO: Jndi(name=AuthorDAOLocalBean) --> Ejb(deployment-id=AuthorDAO)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.JndiBuilder bind
INFO: Jndi(name=global/rest-web/AuthorDAO!org.ucll.rest.dao.AuthorDAO) --> Ejb(deployment-id=AuthorDAO)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.JndiBuilder bind
INFO: Jndi(name=global/rest-web/AuthorDAO) --> Ejb(deployment-id=AuthorDAO)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.JndiBuilder bind
INFO: Jndi(name=AuthorLocalBean) --> Ejb(deployment-id=Author)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.JndiBuilder bind
INFO: Jndi(name=global/rest-web/Author!org.ucll.rest.model.Author) --> Ejb(deployment-id=Author)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.JndiBuilder bind
INFO: Jndi(name=global/rest-web/Author) --> Ejb(deployment-id=Author)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.JndiBuilder bind
INFO: Jndi(name=BookLocalBean) --> Ejb(deployment-id=Book)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.JndiBuilder bind
INFO: Jndi(name=global/rest-web/Book!org.ucll.rest.model.Book) --> Ejb(deployment-id=Book)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.JndiBuilder bind
INFO: Jndi(name=global/rest-web/Book) --> Ejb(deployment-id=Book)
dec 21, 2015 2:25:53 PM org.apache.openejb.cdi.CdiBuilder initSingleton
INFO: Existing thread singleton service in SystemInstance(): org.apache.openejb.cdi.ThreadSingletonServiceImpl#80169cf
dec 21, 2015 2:25:53 PM org.apache.openejb.cdi.OpenEJBLifecycle startApplication
INFO: OpenWebBeans Container is starting...
dec 21, 2015 2:25:53 PM org.apache.openejb.cdi.OpenEJBLifecycle startApplication
INFO: OpenWebBeans Container has started, it took 19 ms.
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.Assembler startEjbs
INFO: Created Ejb(deployment-id=AuthorDAO, ejb-name=AuthorDAO, container=Default Stateless Container)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.Assembler startEjbs
INFO: Created Ejb(deployment-id=Book, ejb-name=Book, container=Default Stateless Container)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.Assembler startEjbs
INFO: Created Ejb(deployment-id=Author, ejb-name=Author, container=Default Stateless Container)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.Assembler startEjbs
INFO: Created Ejb(deployment-id=BookDAO, ejb-name=BookDAO, container=Default Stateless Container)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.Assembler startEjbs
INFO: Started Ejb(deployment-id=AuthorDAO, ejb-name=AuthorDAO, container=Default Stateless Container)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.Assembler startEjbs
INFO: Started Ejb(deployment-id=Book, ejb-name=Book, container=Default Stateless Container)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.Assembler startEjbs
INFO: Started Ejb(deployment-id=Author, ejb-name=Author, container=Default Stateless Container)
dec 21, 2015 2:25:53 PM org.apache.openejb.assembler.classic.Assembler startEjbs
INFO: Started Ejb(deployment-id=BookDAO, ejb-name=BookDAO, container=Default Stateless Container)
HTTP Status 500 stacktrace
javax.servlet.ServletException: java.lang.NullPointerException
org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:487)
org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:425)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:383)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:336)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:223)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.NullPointerException
org.ucll.rest.web.api.AuthorAPI.getAllAuthors(AuthorAPI.java:25)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:497)
org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)
org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)
org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:160)
org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326)
org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
org.glassfish.jersey.internal.Errors.process(Errors.java:315)
org.glassfish.jersey.internal.Errors.process(Errors.java:297)
org.glassfish.jersey.internal.Errors.process(Errors.java:267)
org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:471)
org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:425)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:383)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:336)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:223)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Author.java
package org.ucll.rest.model;
import java.io.Serializable;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
*
* #author larsv
*/
#Entity
#Table(name = "author", schema = "library")
#Stateless
public class Author implements Serializable {
#Id
#GeneratedValue
#Column(name = "id")
private long id;
#Column(name = "name", length = 100, nullable = false)
private String name;
#OneToMany(mappedBy = "author")
private List<Book> books;
public Author() {}
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 List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
}
Book.java
package org.ucll.rest.model;
import java.io.Serializable;
import javax.ejb.Stateless;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
*
* #author larsv
*/
#Entity
#Table(name = "book", schema = "library")
#Stateless
public class Book implements Serializable {
#Id
#GeneratedValue
#Column(name = "id")
private long id;
#Column(name = "title", length = 100, nullable = false)
private String title;
#ManyToOne
#JoinColumn(name = "name")
private Author author;
public Book() {}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
}
AuthorDAO.java
package org.ucll.rest.dao;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.ucll.rest.model.Author;
/**
*
* #author larsv
*/
#Stateless
public class AuthorDAO extends AbstractDAO<Author> {
#PersistenceContext(unitName = "libraryPU")
private EntityManager em;
public AuthorDAO() {
super(Author.class);
}
#Override
protected EntityManager getEntityManager() {
return em;
}
}
BookDAO.java
package org.ucll.rest.dao;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.ucll.rest.model.Book;
/**
*
* #author larsv
*/
#Stateless
public class BookDAO extends AbstractDAO<Book> {
#PersistenceContext(unitName = "libraryPU")
private EntityManager em;
public BookDAO() {
super(Book.class);
}
#Override
protected EntityManager getEntityManager() {
return em;
}
}
AuthorAPI.java
package org.ucll.rest.web.api;
import javax.ejb.EJB;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.ucll.rest.dao.AuthorDAO;
import org.ucll.rest.web.helper.JSONConverter;
/**
*
* #author larsv
*/
#Path("/author")
public class AuthorAPI {
#EJB
private AuthorDAO authorDAO;
#GET
#Path("/all")
#Produces(MediaType.APPLICATION_JSON)
public Response getAllAuthors() {
String json_response = JSONConverter.covertAuthorList(authorDAO.readAll());
return Response.status(200).entity(json_response).build();
}
}
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="libraryPU" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/library</jta-data-source>
<class>org.ucll.rest.model.Author</class>
<class>org.ucll.rest.model.Book</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
</properties>
</persistence-unit>
</persistence>
The reason your #EJB is not being resolved is that you are not in the EE container context.
The easiest solution for this is to make your webservice an EJB.
This can be done by adding the stateless annotation:
#Path("/author")
#Stateless
public class AuthorAPI {
After this change your dao should get injected into it.
On a side note some tips for your code that might help prevent future problems :
You should provide a getter/setter method for
private AuthorDAO authorDAO;
Otherwise the container cant inject the implementation at runtime.
On a related note: I dont know what version of EJB you are using but in 3.0 it was necessairy to create an interface for your EJB's. Since 3.1 it is not needed anymore but I still consider it to be best practice to code vs an interface instead of vs an implementation class.
Related
It is necessary to fill the ObservableList by taking data from the table using hibernate, it turns out to be empty, the table is working, it turns out to be empty, the table works,
session open
class Main
public class Main {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
public static void main(String[] args) {
findAll();
}
#SuppressWarnings({"unchecked", "deprecation"})
public static ObservableList<Task> findAll() {
ObservableList<Task> observableTasks = FXCollections.observableArrayList();
Session session = getSessionFactory().openSession();
observableTasks.addAll(session.createCriteria(Task.class).list());
System.out.println("observableTasks = " + observableTasks.isEmpty()); // true empty
session.close();
return observableTasks;
}
public static SessionFactory getSessionFactory() {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
}
file hibernate.cfg.xml hibernate configuration class
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- <property name="connection.url">jdbc:sqlite:C:/Users/den/IdeaProjects/TodoListFx/TodoListFx/db/todolist.db-->
<property name="connection.url">jdbc:sqlite:C:/Users/den/IdeaProjects/TodoListFx/TodoListFx/db/todolist.db</property>
<property name="connection.driver_class">org.sqlite.JDBC</property>
<property name="hibernate.show_sql">true</property>
<property name="dialect">org.example.hibernate.dialect.SQLiteDialect</property>
<property name="hibernate.connection.autocommit">true</property>
<mapping class="org.example.test_hibernate_connect_bd.Task"/>
<mapping resource="TodoTask.hbm.xml"/>
<!-- <property name="connection.username"/> -->
<!-- <property name="connection.password"/> -->
<!-- DB schema will be updated if needed -->
<!-- <property name="hibernate.hbm2ddl.auto">update</property> -->
</session-factory>
</hibernate-configuration>
file TodoTask.hbm.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.example.test_hibernate_connect_bd.Task" table="todo" schema="main">
<id name="id">
<column name="id" sql-type="integer"/>
</id>
<property name="task">
<column name="task" sql-type="text"/>
</property>
<property name="time">
<column name="task_create_time" sql-type="text"/>
</property>
<property name="status">
<column name="status" sql-type="text" not-null="true"/>
</property>
</class>
</hibernate-mapping>
class Task the object itself
logs current launch
сент. 30, 2022 8:40:14 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.4.11.Final}
сент. 30, 2022 8:40:15 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
сент. 30, 2022 8:40:15 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
сент. 30, 2022 8:40:15 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.sqlite.JDBC] at URL [jdbc:sqlite:C:/Users/den/IdeaProjects/TodoListFx/TodoListFx/db/todolist.db]
сент. 30, 2022 8:40:15 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {autocommit=true}
сент. 30, 2022 8:40:15 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: true
сент. 30, 2022 8:40:15 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
сент. 30, 2022 8:40:15 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.example.hibernate.dialect.SQLiteDialect
сент. 30, 2022 8:40:16 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
сент. 30, 2022 8:40:16 PM org.hibernate.internal.SessionImpl createCriteria
WARN: HHH90000022: Hibernate's legacy org.hibernate.Criteria API is deprecated; use the JPA javax.persistence.criteria.CriteriaQuery instead
observableTasks = true
project structure
I fill in the list first, because the ObservableList class inherits from extends List , then it gets the same addAll(....) methods. I fill in my ObservableList , list , which I got from the table.
class Main
package org.example;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.example.objects.Task;
import org.example.utils.HibernateSessionFactoryUtil;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static ObservableList<Task> personList = FXCollections.observableArrayList();
public static List<Task> ist = new ArrayList<>();
public static void main(String[] args) {
findAll();
}
#SuppressWarnings({"unchecked", "deprecation"})
public static ObservableList<Task> findAll() {
ist = HibernateSessionFactoryUtil.getSessionFactory().openSession().createQuery("From Task").list();
personList.addAll(ist);
System.out.println("personList.isEmpty() = " + personList.isEmpty());
return personList;
}
}
class HibernateSessionFactoryUtil -> In this class, I create a configuration and add a class to it, with a JPA configuration
package org.example.utils;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateSessionFactoryUtil {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
public HibernateSessionFactoryUtil() {
}
public static SessionFactory getSessionFactory(){
if(sessionFactory == null){
try{
Configuration configuration = new Configuration().configure();
// here necessary class add
configuration.addAnnotatedClass(org.example.objects.Task.class);
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
} catch (Exception e) {
System.out.println("Exception !" + e);
}
}
return sessionFactory;
}
}
class Task In this class I put JPA annotations #Entity, #Id, #Column
package org.example.objects;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javax.persistence.*;
#Entity
#Table(name = "todo", schema = "main", catalog = "")
public class Task {
private SimpleIntegerProperty id = new SimpleIntegerProperty();
private SimpleStringProperty task = new SimpleStringProperty("");
private SimpleStringProperty time = new SimpleStringProperty("");
private SimpleStringProperty status = new SimpleStringProperty("");
public Task() {
}
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Id
#Column(name = "id", nullable = false)
public int getId() {
return id.get();
}
public SimpleIntegerProperty idProperty() {
return id;
}
public void setId(int id) {
this.id.set(id);
}
#Basic
#Column(name = "task", nullable = false, length = -1)
public String getTask() {
return task.get();
}
public SimpleStringProperty taskProperty() {
return task;
}
public void setTask(String task) {
this.task.set(task);
}
#Basic
#Column(name = "task_create_time", nullable = false, length = -1)
public String getTime() {
return time.get();
}
public SimpleStringProperty timeProperty() {
return time;
}
public void setTime(String time) {
this.time.set(time);
}
#Basic
#Column(name = "status", nullable = true, length = -1)
public String getStatus() {
return status.get();
}
public SimpleStringProperty statusProperty() {
return status;
}
public void setStatus(String status) {
this.status.set(status);
}
#Override
public String toString() {
return "Task{" +
"id=" + id +
", task=" + task +
", time=" + time +
", status=" + status +
'}';
}
}
the result I wanted to see is that the list is not empty
окт. 01, 2022 8:33:53 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.4.11.Final}
окт. 01, 2022 8:33:54 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
окт. 01, 2022 8:33:54 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
окт. 01, 2022 8:33:54 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.sqlite.JDBC] at URL [jdbc:sqlite:C:/Users/den/IdeaProjects/TestHibernate/db/todolist.db]
окт. 01, 2022 8:33:54 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {autocommit=true}
окт. 01, 2022 8:33:54 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: true
окт. 01, 2022 8:33:54 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
окт. 01, 2022 8:33:55 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.example.hibernate.dialect.SQLiteDialect
окт. 01, 2022 8:33:55 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
****Hibernate:
select task0_.id as id1_0_, task0_.status as status2_0_, task0_.task as task3_0_, task0_.task_create_time as task_cre4_0_ from todo task0_
personList.isEmpty() = false**** <----- here result
For some reason it does not find Polica even tho i have mapped it in code, created seperate file to map it etc. What is the problem?
In file PolicaDAO2 i am also getting createQuery deprecated for some reason if anyone knows solution to this aswell let me know. I tried multiple things aswell as you can see in the file under findall() function
Exception:
Aug 09, 2022 12:41:34 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate ORM core version 6.1.2.Final
Aug 09, 2022 12:41:40 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using built-in connection pool (not intended for production use)
Aug 09, 2022 12:41:40 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: Loaded JDBC driver class: com.mysql.cj.jdbc.Driver
Aug 09, 2022 12:41:40 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001012: Connecting with JDBC URL [jdbc:mysql://127.0.0.1:3306/Wallboard]
Aug 09, 2022 12:41:40 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {password=****, user=root}
Aug 09, 2022 12:41:40 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Aug 09, 2022 12:41:40 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH10001115: Connection pool size: 20 (min=1)
Aug 09, 2022 12:41:43 PM org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl logSelectedDialect
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Aug 09, 2022 12:41:47 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
Aug 09, 2022 12:41:47 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using built-in connection pool (not intended for production use)
Aug 09, 2022 12:41:47 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: Loaded JDBC driver class: com.mysql.cj.jdbc.Driver
Aug 09, 2022 12:41:47 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001012: Connecting with JDBC URL [jdbc:mysql://127.0.0.1:3306/Wallboard]
Aug 09, 2022 12:41:47 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {password=****, user=root}
Aug 09, 2022 12:41:47 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Aug 09, 2022 12:41:47 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH10001115: Connection pool size: 20 (min=1)
Aug 09, 2022 12:41:48 PM org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl logSelectedDialect
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Aug 09, 2022 12:41:48 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
Exception in thread "main" java.lang.IllegalArgumentException: org.hibernate.query.sqm.UnknownEntityException: Could not resolve root entity 'Polica'
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:138)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:175)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:182)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:761)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:663)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:127)
at digiwallboard.DAO.PolicaDAO2.findAll(PolicaDAO2.java:81)
at digiwallboard.Service.PolicaService.findAll(PolicaService.java:18)
at Main.main(Main.java:27)
Caused by: org.hibernate.query.sqm.UnknownEntityException: Could not resolve root entity 'Polica'
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitRootEntity(SemanticQueryBuilder.java:1628)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitRootEntity(SemanticQueryBuilder.java:243)
at org.hibernate.grammars.hql.HqlParser$RootEntityContext.accept(HqlParser.java:1874)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitEntityWithJoins(SemanticQueryBuilder.java:1548)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitFromClause(SemanticQueryBuilder.java:1539)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitQuery(SemanticQueryBuilder.java:833)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitQuerySpecExpression(SemanticQueryBuilder.java:629)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitQuerySpecExpression(SemanticQueryBuilder.java:243)
at org.hibernate.grammars.hql.HqlParser$QuerySpecExpressionContext.accept(HqlParser.java:1218)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitSimpleQueryGroup(SemanticQueryBuilder.java:623)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitSimpleQueryGroup(SemanticQueryBuilder.java:243)
at org.hibernate.grammars.hql.HqlParser$SimpleQueryGroupContext.accept(HqlParser.java:1131)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitSelectStatement(SemanticQueryBuilder.java:399)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitStatement(SemanticQueryBuilder.java:358)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.buildSemanticModel(SemanticQueryBuilder.java:285)
at org.hibernate.query.hql.internal.StandardHqlTranslator.translate(StandardHqlTranslator.java:81)
at org.hibernate.internal.AbstractSharedSessionContract.lambda$createQuery$2(AbstractSharedSessionContract.java:748)
at org.hibernate.query.internal.QueryInterpretationCacheStandardImpl.createHqlInterpretation(QueryInterpretationCacheStandardImpl.java:141)
at org.hibernate.query.internal.QueryInterpretationCacheStandardImpl.resolveHqlInterpretation(QueryInterpretationCacheStandardImpl.java:128)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:745)
... 5 more
Main.java
import digiwallboard.Util.HibernateUtil;
import digiwallboard.Entity.*;
import java.util.List;
import digiwallboard.DAO.*;
import digiwallboard.Service.PolicaService;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
PolicaService policaService = new PolicaService();
List<Polica> pol = policaService.findAll();
for(Polica p : pol) {
System.out.println("-" + p.toString());
}
}
}
PolicaDAO2.java
package digiwallboard.DAO;
import java.util.List;
import javax.persistence.TypedQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import digiwallboard.Entity.Polica;
public class PolicaDAO2 implements PolicaDaoInterface<Polica, String> {
private Session currentSession;
private Transaction currentTransaction;
public PolicaDAO2() {
}
public Session openCurrentSession() {
currentSession = getSessionFactory().openSession();
return currentSession;
}
public Session openCurrentSessionwithTransaction() {
currentSession = getSessionFactory().openSession();
currentTransaction = currentSession.beginTransaction();
return currentSession;
}
public void closeCurrentSession() {
currentSession.close();
}
public void closeCurrentSessionwithTransaction() {
currentTransaction.commit();
currentSession.close();
}
private static SessionFactory getSessionFactory() {
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
configuration.addAnnotatedClass(Polica.class);
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
return sessionFactory;
}
public Session getCurrentSession() {
return currentSession;
}
public void setCurrentSession(Session currentSession) {
this.currentSession = currentSession;
}
public Transaction getCurrentTransaction() {
return currentTransaction;
}
public void setCurrentTransaction(Transaction currentTransaction) {
this.currentTransaction = currentTransaction;
}
#SuppressWarnings("deprecation")
public void persist(Polica entity) {
getCurrentSession().save(entity);
}
#SuppressWarnings({ "unchecked", "deprecation" })
public List<Polica> findAll() {
Session session = openCurrentSession();
TypedQuery<Polica> result = (TypedQuery<Polica>) openCurrentSession().createQuery("FROM Polica");
List<Polica> result = query.getResultList();
closeCurrentSession();
/*
Query query = getCurrentSession().createQuery("select * from Polica");
List<Polica> pol = (List<Polica>) getCurrentSession().createNativeQuery("from Polica").list();
return pol;
*/
return result;
/*
TypedQuery<Polica> query = createQuery( "select * from Polica");
return query.getResultList();
*/
}
}
PolicaDaoInterface.java
package digiwallboard.DAO;
import java.io.Serializable;
import java.util.List;
public interface PolicaDaoInterface<T, Id extends Serializable> {
public List<T> findAll();
}
Polica.java
EDIT: IF YOU ARE USING HIBERNATE 6.0+ DO NOT USE JAVAX.PERSISTENCE LIKE I DID HERE THIS IS ONE OF THE REASONS I WAS GETTING THE EXCEPTION INSTEAD USE JAKARTA.PERSISTENCE
package digiwallboard.Entity;
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 = "Polica")
public class Polica {
#Id
#Column(name="id")
private int id;
#Column(name="ime_pol")
private String ime_pol;
public Polica() {
}
public Polica(int id, String ime_pol) {
super();
this.id = id;
this.ime_pol = ime_pol;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getIme_pol() {
return ime_pol;
}
public void setIme_pol(String ime_pol) {
this.ime_pol = ime_pol;
}
#Override
public String toString() {
return "Polica [id=" + id + ", ime_pol=" + ime_pol + "]";
}
}
PolicaService.java
package digiwallboard.Service;
import java.util.List;
import digiwallboard.DAO.PolicaDAO2;
import digiwallboard.Entity.Polica;
public class PolicaService {
private static PolicaDAO2 policaDao;
public PolicaService() {
policaDao = new PolicaDAO2();
}
public List<Polica> findAll() {
policaDao.openCurrentSession();
List<Polica> police = policaDao.findAll();
policaDao.closeCurrentSession();
return police;
}
}
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">Root123</property>
<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/Wallboard</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<!-- <mapping class="springfoxdemo.java.swagger.Polica" resource="springfoxdemo/java/swagger/Polica.hbm.xml"/> -->
<mapping class="digiwallboard.Entity.Polica"/>
</session-factory>
</hibernate-configuration>
hibernate.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="digiwallboard.Entity.Polica" table="Polica">
<id name="id" type="int" column="id">
<column name="id" />
</id>
<property name="ime_pol" column="ime_pol"
type="String">
</property>
</class>
</hibernate-mapping>
First of all, to avoid deprecation warnings, you should use the type safe variant of createQuery:
TypedQuery<Polica> result = openCurrentSession().createQuery("FROM Polica", Polica.class);
It's hard to say why your code is not working, but I have a few ideas what you could try. Note that you don't reference the hibernate.hbm.xml file anywhere and you commented out the reference to some other file Polica.hbm.xml, though the contents are unnecessary anyway as the annotations on the entity class are enough.
You are correctly listing the class through <mapping class="digiwallboard.Entity.Polica"/>, so it should be picked up by Hibernate. My guess is, that either some of your hbm.xml files that you might reference in your real app are interfering somehow, i.e. registering the entity type under a different name, or that your configuration is not picked up for some reason.
You can check which entities Hibernate found by inspecting getSessionFactory().getMetamodel().getEntities(), and if you find your entity there, check what EntityType#getName() reports, as that is the under which you can use the entity in HQL.
Main
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import javax.persistence.EntityManager;
import model.Companie;
import repository.CompanieRepository;
import java.util.UUID;
public class Main
{
private static final SessionFactory sessionFactory;
private static final EntityManager entityManager;
static
{
Configuration configuration = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Companie.class);
sessionFactory = configuration.buildSessionFactory();
entityManager = sessionFactory.createEntityManager();
}
public static void main(String[] args)
{
CompanieRepository companieRepository = new CompanieRepository(entityManager);
Session session = sessionFactory.openSession();
Companie comp = new Companie(26, "some name", "some another thing", "that thing");
entityManager.persist(comp);
session.close();
System.out.println();
}
}
Company class
package model;
import lombok.Data;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.UUID;
#Entity
#Data
public class Companie
{
// #Id
// #GeneratedValue(generator = "UUID")
// #GenericGenerator(name = "id", strategy = "org.hibernate.id.UUIDGenerator")
// #Column(name = "id", updatable = false, nullable = false, columnDefinition = "BINARY(16)")
// private UUID id;
#Id
private int id;
private String nume;
#Column(name = "cod_fiscal")
private String codFiscal;
#Column(name = "nr_registru_comertului")
private String nrRegistruComertului;
public Companie()
{
}
public Companie(int id, String nume, String codFiscal, String nrRegistruComertului)
{
this.id = id;
this.nume = nume;
this.codFiscal = codFiscal;
this.nrRegistruComertului = nrRegistruComertului;
}
}
Output
"C:\Program Files\Eclipse Adoptium\jdk-17.0.1.12-hotspot\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2021.2.3\lib\idea_rt.jar=49640:C:\Program Files\JetBrains\IntelliJ IDEA 2021.2.3\bin" -Dfile.encoding=UTF-8 -classpath D:\2xProjects\JavaPr\ContaApp\target\classes;C:\Users\Kentryx\.m2\repository\mysql\mysql-connector-java\8.0.25\mysql-connector-java-8.0.25.jar;C:\Users\Kentryx\.m2\repository\com\google\protobuf\protobuf-java\3.11.4\protobuf-java-3.11.4.jar;C:\Users\Kentryx\.m2\repository\org\hibernate\hibernate-core\5.6.1.Final\hibernate-core-5.6.1.Final.jar;C:\Users\Kentryx\.m2\repository\org\jboss\logging\jboss-logging\3.4.2.Final\jboss-logging-3.4.2.Final.jar;C:\Users\Kentryx\.m2\repository\javax\persistence\javax.persistence-api\2.2\javax.persistence-api-2.2.jar;C:\Users\Kentryx\.m2\repository\net\bytebuddy\byte-buddy\1.11.20\byte-buddy-1.11.20.jar;C:\Users\Kentryx\.m2\repository\antlr\antlr\2.7.7\antlr-2.7.7.jar;C:\Users\Kentryx\.m2\repository\org\jboss\spec\javax\transaction\jboss-transaction-api_1.2_spec\1.1.1.Final\jboss-transaction-api_1.2_spec-1.1.1.Final.jar;C:\Users\Kentryx\.m2\repository\org\jboss\jandex\2.2.3.Final\jandex-2.2.3.Final.jar;C:\Users\Kentryx\.m2\repository\com\fasterxml\classmate\1.5.1\classmate-1.5.1.jar;C:\Users\Kentryx\.m2\repository\javax\activation\javax.activation-api\1.2.0\javax.activation-api-1.2.0.jar;C:\Users\Kentryx\.m2\repository\org\hibernate\common\hibernate-commons-annotations\5.1.2.Final\hibernate-commons-annotations-5.1.2.Final.jar;C:\Users\Kentryx\.m2\repository\javax\xml\bind\jaxb-api\2.3.1\jaxb-api-2.3.1.jar;C:\Users\Kentryx\.m2\repository\org\glassfish\jaxb\jaxb-runtime\2.3.1\jaxb-runtime-2.3.1.jar;C:\Users\Kentryx\.m2\repository\org\glassfish\jaxb\txw2\2.3.1\txw2-2.3.1.jar;C:\Users\Kentryx\.m2\repository\com\sun\istack\istack-commons-runtime\3.0.7\istack-commons-runtime-3.0.7.jar;C:\Users\Kentryx\.m2\repository\org\jvnet\staxex\stax-ex\1.8\stax-ex-1.8.jar;C:\Users\Kentryx\.m2\repository\com\sun\xml\fastinfoset\FastInfoset\1.2.15\FastInfoset-1.2.15.jar;C:\Users\Kentryx\.m2\repository\org\projectlombok\lombok\1.18.22\lombok-1.18.22.jar Main
Jan 06, 2022 5:15:55 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate ORM core version 5.6.1.Final
Jan 06, 2022 5:15:55 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
Jan 06, 2022 5:15:56 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Jan 06, 2022 5:15:56 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.cj.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/contabilitate]
Jan 06, 2022 5:15:56 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {password=****, user=clientDragos}
Jan 06, 2022 5:15:56 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Jan 06, 2022 5:15:56 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Jan 06, 2022 5:15:56 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
Jan 06, 2022 5:15:56 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#44784e2f] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Jan 06, 2022 5:15:56 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
Process finished with exit code 0
I have a problem that I can't solve at all. I'm new to hibernate. I want to insert a new row in my database. The table is created, if I run it for the first time everything goes just fine with the creation of the table and the columns. After that, when I try to insert a row my database is not updated. Java is not inserting anything.
PS: I tried to insert a new row in MySQL Workbench at it worked just fine, the problem is that in Java it won't do the trick.
PSS: I tried another solution: session.save(Object o) etc. Nothing worked
Because you forget to start the transaction to do your work. You have to commit the transaction to confirm saving your changes to DB.
If you are using the native Hibernate API , the codes should look likes:
Session session = sessionFactory.openSession();
session.getTransaction().begin();
session.persist(comp);
session.getTransaction().commit();
If you are using JPA API , the codes should like likes :
EntityManager em = entityManagerFactory.createEntityManager();
em.getTransaction().begin();
em.persist(comp);
em.getTransaction().commit();
perform the transaction in hibernateUtil class by invoking the session and then commit the transaction. The changes may affected to the db.
I'm trying to use Hibernate in order to get data from MySQL database. In order to achieve such a goal, I have created:
Hibernate configuration file:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN" "http://www.hibernate.org/dtd/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://localhost:3306/employeesDbAF
</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.connection.pool_size">50</property>
<property name="show_sql">true</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.hbm2ddl.auto">validate</property>
<mapping class="employeesapp.Employee"></mapping>
</session-factory>
</hibernate-configuration>
Utility class
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
public static SessionFactory createSessionFactory() {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
//sessionFactory = configuration.buildSessionFactory(serviceRegistry);
sessionFactory = configuration.buildSessionFactory();
return sessionFactory;
}
public static void close() {
StandardServiceRegistryBuilder.destroy(serviceRegistry);
}
}
Main class:
public class EmployeesApp extends javax.swing.JFrame {
public static void main(String[] args) {
Session session = HibernateUtil.createSessionFactory().openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Employee emp = (Employee)session.get(Employee.class, 2);
System.out.println(emp);
tx.commit();
} catch (HibernateException e) {
if (tx != null) {
tx.rollback();
}
System.out.println(e);
} finally {
HibernateUtil.close();
}
}
EDIT:
4. Employee class:
#Entity
#Table(name="employee")
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="employee_ID")
private int employee_ID;
#Column(name="name")
private String name;
#Column(name="age")
private int age;
#Column(name="address")
private String address;
#Column(name="salary")
private int salary;
public int getEmployee_ID() {return employee_ID;}
public void setEmployee_ID(int employee_ID) {this.employee_ID = employee_ID; }
public String getName() {return name; }
public void setName(String name) {this.name = name; }
public int getAge() {return age;}
public void setAge(int age) {this.age = age; }
public String getAddress() {return address; }
public void setAddress(String address) {this.address = address; }
public int getSalary() {return salary; }
public void setSalary(int salary) {this.salary = salary; }
public Employee(int employee_ID, String name, int age, String address, int salary) {
//this.employee_ID = employee_ID;
this.name = name;
this.age = age;
this.address = address;
this.salary = salary;
}
public Employee(){
}
}
When it comes to run code, I'm not getting row from the database, just some generic SELECT clause (last row).
What am I doing wrong?
run:
Jun 05, 2019 10:53:26 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
Jun 05, 2019 10:53:26 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.1.Final}
Jun 05, 2019 10:53:26 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jun 05, 2019 10:53:26 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Jun 05, 2019 10:53:26 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Jun 05, 2019 10:53:26 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Jun 05, 2019 10:53:26 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Jun 05, 2019 10:53:26 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Jun 05, 2019 10:53:26 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/employeesDbAF]
Jun 05, 2019 10:53:26 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=root, password=****}
Jun 05, 2019 10:53:26 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
Jun 05, 2019 10:53:26 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 50 (min=1)
Jun 05, 2019 10:53:27 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Jun 05, 2019 10:53:27 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Jun 05, 2019 10:53:27 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Jun 05, 2019 10:53:27 PM org.hibernate.tool.hbm2ddl.SchemaValidator validate
INFO: HHH000229: Running schema validator
Jun 05, 2019 10:53:27 PM org.hibernate.tool.hbm2ddl.SchemaValidator validate
INFO: HHH000102: Fetching database metadata
Jun 05, 2019 10:53:27 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: employeesDbAF.employee
Jun 05, 2019 10:53:27 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [address, employee_id, name, salary, age]
**Hibernate: select employee0_.employee_ID as employee1_0_0_, employee0_.address as address2_0_0_, employee0_.age as age3_0_0_, employee0_.name as name4_0_0_, employee0_.salary as salary5_0_0_ from employee employee0_ where employee0_.employee_ID=?
employeesapp.Employee#53b7f657**
You have to override public String toString() method in Employee class.
#Override
public String toString() {
return "Employee{" +
"employee_ID=" + employee_ID +
", name='" + name + '\'' +
", age=" + age +
", address='" + address + '\'' +
", salary=" + salary +
'}';
}
System.out.println(emp); method just print to console the toString() method return value
Employee#53b7f657
Internally it will call,
// java.io.PrintStream
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
// java.lang.String
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
And the implementation of that method in Object class is
// java.lang.Object
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
So, if you do not have a 'custom' public String toString() on your class, that's what you will see because of every class is implicitly a subclass of Object.
Excepting Object, which has no superclass, every class has one and
only one direct superclass (single inheritance). In the absence of any
other explicit superclass, every class is implicitly a subclass of
Object.
Source https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
I'm trying to set up a small working sample of JPA, however when I run the code I get the follwing error:
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import encje.Klient;
import encje.Zamowienie;
public class SzkolenieJPA {
public static void main(String[] args) {
EntityManagerFactory fabryka = Persistence.createEntityManagerFactory("jpaHibernateTest");
EntityManager menadzer = fabryka.createEntityManager();
Klient przykladowy = menadzer.find(Klient.class, 1);
for(Zamowienie z : przykladowy.getZamowienia())
System.out.println(z.getAdres() + " "+ z.getData() + " "+ przykladowy.getNazwisko());
menadzer.close();
}
}
package encje;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.persistence.*;
#Entity
#Table(name="klient")
public class Klient {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name="imie", length=50, nullable=false)
private String imie;
#Column(name="nazwisko", length=50, nullable=false)
private String nazwisko;
#OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL, mappedBy="klient")
private Set<Zamowienie> zamowienia;
public Klient(){
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getImie() {
return imie;
}
public void setImie(String imie) {
this.imie = imie;
}
public String getNazwisko() {
return nazwisko;
}
public void setNazwisko(String nazwisko) {
this.nazwisko = nazwisko;
}
public Set<Zamowienie> getZamowienia() {
return zamowienia;
}
public void setZamowienia(Set<Zamowienie> zamowienia) {
this.zamowienia = zamowienia;
}
}
package encje;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.*;
import javax.persistence.Table;
#Entity
#Table(name="zamowienie")
public class Zamowienie {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name="data")
#Temporal(TemporalType.DATE)
private Date data;
#Column(name="imie", length=50)
private String adres;
#ManyToOne
#JoinColumn(name="klient", nullable=false)
private Klient klient;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getData() {
return data;
}
public void setData(Date data) {
this.data = data;
}
public String getAdres() {
return adres;
}
public void setAdres(String adres) {
this.adres = adres;
}
public Klient getKlient() {
return klient;
}
public void setKlient(Klient klient) {
this.klient = klient;
}
}
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="jpaHibernateTest" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.connection.username" value="root" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.password" value="" />
<property name="hibernate.connection.url" value="jdbc:mysql://localhost/szkolenie" />
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
</properties>
</persistence-unit>
CREATE TABLE IF NOT EXISTS `klient` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`imie` varchar(50) COLLATE utf8_polish_ci NOT NULL,
`nazwisko` varchar(50) COLLATE utf8_polish_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci AUTO_INCREMENT=4 ;
INSERT INTO `klient` (`id`, `imie`, `nazwisko`) VALUES
(1, 'janek', 'kowalski'),
(2, 'marian', 'nowak'),
(3, 'andrzej', 'nowak');
CREATE TABLE IF NOT EXISTS `zamowienie` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`data` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`adres` text NOT NULL,
`klient` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `klient_zamowienie` (`klient`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
INSERT INTO `zamowienie` (`id`, `data`, `adres`, `klient`) VALUES
(1, '2014-06-13 14:45:54', 'Adres', 1),
(2, '2014-06-14 11:58:43', 'zamowienie mariana nowaka', 2),
(3, '2014-06-02 08:31:22', 'zamowienie andrzeja nowaka', 3),
(4, '2014-06-14 11:59:11', 'zamowienie andrzeja nowaka nr 2', 3);
my errors:
juin 14, 2014 7:51:22 PM org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
juin 14, 2014 7:51:22 PM org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
juin 14, 2014 7:51:22 PM org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
juin 14, 2014 7:51:22 PM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
name: jpaHibernateTest
...]
juin 14, 2014 7:51:22 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.5.Final}
juin 14, 2014 7:51:22 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
juin 14, 2014 7:51:22 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
juin 14, 2014 7:51:22 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
juin 14, 2014 7:51:22 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
juin 14, 2014 7:51:22 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/szkolenie]
juin 14, 2014 7:51:22 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=root, password=****}
juin 14, 2014 7:51:22 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
juin 14, 2014 7:51:22 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
juin 14, 2014 7:51:23 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
juin 14, 2014 7:51:23 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
juin 14, 2014 7:51:23 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
juin 14, 2014 7:51:23 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1054, SQLState: 42S22
juin 14, 2014 7:51:23 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Unknown column 'zamowienia1_.imie' in 'field list'
juin 14, 2014 7:51:23 PM org.hibernate.event.internal.DefaultLoadEventListener onLoad
INFO: HHH000327: Error performing load command : org.hibernate.exception.SQLGrammarException: could not extract ResultSet
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1763)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1694)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:1141)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:1068)
at SzkolenieJPA.main(SzkolenieJPA.java:15)
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:89)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.getResultSet(AbstractLoadPlanBasedLoader.java:449)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeQueryStatement(AbstractLoadPlanBasedLoader.java:202)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:137)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:102)
at org.hibernate.loader.entity.plan.AbstractLoadPlanBasedEntityLoader.load(AbstractLoadPlanBasedEntityLoader.java:186)
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:4126)
at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:502)
at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:467)
at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:212)
at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:274)
at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:150)
at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1070)
at org.hibernate.internal.SessionImpl.access$2000(SessionImpl.java:176)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2551)
at org.hibernate.internal.SessionImpl.get(SessionImpl.java:955)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:1110)
... 2 more
Caused by: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Unknown column 'zamowienia1_.imie' in 'field list'
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3283)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1332)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1467)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:80)
... 18 more
some suggestions or little bit of help please
The problem is with the entity Zamowienie you are mapping the field adres to a column named imie:
#Column(name="imie", length=50)
private String adres;
I think it should be:
#Column(name="adres", length=50)
private String adres;