当前位置: 首页 > 知识库问答 >
问题:

Hibernate实用类

姬宝
2023-03-14

我正在尝试重写我拥有的 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文件,看起来不错!

下面是我的实体类:

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;
    }
}

这是与前一个相关的表的实体:

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>


提前感谢!

共有1个答案

章晗日
2023-03-14

该错误抱怨对象实体实体类中信息字段的对象字段类型。更改为适当的类型将解决问题。

另外,看看类似的问题。org.hibernate.MappingException:属性映射在 ENUM 实体中具有错误的列数

 类似资料:
  • 问题内容: 我收到以下hibernate异常: 简化的Matchup类如下所示: 简化的Team类如下所示: 笔记: 比赛和团队都有子类。我不确定这是否会影响局势。 我的persistence.xml中列出了Matchup和Team都包括在内。 如果我在两个getter方法上都使用@Transient批注,该错误将消失。 谁能阐明为什么会发生这种异常? 问题答案: 我发现了问题:我没有将Team类

  • 我对这些技术是新的,所以提前道歉。 我在我的应用程序中使用了springboot、Spring JPA、hibernate和mapstruct。

  • 问题内容: 是否可以使用公式加载实体? 例如: 如果是这样,则映射必须看起来如何。 另外,使用公式加载某些实体的替代方法是什么? 问题答案: 可以,但是公式看起来像: 另一种选择是

  • 问题内容: 您是否具有Hibernate实体的通用基类,即具有id,version和其他通用属性的MappedSuperclass?有什么缺点吗? 例: 问题答案: 这对我们来说很好。除了ID和创建日期,我们还有一个修改日期。我们还具有一个实现 Taggable 接口的中间 TaggedBaseEntity ,因为我们的某些Web应用程序实体具有标签,例如有关Stack Overflow的问题。

  • 问题内容: 我试图按顺序实施乐观锁定,以避免丢失更新情况。在我的应用程序中,当两个用户获取相同的记录,而第一个用户通过一些更改对其进行更新时。查看相同记录的第二个用户看不到此更改,并且他自己进行了一些更改并更新了该记录。因此,第一人称更改丢失。为了防止这种情况,我写了以下内容,但问题仍然存在。我是这个概念的新手,无法发现问题。 我试图通过阅读doc 11.3.4 来实现这一目标。自定义自动版本控制

  • 问题内容: 我是Java和Hibernate的新手(是Rails和C#开发人员)。无论如何,我有一个可以在Hibernate上正常运行的测试程序,但是我的实际Web应用程序(Struts 1)崩溃了: 我在用: 下面是实际的程序WORKS。这是主体项目的一部分。只是一个简单的JAVA测试。 效果很好。输出一些样本数据。 现在,当我尝试在Struts中执行相同的操作时,出现了异常。这是行不通的: 这

  • 我有几个从db动态创建的实体类,但是当我用关系注释它们时,我有以下错误 组织。冬眠AnnotationException:mappedBy引用未知的目标实体属性:coma。实体impl。能力标准实施。昏迷中的能力。实体impl。胜任力impl。能力标准执行 我的实体类如下 和 我对冬眠感到困惑和绝望。。。

  • 是否可以在超类实体中有一个列定义供子类实体使用? 我采用了每子类表层次结构来表示从“超级业务”继承的不同类型的“业务”。因此,每个业务类型在数据库中都有自己的表,并且还有一个通用的“业务”表,其中包含所有业务类型共有的信息。 每个企业都有一个外键列,名为“parent\u id”,它指向相同类型的另一个企业(因此企业可以属于相同类型的其他企业)。这意味着我的每个业务类型类都有自己的“parent”