1. ホーム
  2. java

[解決済み] Hibernateユーティリティクラス

2022-02-07 14:30:15

質問

私は、データベースに多くの変更を加えたため、持っているJavaアプリを書き直そうとしています。 私は持っていたHibernateUtilクラスのコピー/ペーストを私の新しいアプリに行いました。そして、それはちょうど動作しないようです:( )。

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();

    private static SessionFactory sessionFactory = null;
    static {
        sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
    }

    public static Session getSession() {

        Session session = null;
        if (threadLocal.get() == null) {
            // Create Session object
            session = sessionFactory.openSession();
            threadLocal.set(session);
        } else {
            session = threadLocal.get();
        }
        return session;
    }

    public static void closeSession() {
        Session session = null;
        if (threadLocal.get() != null) {
            session = threadLocal.get();
            session.close();
            threadLocal.remove();
        }
    }

    public static void closeSessionFactory() {
        sessionFactory.close();
    }
}


これが私の得たエラーです。

Exception in thread "Thread-1" Exception in Application constructor
java.lang.ExceptionInInitializerError
    at Mach.lambda$main$0(Mach.java:58)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: org.hibernate.MappingException: property mapping has wrong number of columns: Entities.ObjectEntity.info type: object
    at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:629)
    at org.hibernate.mapping.RootClass.validate(RootClass.java:267)
    at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:351)
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:464)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
    at Utility.HibernateUtil.<clinit>(HibernateUtil.java:12)
    ... 2 more
java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:473)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:372)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Unable to construct Application instance: class Mach
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:963)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:198)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:875)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$11(PlatformImpl.java:449)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$9(PlatformImpl.java:418)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:417)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:175)
    ... 1 more
Caused by: java.lang.NoClassDefFoundError: Could not initialize class Utility.HibernateUtil
    at Models.UserIM.<init>(UserIM.java:18)
    at Mach.<init>(Mach.java:30)
    ... 13 more
Exception running application Mach

また、私自身のビルドを手伝っていただけると本当にありがたいです。とはいえ、今のところ、私は自分のアプリを完成させたいだけなのですが。私は新しい要求のためにデータベースを再構築するために何日も働きました、私はほとんどすべてのコードを準備しました、そして私はこのことで立ち往生しています:/悪い感じです。 私はすでに私のhibernate.cfg.xmlファイルをチェックし、大丈夫なようです!私は、このアプリを完成させたいと思います。

これが私のEntityクラスです。

package Entities;

import javax.persistence.*;
import java.math.BigDecimal;
import java.util.Objects;

@Entity
@Table(name = "user_is_worker", schema = "walker", catalog = "")
public class UserIsWorkerEntity {
    private String workerId;
    private String userLogName;
    private String userLogPass;
    private String amka;
    private String afm;
    private BigDecimal salary;
    private Byte bonusProgram;
    private UserEntity userByWorkerId;
    private UserIsWorkerEntity userIsWorkerBySupervisor;
    private PermisEntity permisByPermisId;

    @Id
    @Column(name = "WorkerID", nullable = false, length = 20)
    public String getWorkerId() {
        return workerId;
    }

    public void setWorkerId(String workerId) {
        this.workerId = workerId;
    }

    @Basic
    @Column(name = "UserLogName", nullable = true, length = 15)
    public String getUserLogName() {
        return userLogName;
    }

    public void setUserLogName(String userLogName) {
        this.userLogName = userLogName;
    }

    @Basic
    @Column(name = "UserLogPass", nullable = true, length = 15)
    public String getUserLogPass() {
        return userLogPass;
    }

    public void setUserLogPass(String userLogPass) {
        this.userLogPass = userLogPass;
    }

    @Basic
    @Column(name = "AMKA", nullable = true, length = 12)
    public String getAmka() {
        return amka;
    }

    public void setAmka(String amka) {
        this.amka = amka;
    }

    @Basic
    @Column(name = "AFM", nullable = true, length = 9)
    public String getAfm() {
        return afm;
    }

    public void setAfm(String afm) {
        this.afm = afm;
    }

    @Basic
    @Column(name = "Salary", nullable = true, precision = 2)
    public BigDecimal getSalary() {
        return salary;
    }

    public void setSalary(BigDecimal salary) {
        this.salary = salary;
    }

    @Basic
    @Column(name = "BonusProgram", nullable = true)
    public Byte getBonusProgram() {
        return bonusProgram;
    }

    public void setBonusProgram(Byte bonusProgram) {
        this.bonusProgram = bonusProgram;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        UserIsWorkerEntity that = (UserIsWorkerEntity) o;
        return Objects.equals(workerId, that.workerId) &&
                Objects.equals(userLogName, that.userLogName) &&
                Objects.equals(userLogPass, that.userLogPass) &&
                Objects.equals(amka, that.amka) &&
                Objects.equals(afm, that.afm) &&
                Objects.equals(salary, that.salary) &&
                Objects.equals(bonusProgram, that.bonusProgram);
    }

    @Override
    public int hashCode() {
        return Objects.hash(workerId, userLogName, userLogPass, amka, afm, salary, bonusProgram);
    }

    @OneToOne
    @JoinColumn(name = "WorkerID", referencedColumnName = "UserID", nullable = false)
    public UserEntity getUserByWorkerId() {
        return userByWorkerId;
    }

    public void setUserByWorkerId(UserEntity userByWorkerId) {
        this.userByWorkerId = userByWorkerId;
    }

    @ManyToOne
    @JoinColumn(name = "Supervisor", referencedColumnName = "WorkerID")
    public UserIsWorkerEntity getUserIsWorkerBySupervisor() {
        return userIsWorkerBySupervisor;
    }

    public void setUserIsWorkerBySupervisor(UserIsWorkerEntity userIsWorkerBySupervisor) {
        this.userIsWorkerBySupervisor = userIsWorkerBySupervisor;
    }

    @ManyToOne
    @JoinColumn(name = "PermisID", referencedColumnName = "PermisID")
    public PermisEntity getPermisByPermisId() {
        return permisByPermisId;
    }

    public void setPermisByPermisId(PermisEntity permisByPermisId) {
        this.permisByPermisId = permisByPermisId;
    }
}


そして、これが前のテーブルと関連するEntityです。

package Entities;

import javax.persistence.*;
import java.sql.Date;
import java.util.Objects;

@Entity
@Table(name = "user", schema = "walker", catalog = "")
public class UserEntity {
    private String userId;
    private String name;
    private String surname;
    private Date birthday;
    private UserIsShopkeeperEntity userIsShopkeeperByUserId;
    private UserIsWorkerEntity userIsWorkerByUserId;

    @Id
    @Column(name = "UserID", nullable = false, length = 20)
    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    @Basic
    @Column(name = "Name", nullable = true, length = 35)
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Basic
    @Column(name = "Surname", nullable = true, length = 35)
    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    @Basic
    @Column(name = "Birthday", nullable = true)
    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        UserEntity that = (UserEntity) o;
        return Objects.equals(userId, that.userId) &&
                Objects.equals(name, that.name) &&
                Objects.equals(surname, that.surname) &&
                Objects.equals(birthday, that.birthday);
    }

    @Override
    public int hashCode() {
        return Objects.hash(userId, name, surname, birthday);
    }

    @OneToOne(mappedBy = "userByShopKeeperId")
    public UserIsShopkeeperEntity getUserIsShopkeeperByUserId() {
        return userIsShopkeeperByUserId;
    }

    public void setUserIsShopkeeperByUserId(UserIsShopkeeperEntity userIsShopkeeperByUserId) {
        this.userIsShopkeeperByUserId = userIsShopkeeperByUserId;
    }

    @OneToOne(mappedBy = "userByWorkerId")
    public UserIsWorkerEntity getUserIsWorkerByUserId() {
        return userIsWorkerByUserId;
    }

    public void setUserIsWorkerByUserId(UserIsWorkerEntity userIsWorkerByUserId) {
        this.userIsWorkerByUserId = userIsWorkerByUserId;
    }
}


そして最後に、これは私のhibernate.cfg.xmlファイルです。

<?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:mysql://localhost:3306/walker</property>

        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>

        <property name="format_sql">true</property>
        <property name="show_sql">true</property>

        <mapping class="Entities.ActivationEntity"/>
        <mapping class="Entities.AutomaticSoftwareEntity"/>
        <mapping class="Entities.CanisterEntity"/>
        <mapping class="Entities.ChargeEntity"/>
        <mapping class="Entities.CityEntity"/>
        <mapping class="Entities.ColorVersionEntity"/>
        <mapping class="Entities.CompanyEntity"/>
        <mapping class="Entities.ComTypeEntity"/>
        <mapping class="Entities.ContractEntity"/>
        <mapping class="Entities.ContractEventEntity"/>
        <mapping class="Entities.CountryEntity"/>
        <mapping class="Entities.CustomerEntity"/>
        <mapping class="Entities.CustomerHasRequestsEntity"/>
        <mapping class="Entities.CustomerHasShopkeepersEntity"/>
        <mapping class="Entities.CustomerHasTargetsEntity"/>
        <mapping class="Entities.CustomerHasVersionsEntity"/>
        <mapping class="Entities.DepartmentEntity"/>
        <mapping class="Entities.DispenserTechEntity"/>
        <mapping class="Entities.EventEntity"/>
        <mapping class="Entities.MachineAgeEntity"/>
        <mapping class="Entities.MailEntity"/>
        <mapping class="Entities.ModelEntity"/>
        <mapping class="Entities.ModelHasPartsEntity"/>
        <mapping class="Entities.ModelDispenserEntity"/>
        <mapping class="Entities.ModelPartEntity"/>
        <mapping class="Entities.ModelRootEntity"/>
        <mapping class="Entities.ModelTypeEntity"/>
        <mapping class="Entities.MonitorEntity"/>
        <mapping class="Entities.MonitorPanelEntity"/>
        <mapping class="Entities.ObjectEntity"/>
        <mapping class="Entities.ObjectEventEntity"/>
        <mapping class="Entities.PartEntity"/>
        <mapping class="Entities.PcEntity"/>
        <mapping class="Entities.PermisEntity"/>
        <mapping class="Entities.PhoneEntity"/>
        <mapping class="Entities.PrinterEntity"/>
        <mapping class="Entities.PriorityEntity"/>
        <mapping class="Entities.PumpEntity"/>
        <mapping class="Entities.RegionEntity"/>
        <mapping class="Entities.RequestsEntity"/>
        <mapping class="Entities.RoleEntity"/>
        <mapping class="Entities.SectionEntity"/>
        <mapping class="Entities.ShakerEntity"/>
        <mapping class="Entities.ShakerTypeEntity"/>
        <mapping class="Entities.ShelfEntity"/>
        <mapping class="Entities.SpectroEntity"/>
        <mapping class="Entities.StatusEntity"/>
        <mapping class="Entities.StatusHasStoreEntity"/>
        <mapping class="Entities.StoreEntity"/>
        <mapping class="Entities.SupplierEntity"/>
        <mapping class="Entities.SupplierHasVendorsEntity"/>
        <mapping class="Entities.TeamviewerEntity"/>
        <mapping class="Entities.UpsEntity"/>
        <mapping class="Entities.UserEntity"/>
        <mapping class="Entities.UserHasEmailsEntity"/>
        <mapping class="Entities.UserHasPhonesEntity"/>
        <mapping class="Entities.UserIsShopkeeperEntity"/>
        <mapping class="Entities.UserIsWorkerEntity"/>
        <mapping class="Entities.VariantEntity"/>
        <mapping class="Entities.VendorEntity"/>
        <mapping class="Entities.WifiAdapterEntity"/>
        <mapping class="Entities.WorkerHasRegionsEntity"/>
        <mapping class="Entities.WorkerHasRolesEntity"/>
        <mapping class="Entities.WorkerHasSectionsEntity"/>


        <!-- <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>



ありがとうございました。

どのように解決するのですか?

ObjectEntityエンティティクラスのinfoフィールドのフィールドタイプがObjectであるため、エラーが発生します。適切な型に変更することで、問題を解決できます。

また、似たような問題を見てみましょう。 org.hibernate.MappingException: プロパティマッピングに ENUM エンティティの間違った列数がある。