无法理解我做错了什么。
在线程中有一个例外" AWT-EventQueue-0" java.lang.ExceptionInInitializerError
我认为这是sessionFactory的一个问题,但无法理解如何解决它。
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);
}
}
错误
мар 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
答案 0 :(得分:0)
错误消息显示,商品未映射。您需要将商品添加到您的hibernate.cfg.xml
<mapping class="main.java.table.Brand"/>
<mapping class="main.java.table.HardDrive"/>
<mapping class="main.java.table.Goods"/>