Can't understand what i'm doing wrong.
Have an Exception in thread "AWT-EventQueue-0" java.lang.ExceptionInInitializerError
I thought it`s a problem with sessionFactory but can't understand how resolve it.
HibernateUtil.java
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import java.util.List;
import java.util.Date;
import java.util.Iterator;
public class HibernateUtil {
private static SessionFactory sessionFactory;
public HibernateUtil(){ }
static{
try{
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
}catch(Throwable e) {
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
}
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/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>
<!-- Assume test is the database name -->
<property name="hibernate.connection.url">
jdbc:mysql://localhost/storage
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
root
</property>
<mapping class="main.java.table.Brand"/>
<mapping class="main.java.table.HardDrive"/>
</session-factory>
</hibernate-configuration>
Goods.java
package main.java.table;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "goods")
public class Goods {
#Id #GeneratedValue
#Column(name = "idGoods")
private int idGoods;
#Column(name = "price")
private double price;
#Column(name = "quantity")
private int quantity;
public int getIdGoods() {
return idGoods;
}
public void setIdGoods(int idGoods) {
this.idGoods = idGoods;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
CheckInDatabase.java
package main.java.cheking;
import java.util.Iterator;
import java.util.List;
import main.java.table.Brand;
import main.java.table.HardDrive;
import main.java.util.HibernateUtil;
import org.hibernate.Session;
/*
* Класс проверяет повторы в таблицах и если их нет создает и возвращает запись
*/
public class CheckInDatabase {
private static Session session = null;
public static List list = null;
public static List<Brand> listOut = null;
//List <E> list = null;
CheckInDatabase(){}
public static List isNameInDataBase(String name, String table) {
try{
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
list = session.createQuery("FROM " + table + " WHERE name like '" + name + "' ").list();
} catch(Exception e){
e.printStackTrace();
} finally {
if ((session != null) && (session.isOpen()))
session.close();
}
return list;
}
public static Brand isBrandInDataBase(String name){
Brand brand = new Brand();
try{
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
listOut = session.createQuery("FROM Brand WHERE nameBrand like '" + name + "' ").list();
} catch(Exception e){
e.printStackTrace();
} finally {
if ((session != null) && (session.isOpen()))
session.close();
}
if (listOut.isEmpty()){
brand.nameBrand = name; //если бренда в базе нет, создаем
Session session = null;
try{
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(brand);
System.out.println("Brand created");
session.getTransaction().commit();
} catch(Exception e){
e.printStackTrace();
} finally {
if ((session != null) && (session.isOpen()))
session.close();
}
return brand;
}
else{
for (Iterator iterator =
CheckInDatabase.listOut.iterator(); iterator.hasNext();){
brand = (Brand) iterator.next();
System.out.print("Id: " + brand.getIdBrand()+ " ");
System.out.print("Name: " + brand.getNameBrand()+ " ");
System.out.println("\n");
}
return brand;
}
}
}
HardDrive.java
package main.java.table;
import java.sql.SQLException;
import java.util.List;
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;
import main.java.cheking.CheckInDatabase;
#Entity
#Table(name = "harddrives")
public class HardDrive {
#Id #GeneratedValue
#Column(name = "idHardDrive")
private int idHardDrive;
#Column(name = "name")
private String name;
#Column(name = "formFactor")
private double formFactor;
#Column(name = "capacity")
private int capacity;
#Column(name = "interface")
private String interFace;
#Column(name = "bufferSize")
private String bufferSize;
#ManyToOne
#JoinColumn (name = "idBrand")
private Brand brand;
#ManyToOne
#JoinColumn (name = "idGoods")
private Goods goods;
public HardDrive(){}
public HardDrive(String name, double formFactor, int capacity, String interFace, String bufferSize, String brand) {
List nameList = null;
nameList = CheckInDatabase.isNameInDataBase(name, "HardDrive");
if (nameList.isEmpty()){
this.name = name;
this.formFactor = formFactor;
this.capacity = capacity;
this.interFace = interFace;
this.bufferSize = bufferSize;
Brand brand2 = new Brand();
this.brand = brand2.setNameBrand(brand);
System.out.println("BRAND NAME IN HARDDRIVE = " + this.brand.getNameBrand() );
}
else{
System.out.println("this name is in the table");
}
System.out.println("Can set");
}
public int getIdHardDrives() {
return idHardDrive;
}
public void setIdHardDrives(int idHardDrives) {
this.idHardDrive = idHardDrives;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getFormFactor() {
return formFactor;
}
public void setFormFactor(double formFactor) {
this.formFactor = formFactor;
}
public int getCapacity() {
return capacity;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
public String getInterFace() {
return interFace;
}
public void setInterFace(String interFace) {
this.interFace = interFace;
}
public String getBufferSize() {
return bufferSize;
}
public void setBufferSize(String bufferSize) {
this.bufferSize = bufferSize;
}
public void setBrand(Brand brand){
this.brand = brand;
}
public Brand getBrand(){
return brand;
}
public Goods getGoods() {
return goods;
}
public void setGoods(Goods goods) {
this.goods = goods;
}
}
AddHardDrive.java
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.SQLException;
import javax.swing.JComboBox;
public class AddHardDrive extends JFrame {
private JPanel contentPane;
private JTextField nameTextField;
private JComboBox formFactorComboBox;
private JComboBox capacityComboBox;
private JComboBox interFaceComboBox;
private JComboBox bufferSizeComboBox;
private JComboBox brandComboBox;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AddHardDrive frame = new AddHardDrive();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public AddHardDrive() {
String [] formFactor = {"2.5", "3.5"};
String[] capacity = {"250", "320", "500", "750", "1000",
"1250", "1500", "2000", "3000"};
String[] interFaces = {"eSATA", "SATA2", "SATA3","USB 2.0", "USB 3.0"};
String[] bufferSize = {"2 MB", "8 MB", "16 MB","32 MB", "64 MB", "128 MB"};
String[] brands = {"A-DATA","ASUS", "Fujitsu","Hitachi", "IBM", "Samsung",
"Seagate", "Silicon Power","Toshiba", "Transcend", "WD"};
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
nameTextField = new JTextField();
nameTextField.setBounds(213, 8, 211, 20);
contentPane.add(nameTextField);
nameTextField.setColumns(10);
JLabel lblNewLabel = new JLabel("Название :");
lblNewLabel.setBounds(148, 11, 55, 14);
contentPane.add(lblNewLabel);
JLabel lblNewLabel_5 = new JLabel("Форм-фактор :");
lblNewLabel_5.setBounds(127, 36, 76, 14);
contentPane.add(lblNewLabel_5);
JLabel lblNewLabel_1 = new JLabel("Обьем :");
lblNewLabel_1.setBounds(164, 73, 39, 14);
contentPane.add(lblNewLabel_1);
JLabel lblNewLabel_2 = new JLabel("Интерфейс :");
lblNewLabel_2.setBounds(140, 101, 63, 14);
contentPane.add(lblNewLabel_2);
JLabel lblNewLabel_3 = new JLabel("Тип соединения :");
lblNewLabel_3.setBounds(113, 126, 88, 14);
contentPane.add(lblNewLabel_3);
JLabel lblNewLabel_4 = new JLabel("Бренд :");
lblNewLabel_4.setBounds(164, 151, 38, 14);
contentPane.add(lblNewLabel_4);
JButton btnNewButton = new JButton("Добавить");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
HardDrive hardDrive = new HardDrive(nameTextField.getText(),
Double.parseDouble(formFactorComboBox.getSelectedItem().toString()),
Integer.parseInt(capacityComboBox.getSelectedItem().toString()),
interFaceComboBox.getSelectedItem().toString(),bufferSizeComboBox.getSelectedItem().toString(),
brandComboBox.getSelectedItem().toString());
HardDriveDaoImpl hddi = new HardDriveDaoImpl();
hddi.addHardDrive(hardDrive);
} catch (NumberFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnNewButton.setBounds(213, 179, 211, 71);
contentPane.add(btnNewButton);
interFaceComboBox = new JComboBox(interFaces);
interFaceComboBox.setBounds(213, 98, 211, 20);
contentPane.add(interFaceComboBox);
capacityComboBox = new JComboBox(capacity);
capacityComboBox.setBounds(213, 70, 211, 20);
contentPane.add(capacityComboBox);
bufferSizeComboBox = new JComboBox(bufferSize);
bufferSizeComboBox.setBounds(213, 123, 211, 20);
contentPane.add(bufferSizeComboBox);
brandComboBox = new JComboBox(brands);
brandComboBox.setBounds(213, 148, 211, 20);
contentPane.add(brandComboBox);
formFactorComboBox = new JComboBox(formFactor);
formFactorComboBox.setBounds(213, 39, 211, 20);
contentPane.add(formFactorComboBox);
}
}
Error
мар 11, 2015 11:33:23 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
мар 11, 2015 11:33:23 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.7.Final}
мар 11, 2015 11:33:23 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
мар 11, 2015 11:33:23 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
мар 11, 2015 11:33:23 AM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
мар 11, 2015 11:33:23 AM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
мар 11, 2015 11:33:23 AM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
мар 11, 2015 11:33:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
мар 11, 2015 11:33:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/storage]
мар 11, 2015 11:33:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=root, password=****}
мар 11, 2015 11:33:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
мар 11, 2015 11:33:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
мар 11, 2015 11:33:23 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
мар 11, 2015 11:33:23 AM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Exception in thread "AWT-EventQueue-0" java.lang.ExceptionInInitializerError
at HibernateUtil.<clinit>(HibernateUtil.java:30)
at CheckInDatabase.isNameInDataBase(CheckInDatabase.java:27)
at HardDrive.<init>(HardDrive.java:47)
at AddHardDrive$2.actionPerformed(AddHardDrive.java:98)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$400(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: org.hibernate.AnnotationException: #OneToOne or #ManyToOne on HardDrive.goods references an unknown entity: Goods
at org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(ToOneFkSecondPass.java:109)
at org.hibernate.cfg.Configuration.processEndOfQueue(Configuration.java:1598)
at org.hibernate.cfg.Configuration.processFkSecondPassInOrder(Configuration.java:1521)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1422)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1846)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1930)
at HibernateUtil.<clinit>(HibernateUtil.java:28)
... 39 more
The error messages says, that Goods are not mapped. You need to add goods to your hibernate.cfg.xml
<mapping class="main.java.table.Brand"/>
<mapping class="main.java.table.HardDrive"/>
<mapping class="main.java.table.Goods"/>
Related
When i query ` the sql bellow the error keep showing
search = session.createQuery("FROM QLKH_DTO a WHERE a.Fullname LIKE :temp", QLKH_DTO.class)
.setParameter("temp",temp)
.list();
However if it just like this then it does work
search = session.createQuery("FROM QLKH_DTO", QLKH_DTO.class)
.list();
Here my entity class QLKH_DTO
package DTO;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
#Entity
#Table(name = "customers", catalog = "market")
public class QLKH_DTO implements java.io.Serializable {
private Integer CustomerID;
private String Password;
private String Fullname;
private String Address;
private String City;
public QLKH_DTO(){}
public QLKH_DTO(String Password,String Fullname, String Address, String City) {
this.Password = Password;
this.Fullname = Fullname;
this.Address = Address;
this.City = City;
}
#Id
#GeneratedValue(strategy =GenerationType.IDENTITY)
#Column(name = "CustomerID")
public Integer getCustomerID() {
return CustomerID;
}
public void setCustomerID(Integer CustomerID) {
this.CustomerID = CustomerID;
}
#Column(name = "Password")
public String getPassword() {
return Password;
}
public void setPassword(String Password) {
this.Password = Password;
}
#Column(name = "Fullname")
public String getFullname() {
return Fullname;
}
public void setFullname(String Fullname) {
this.Fullname = Fullname;
}
#Column(name = "Address", length = 20)
public String getAddress() {
return Address;
}
public void setAddress(String Address) {
this.Address = Address;
}
#Column(name = "City", length = 20)
public String getCity() {
return City;
}
public void setCity(String City) {
this.City = City;
}
}
The HibernateUtil class
package utils;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
public static SessionFactory buildSessionFactory() {
try {
ServiceRegistry serviceRegistry;
serviceRegistry = new StandardServiceRegistryBuilder()
.configure()
.build();
Metadata metadata = new MetadataSources(serviceRegistry)
.getMetadataBuilder().build();
return metadata.getSessionFactoryBuilder().build();
} catch (Throwable ex) {
}
return sessionFactory;
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
;
The test class
package GUI.QLKH;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import DTO.QLKH_DTO;
import java.util.List;
import utils.HibernateUtil;
public class QLKH {
private static SessionFactory factory;
Session session=null;
// Transaction txn = null;
public static void main(String[] args) {
factory = HibernateUtil.getSessionFactory();
QLKH Customer = new QLKH();
System.out.println("search customers:");
Customer.search();
}
public void search(){
String temp="John";
session = factory.openSession();
session.beginTransaction();
List<QLKH_DTO> search;
search = session.createQuery("FROM QLKH_DTO a WHERE a.Fullname LIKE :temp", QLKH_DTO.class)
.setParameter("temp",temp)
.list();
session.getTransaction().commit();
for (QLKH_DTO customer : search) {
System.out.print("Password: " + customer.getPassword());
System.out.print("Fullname: " + customer.getFullname());
System.out.println("Address: " + customer.getAddress());
System.out.println("City: " + customer.getCity());
}
}
}
The sql
CREATE TABLE `Customers` (
`CustomerID` int(10) NOT NULL auto_increment,
`Password` varchar(20) NOT NULL,
`Fullname` varchar(40) NOT NULL,
`Address` varchar(50) DEFAULT NULL,
`City` varchar(20) DEFAULT NULL,
PRIMARY KEY (CustomerID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `Customers`
--
INSERT INTO `Customers` (`CustomerID`, `Password`, `Fullname`, `Address`, `City`) VALUES
(1, 'Abcd1234', 'John Smith', '30 Broadway', 'London'),
(2, 'Abcd1234', 'Jonny English', '99 River View', 'Reading'),
(3, 'Abcd1234', 'Elizabeth', '23 Buckinghamshire', 'York'),
(4, 'Abcd1234', 'Beatrix', '66 Royal Crescent', 'Bath');
Hibernate.cfg.xml
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/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>
<!-- Assume students is the database name -->
<property name = "hibernate.connection.url">
jdbc:mysql://localhost:3306/market
</property>
<property name = "hibernate.connection.username">
root
</property>
<property name = "hibernate.connection.password">
</property>
<mapping class="DTO.QLKH_DTO" />
</session-factory>
</hibernate-configuration>
And the error log
cd C:\Users\MyPC\Documents\NetBeansProjects\QLKH; "JAVA_HOME=C:\\Program Files\\Java\\jdk-14.0.1" cmd /c "\"C:\\Program Files\\NetBeans-15\\netbeans\\java\\maven\\bin\\mvn.cmd\" -Dexec.vmArgs= \"-Dexec.args=${exec.vmArgs} -classpath %classpath ${exec.mainClass} ${exec.appArgs}\" \"-Dexec.executable=C:\\Program Files\\Java\\jdk-14.0.1\\bin\\java.exe\" -Dexec.mainClass=GUI.QLKH.QLKH -Dexec.classpathScope=runtime -Dexec.appArgs= \"-Dmaven.ext.class.path=C:\\Program Files\\NetBeans-15\\netbeans\\java\\maven-nblib\\netbeans-eventspy.jar\" -Dfile.encoding=UTF-8 org.codehaus.mojo:exec-maven-plugin:3.0.0:exec"
Running NetBeans Compile On Save execution. Phase execution is skipped and output directories of dependency projects (with Compile on Save turned on) will be used instead of their jar artifacts.
Scanning for projects...
------------------------------< GUI:QLKH >------------------------------
Building QLKH 1.0
--------------------------------[ jar ]---------------------------------
--- exec-maven-plugin:3.0.0:exec (default-cli) # QLKH ---
Nov 22, 2022 9:55:29 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate ORM core version 6.1.5.Final
Nov 22, 2022 9:55:31 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using built-in connection pool (not intended for production use)
Nov 22, 2022 9:55:31 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: Loaded JDBC driver class: com.mysql.jdbc.Driver
Nov 22, 2022 9:55:31 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001012: Connecting with JDBC URL [jdbc:mysql://localhost:3306/market]
Nov 22, 2022 9:55:31 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {password=****, user=root}
Nov 22, 2022 9:55:31 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Nov 22, 2022 9:55:31 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH10001115: Connection pool size: 20 (min=1)
Nov 22, 2022 9:55:32 AM org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl logSelectedDialect
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Nov 22, 2022 9:55:35 AM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
search customers:
Exception in thread "main" java.lang.IllegalArgumentException: org.hibernate.query.sqm.InterpretationException: Error interpreting query [FROM QLKH_DTO a WHERE a.Fullname LIKE :temp]; this may indicate a semantic (user query) problem or a bug in the parser [FROM QLKH_DTO a WHERE a.Fullname LIKE :temp]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:141)
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:127)
at GUI.QLKH.QLKH.search(QLKH.java:28)
at GUI.QLKH.QLKH.main(QLKH.java:21)
Caused by: org.hibernate.query.sqm.InterpretationException: Error interpreting query [FROM QLKH_DTO a WHERE a.Fullname LIKE :temp]; this may indicate a semantic (user query) problem or a bug in the parser [FROM QLKH_DTO a WHERE a.Fullname LIKE :temp]
at org.hibernate.query.hql.internal.StandardHqlTranslator.translate(StandardHqlTranslator.java:97)
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)
... 3 more
Caused by: java.lang.IllegalArgumentException: org.hibernate.query.SemanticException: Could not resolve attribute 'Fullname' of 'DTO.QLKH_DTO'
at org.hibernate.query.sqm.SqmPathSource.getSubPathSource(SqmPathSource.java:61)
at org.hibernate.query.sqm.tree.domain.AbstractSqmPath.get(AbstractSqmPath.java:160)
at org.hibernate.query.sqm.tree.domain.AbstractSqmFrom.resolvePathPart(AbstractSqmFrom.java:192)
at org.hibernate.query.hql.internal.DomainPathPart.resolvePathPart(DomainPathPart.java:42)
at org.hibernate.query.hql.internal.BasicDotIdentifierConsumer.consumeIdentifier(BasicDotIdentifierConsumer.java:91)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitSimplePath(SemanticQueryBuilder.java:4808)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitIndexedPathAccessFragment(SemanticQueryBuilder.java:4755)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitGeneralPathFragment(SemanticQueryBuilder.java:4724)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitGeneralPathExpression(SemanticQueryBuilder.java:1423)
at org.hibernate.grammars.hql.HqlParser$GeneralPathExpressionContext.accept(HqlParser.java:6963)
at org.antlr.v4.runtime.tree.AbstractParseTreeVisitor.visitChildren(AbstractParseTreeVisitor.java:46)
at org.hibernate.grammars.hql.HqlParserBaseVisitor.visitBarePrimaryExpression(HqlParserBaseVisitor.java:671)
at org.hibernate.grammars.hql.HqlParser$BarePrimaryExpressionContext.accept(HqlParser.java:6437)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitLikePredicate(SemanticQueryBuilder.java:2217)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitLikePredicate(SemanticQueryBuilder.java:243)
at org.hibernate.grammars.hql.HqlParser$LikePredicateContext.accept(HqlParser.java:5442)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitWhereClause(SemanticQueryBuilder.java:1949)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitWhereClause(SemanticQueryBuilder.java:243)
at org.hibernate.grammars.hql.HqlParser$WhereClauseContext.accept(HqlParser.java:5290)
at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitQuery(SemanticQueryBuilder.java:857)
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)
... 7 more
Caused by: org.hibernate.query.SemanticException: Could not resolve attribute 'Fullname' of 'DTO.QLKH_DTO'
... 37 more
Command execution failed.
org.apache.commons.exec.ExecuteException: Process exited with an error: 1 (Exit value: 1)
at org.apache.commons.exec.DefaultExecutor.executeInternal (DefaultExecutor.java:404)
at org.apache.commons.exec.DefaultExecutor.execute (DefaultExecutor.java:166)
at org.codehaus.mojo.exec.ExecMojo.executeCommandLine (ExecMojo.java:982)
at org.codehaus.mojo.exec.ExecMojo.executeCommandLine (ExecMojo.java:929)
at org.codehaus.mojo.exec.ExecMojo.execute (ExecMojo.java:457)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
at org.apache.maven.lifecycle.internal.MojoExecutor.doExecute2 (MojoExecutor.java:370)
at org.apache.maven.lifecycle.internal.MojoExecutor.doExecute (MojoExecutor.java:351)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:215)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:171)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:163)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:294)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
at org.apache.maven.cli.MavenCli.execute (MavenCli.java:960)
at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:293)
at org.apache.maven.cli.MavenCli.main (MavenCli.java:196)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke (Method.java:564)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
------------------------------------------------------------------------
BUILD FAILURE
------------------------------------------------------------------------
Total time: 12.026 s
Finished at: 2022-11-22T09:55:37+07:00
------------------------------------------------------------------------
Failed to execute goal org.codehaus.mojo:exec-maven-plugin:3.0.0:exec (default-cli) on project QLKH: Command execution failed.: Process exited with an error: 1 (Exit value: 1) -> [Help 1]
To see the full stack trace of the errors, re-run Maven with the -e switch.
Re-run Maven using the -X switch to enable full debug logging.
For more information about the errors and possible solutions, please read the following articles:
[Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
`
I don't know what wrong,i have try another propety like City,Password and it could not reslove the propety too.Eventhough make the propety name and name in database the same to avoid error
I solved the problem,it because I tagged the #column in the wrong place
#Table(name = "customers", catalog = "market")
public class QLKH_DTO implements java.io.Serializable {
#Id
#GeneratedValue(strategy =GenerationType.IDENTITY)
#Column(name = "CustomerID")
private Integer CustomerID;
#Column(name = "Password")
private String Password;
#Column(name = "Fullname")
private String Fullname;
#Column(name = "Address")
private String Address;
#Column(name = "City")
private String City;
public QLKH_DTO(){}
public QLKH_DTO(String Password,String Fullname, String Address, String City) {
this.Password = Password;
this.Fullname = Fullname;
this.Address = Address;
this.City = City;
}
public Integer getCustomerID() {
return this.CustomerID;
}
public void setCustomerID(Integer CustomerID) {
this.CustomerID = CustomerID;
}
public String getPassword() {
return this.Password;
}
public void setPassword(String Password) {
this.Password = Password;
}
public String getFullname() {
return this.Fullname;
}
public void setFullname(String Fullname) {
this.Fullname = Fullname;
}
public String getAddress() {
return this.Address;
}
public void setAddress(String Address) {
this.Address = Address;
}
public String getCity() {
return this.City;
}
public void setCity(String City) {
this.City = City;
}
}
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
I am trying to connect to a database that I created with java in eclipse using hibernate. It is supposed to connect to the payroll database and insert records into the student table but I am getting this error! I inserted the jdbc connect and the other required jar files. I am not sure why it's not working. Please help.
Error:
Jul 14, 2022 2:34:10 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate ORM core version 5.5.3.Final
Jul 14, 2022 2:34:11 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
Jul 14, 2022 2:34:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
Jul 14, 2022 2:34:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/payroll]
Jul 14, 2022 2:34:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
Jul 14, 2022 2:34:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Jul 14, 2022 2:34:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 3 (min=1)
Jul 14, 2022 2:34:11 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
Jul 14, 2022 2:34:11 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#304b9f1a] 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.
Hibernate:
select
student0_.id as id1_0_,
student0_.email as email2_0_,
student0_.first_name as first_na3_0_,
student0_.last_name as last_nam4_0_
from
student student0_
Hibernate:
select
student0_.id as id1_0_0_,
student0_.email as email2_0_0_,
student0_.first_name as first_na3_0_0_,
student0_.last_name as last_nam4_0_0_
from
student student0_
where
student0_.id=?
Exception in thread "main" java.lang.IllegalStateException: org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl#5eb97ced is closed
at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.errorIfClosed(AbstractLogicalConnectionImplementor.java:37)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:137)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getConnectionForTransactionManagement(LogicalConnectionManagedImpl.java:276)
at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.rollback(AbstractLogicalConnectionImplementor.java:121)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.rollback(JdbcResourceLocalTransactionCoordinatorImpl.java:304)
at org.hibernate.engine.transaction.internal.TransactionImpl.rollback(TransactionImpl.java:142)
at models.Student.get(Student.java:131)
at Driver.main(Driver.java:24)
Driver Class(driver.java)
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.*;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import models.Student;
public class Driver {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student stu =new Student();//1,"Simone","Charles","#Home");
//stu.create();
List<Student> students=stu.readAll();
for(Student s: students) {
System.out.println(s.getFirstName());
}
Student s1=stu.get(4);
System.out.println(s1.getFirstName());
//sstu.delete(2);
//getCurrentSessionFromConfig();
}
public static Session getCurrentSessionFromConfig() {
// SessionFactory in Hibernate 5 example
Configuration config = new Configuration();
config.configure();
// local SessionFactory bean created
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
return session;
}
public static Session getCurrentSessionX() {
// Hibernate 5.4 SessionFactory example without XML
Map<String, String> settings = new HashMap<>();
settings.put("connection.driver_class", "com.mysql.jdbc.Driver");
settings.put("dialect", "org.hibernate.dialect.MySQL8Dialect");
settings.put("hibernate.connection.url",
"jdbc:mysql://localhost/hibernate_examples");
settings.put("hibernate.connection.username", "root");
settings.put("hibernate.connection.password", "");
settings.put("hibernate.current_session_context_class", "thread");
settings.put("hibernate.show_sql", "true");
settings.put("hibernate.format_sql", "true");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(settings).build();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
// metadataSources.addAnnotatedClass(Player.class);
Metadata metadata = metadataSources.buildMetadata();
// here we build the SessionFactory (Hibernate 5.4)
SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build();
Session session = sessionFactory.getCurrentSession();
return session;
}
}
Hibernate xml file
<?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">
<!-- Version 8 MySQL hiberante-cfg.xml example for Hibernate 5 -->
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- property name="connection.driver_class">com.mysql.jdbc.Driver</property -->
<property name="connection.url">jdbc:mysql://localhost/payroll</property>
<property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="connection.pool_size">3</property>
<!--property name="dialect">org.hibernate.dialect.MySQLDialect</property-->
<property name="current_session_context_class">thread</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<!-- mapping class="com.mcnz.jpa.examples.Player" / -->
<mapping class="models.Student" />
</session-factory>
</hibernate-configuration>
SessionBuilder File
package factories;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import models.Student;
public class SessionFactoryBuilder {
private static SessionFactory sessionFactory = null;
public static SessionFactory getSessionFactory () {
if(sessionFactory==null) {
try {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
sessionFactory = cfg.buildSessionFactory();
// session =sessionFactory.openSession();
/* sessionFactory =new
Configuration().configure("hibernate.cfg.xml").addAnnotatedClass
(Student.class).buildSessionFactory();
*/
}catch(RuntimeException e) {System.out.println(e.toString());}
}
return sessionFactory;
}
public static void closeSessionFactory () {
if(sessionFactory!=null) {
sessionFactory.close();
}
}
}
Student Class
package models;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.*;
import org.hibernate.Session;
import org.hibernate.Transaction;
import factories.SessionFactoryBuilder;
#Entity
#Table(name="student")
public class Student {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
int id;
#Column(name="first_name")
String firstName;
#Column(name="last_name")
String lastName;
#Column(name="email")
String email;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(int id, String firstName, String lastName, String email) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public void create() {
Session session =SessionFactoryBuilder.getSessionFactory().getCurrentSession();
Transaction transaction= session.beginTransaction();
//Student stu=(Student) session.get(Student.class, this.id);
//stu.setFirstName(firstName);
//stu.setLastName(lastName);
session.save(this);
transaction.commit();
session.close();
}
public List<Student> readAll(){
List<Student> studentList=new ArrayList<>();
Session session =SessionFactoryBuilder.getSessionFactory().getCurrentSession();
Transaction transaction= session.beginTransaction();
studentList=(List<Student>) session.createQuery("From Student").getResultList();
transaction.commit();
session.close();
return studentList;
}
public void delete(int id) {
Session session =SessionFactoryBuilder.getSessionFactory()
.getCurrentSession();
Transaction transaction= session.beginTransaction();
//Student stu=(Student) session.get(Student.class, this.id);
//session.delete(stu);
// Delete a persistent object
Student student = session.get(Student.class, id);
if (student != null) {
session.delete(student);
System.out.println("student deleted");
}
// Delete a transient object
/* Student student2 = new Student();
student2.setId(2);
session.delete(student2);
System.out.println("Student 2 is deleted");
*/
transaction.commit();
session.close();
}
public void update() {
Session session =SessionFactoryBuilder.getSessionFactory()
.getCurrentSession();
Transaction transaction= session.beginTransaction();
//Student stu=(Student) session.get(Student.class, this.id);
session.update(this);
transaction.commit();
session.close();
}
public Student get(int id) {
Student stu=null;
Transaction transaction=null;
try(Session session =SessionFactoryBuilder.getSessionFactory()
.getCurrentSession()){
transaction= session.beginTransaction();
stu=(Student) session.get(Student.class, id);
session.delete(stu);
transaction.commit();
}catch(Exception e) {
if(transaction!=null) {
transaction.rollback();
}
e.printStackTrace();
}
return stu;
}
}
I'm beginner in JPA and hibernate and I'm just trying to fetch some data from my DB via hibernate but I failed and I got this error :
Apr 29, 2019 5:14:28 AM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing qPersistenceUnitInfo [name: NewPersistenceUnit]
Apr 29, 2019 5:14:29 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.4.2.Final}
Apr 29, 2019 5:14:29 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
Apr 29, 2019 5:14:30 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
Apr 29, 2019 5:14:30 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/shopping]
Apr 29, 2019 5:14:30 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
Apr 29, 2019 5:14:30 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Apr 29, 2019 5:14:30 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Apr 29, 2019 5:14:32 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
Apr 29, 2019 5:14:33 AM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#35e478f] 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.
Apr 29, 2019 5:14:33 AM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
Hibernate:
select
itemclass0_.id as id1_0_0_,
itemclass0_.author as author2_0_0_,
itemclass0_.available_amount as availabl3_0_0_,
itemclass0_.bought as bought4_0_0_,
itemclass0_.imageURL as imageURL5_0_0_,
itemclass0_.name as name6_0_0_,
itemclass0_.price as price7_0_0_,
itemclass0_.publish_time as publish_8_0_0_
from
item itemclass0_
where
itemclass0_.id=?
Apr 29, 2019 5:14:33 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: S1009
Apr 29, 2019 5:14:33 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: MONTH
Apr 29, 2019 5:14:33 AM org.hibernate.event.internal.DefaultLoadEventListener doOnLoad
INFO: HHH000327: Error performing load command : org.hibernate.exception.GenericJDBCException: Could not read entity state from ResultSet : EntityKey[entities.ItemClass#58]
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not read entity state from ResultSet : EntityKey[entities.ItemClass#58]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154)
at org.hibernate.internal.SessionImpl.find(SessionImpl.java:3581)
at org.hibernate.internal.SessionImpl.find(SessionImpl.java:3519)
at Test.main(Test.java:17)
Caused by: org.hibernate.exception.GenericJDBCException: Could not read entity state from ResultSet : EntityKey[entities.ItemClass#58]
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
at org.hibernate.loader.plan.exec.process.internal.EntityReferenceInitializerImpl.loadFromResultSet(EntityReferenceInitializerImpl.java:320)
at org.hibernate.loader.plan.exec.process.internal.EntityReferenceInitializerImpl.hydrateEntityState(EntityReferenceInitializerImpl.java:233)
at org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.readRow(AbstractRowReader.java:103)
at org.hibernate.loader.plan.exec.internal.EntityLoadQueryDetails$EntityLoaderRowReader.readRow(EntityLoadQueryDetails.java:254)
at org.hibernate.loader.plan.exec.process.internal.ResultSetProcessorImpl.extractResults(ResultSetProcessorImpl.java:122)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:122)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:86)
at org.hibernate.loader.entity.plan.AbstractLoadPlanBasedEntityLoader.load(AbstractLoadPlanBasedEntityLoader.java:197)
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:4279)
at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:482)
at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:452)
at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:203)
at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:262)
at org.hibernate.event.internal.DefaultLoadEventListener.doOnLoad(DefaultLoadEventListener.java:105)
at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1287)
at org.hibernate.internal.SessionImpl.access$2100(SessionImpl.java:212)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.doLoad(SessionImpl.java:2930)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.lambda$load$1(SessionImpl.java:2911)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.perform(SessionImpl.java:2867)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2911)
at org.hibernate.internal.SessionImpl.find(SessionImpl.java:3552)
... 2 more
Caused by: java.sql.SQLException: MONTH
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:73)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:85)
at com.mysql.cj.jdbc.result.ResultSetImpl.getDate(ResultSetImpl.java:847)
at com.mysql.cj.jdbc.result.ResultSetImpl.getDate(ResultSetImpl.java:860)
at org.hibernate.type.descriptor.sql.DateTypeDescriptor$2.doExtract(DateTypeDescriptor.java:76)
at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:47)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:257)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:253)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:243)
at org.hibernate.type.AbstractStandardBasicType.hydrate(AbstractStandardBasicType.java:329)
at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:3014)
at org.hibernate.loader.plan.exec.process.internal.EntityReferenceInitializerImpl.loadFromResultSet(EntityReferenceInitializerImpl.java:305)
... 23 more
Caused by: com.mysql.cj.exceptions.WrongArgumentException: MONTH
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)
at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:105)
at com.mysql.cj.result.SqlDateValueFactory.createFromDate(SqlDateValueFactory.java:80)
at com.mysql.cj.result.SqlDateValueFactory.createFromDate(SqlDateValueFactory.java:46)
at com.mysql.cj.result.BaseDecoratingValueFactory.createFromDate(BaseDecoratingValueFactory.java:53)
at com.mysql.cj.result.BaseDecoratingValueFactory.createFromDate(BaseDecoratingValueFactory.java:53)
at com.mysql.cj.protocol.a.MysqlTextValueDecoder.decodeDate(MysqlTextValueDecoder.java:72)
at com.mysql.cj.protocol.result.AbstractResultsetRow.decodeAndCreateReturnValue(AbstractResultsetRow.java:90)
at com.mysql.cj.protocol.result.AbstractResultsetRow.getValueFromBytes(AbstractResultsetRow.java:250)
at com.mysql.cj.protocol.a.result.ByteArrayRow.getValue(ByteArrayRow.java:91)
at com.mysql.cj.jdbc.result.ResultSetImpl.getNonStringValueFromRow(ResultSetImpl.java:656)
at com.mysql.cj.jdbc.result.ResultSetImpl.getDateOrTimestampValueFromRow(ResultSetImpl.java:679)
... 33 more
Caused by: java.lang.IllegalArgumentException: MONTH
at java.util.GregorianCalendar.computeTime(GregorianCalendar.java:2648)
at java.util.Calendar.updateTime(Calendar.java:3393)
at java.util.Calendar.getTimeInMillis(Calendar.java:1782)
at com.mysql.cj.result.SqlDateValueFactory.createFromDate(SqlDateValueFactory.java:77)
... 42 more
Process finished with exit code 1
and Also type of publish_time column is date.
Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="NewPersistenceUnit">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>entities.ItemClass</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/shopping"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value="****"/>
<property name="hibernate.archive.autodetection" value="class"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
This is my Entity Class
ItemClass.java
package entities;
import javax.persistence.*;
import java.sql.Date;
import java.util.Objects;
#Entity
#Table(name = "item", schema = "shopping", catalog = "")
public class ItemClass {
private int id;
private String name;
private Integer price;
private String imageUrl;
private Integer availableAmount;
private Integer bought;
#Temporal(TemporalType.TIMESTAMP)
private Date publishTime;
private String author;
#Id
#Column(name = "id", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "name", nullable = false, length = 45)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Basic
#Column(name = "price", nullable = true)
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
#Basic
#Column(name = "imageURL", nullable = true, length = 45)
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
#Basic
#Column(name = "available_amount", nullable = true)
public Integer getAvailableAmount() {
return availableAmount;
}
public void setAvailableAmount(Integer availableAmount) {
this.availableAmount = availableAmount;
}
#Basic
#Column(name = "bought", nullable = true)
public Integer getBought() {
return bought;
}
public void setBought(Integer bought) {
this.bought = bought;
}
#Basic
#Column(name = "publish_time", nullable = true)
public Date getPublishTime() {
return publishTime;
}
public void setPublishTime(Date publishTime) {
this.publishTime = publishTime;
}
#Basic
#Column(name = "author", nullable = false, length = 45)
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ItemClass itemClass = (ItemClass) o;
return id == itemClass.id &&
Objects.equals(name, itemClass.name) &&
Objects.equals(price, itemClass.price) &&
Objects.equals(imageUrl, itemClass.imageUrl) &&
Objects.equals(availableAmount, itemClass.availableAmount) &&
Objects.equals(bought, itemClass.bought) &&
Objects.equals(publishTime, itemClass.publishTime) &&
Objects.equals(author, itemClass.author);
}
#Override
public int hashCode() {
return Objects.hash(id, name, price, imageUrl, availableAmount, bought, publishTime, author);
}
}
Test.java
import entities.ItemClass;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Test {
public static void main(String[] args) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("NewPersistenceUnit");
EntityManager entityManager = entityManagerFactory.createEntityManager();
ItemClass item = entityManager.find(ItemClass.class,58);
System.out.println(item.getAuthor());
}
}
I reviewed another questions that were similar to my title but It doesn't help.
can anyone plz help me to solve this issue ?
UPDATE
These are my rows with publish_time columns:
My Table
This is likely a data issue (in the database table).
A mysql table could contain datetime / timestamp entries like 2019-00-00. While such dates are valid in mysql (depending on the server version and mode), they will cause an exception when the mysql driver tries to parse them into Java dates.
Double check that the rows you are trying to retrieve have valid dates in the publish_time column.
ps. if you have all zero dates (0000-00-00 00:00:00) then you can use the zeroDateTimeBehavior property in the connection string to handle them more gracefully without changing the database values.
the system that I'm implementing is composed of:
Eclipse Neon 4.6 + maven (integreted) + Hibernate 5.2.2 + Mysql (i use MySql Workbench 6.3)
algorithm:
I tried to create this java application on eclipse:
a student entity and an address entity (the some address can be used for many students)
info:
I created only a htmanytoone schemas on mysql, and I want hibernate it to take care of creation and management of the entities on.
I hope there are no problems of continuity (I modified the code several times )
My project on eclipse:
Package Explorer
Student.java:
package withMaven.hibernateMaven1;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "student")
public class Student {
private long studentId;
private String studentName;
private Address studentAddress;
public Student() {
}
public Student(String studentName, Address studentAddress) {
this.studentName = studentName;
this.studentAddress = studentAddress;
}
#Id
#GeneratedValue
#Column(name = "student_id")
public long getStudentId() {
return this.studentId;
}
public void setStudentId(long studentId) {
this.studentId = studentId;
}
#Column(name = "student_name")//, nullable = false, length = 100)
public String getStudentName() {
return this.studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
#ManyToOne(cascade = CascadeType.ALL)
public Address getStudentAddress() {
return this.studentAddress;
}
public void setStudentAddress(Address studentAddress) {
this.studentAddress = studentAddress;
}
}
Address.java:
package withMaven.hibernateMaven1;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "address")
public class Address {
private long addressId;
private String street;
private String city;
private String state;
private String zipcode;
public Address() {
}
public Address(String street, String city, String state, String zipcode) {
this.street = street;
this.city = city;
this.state = state;
this.zipcode = zipcode;
}
#Id
#GeneratedValue
#Column(name = "adderess_id")
public long getAddressId() {
return this.addressId;
}
public void setAddressId(long addressId) {
this.addressId = addressId;
}
//#Column(name = "address_street", nullable = false, length=250)
#Column(name = "address_street")
public String getStreet() {
return this.street;
}
public void setStreet(String street) {
this.street = street;
}
//#Column(name = "address_city", nullable = false, length=50)
#Column(name = "address_city")
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
//#Column(name = "address_state", nullable = false, length=50)
#Column(name = "address_state")
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
#Column(name = "address_zipcode")//, nullable = false, length=10)
public String getZipcode() {
return this.zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
}
play.java: (the test main)
package withMaven.hibernateMaven1;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class play {
public static void main(String[] args) {
SessionFactory factory = new Configuration().configure().buildSessionFactory();
Session session=factory.getCurrentSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Address address = new Address("OMR Road", "Chennai", "TN", "600097");
Student student1 = new Student("Eswar", address);
Student student2 = new Student("Joe", address);
session.save(student1);
session.save(student2);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}
hibernate.cfx.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"> org.hsqldb.jdbcDriver</property>
<property name="hibernate.connection.url"> jdbc:hsqldb:hsql://3306/htmanytoone?useSSL=false</property>
<property name="hibernate.connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping class="Student" />
<mapping class="Address" />
</session-factory>
</hibernate-configuration>
the pom.xml: (I use maven because it is recommended, but I have no experience with it)
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>withMaven</groupId>
<artifactId>prova1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>proviamo maven</name>
<description>primo utilizzo con maven</description>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.2.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.31</version>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.3.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
and now the console when i run play.java:
Sep 07, 2016 10:12:09 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.2.Final}
Sep 07, 2016 10:12:09 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Sep 07, 2016 10:12:09 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Sep 07, 2016 10:12:09 AM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-configuration. Use namespace http://www.hibernate.org/dtd/hibernate-configuration instead. Support for obsolete DTD/XSD namespaces may be removed at any time.
Sep 07, 2016 10:12:09 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Sep 07, 2016 10:12:09 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Sep 07, 2016 10:12:09 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.hsqldb.jdbcDriver] at URL [jdbc:hsqldb:hsql://3306/htmanytoone?useSSL=false]
Sep 07, 2016 10:12:09 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
Sep 07, 2016 10:12:09 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Sep 07, 2016 10:12:09 AM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
Exception in thread "main" org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:267)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:231)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:240)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:691)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
at withMaven.hibernateMaven1.play.main(play.java:13)
Caused by: org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:115)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.convert(BasicConnectionCreator.java:101)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:123)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:41)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:58)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections.addConnections(PooledConnections.java:123)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections.<init>(PooledConnections.java:42)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections.<init>(PooledConnections.java:20)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections$Builder.build(PooledConnections.java:161)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildPool(DriverManagerConnectionProviderImpl.java:109)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:72)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:240)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.buildJdbcConnectionAccess(JdbcEnvironmentInitiator.java:145)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:66)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:257)
... 14 more
Caused by: java.sql.SQLTransientConnectionException: java.net.SocketException: Network is unreachable: connect
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCConnection.<init>(Unknown Source)
at org.hsqldb.jdbc.JDBCDriver.getConnection(Unknown Source)
at org.hsqldb.jdbc.JDBCDriver.connect(Unknown Source)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:38)
... 29 more
Caused by: org.hsqldb.HsqlException: java.net.SocketException: Network is unreachable: connect
at org.hsqldb.ClientConnection.openConnection(Unknown Source)
at org.hsqldb.ClientConnection.initConnection(Unknown Source)
at org.hsqldb.ClientConnection.<init>(Unknown Source)
... 33 more
Caused by: java.net.SocketException: Network is unreachable: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at org.hsqldb.server.HsqlSocketFactory.createSocket(Unknown Source)
... 36 more
If you want to use mysql, you have to Change this lines:
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/htmanytoone?useSSL=false</property>