Java Hibernate错误:为类example4.heroesMap提供了错误类型的ID,预期:class java.lang. String,得到class java.lang.String

ctehm74n  于 2023-10-23  发布在  Java
关注(0)|答案(2)|浏览(138)

我有一张table

create table heroes
(
    id       int          null,
    name     varchar(255) null,
    level    int          null,
    ultimate varchar(255) null
);

然后连接cfg.xml文件

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- JDBC Database connection settings -->
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/xxi?useSSL=false</property>
        <property name="connection.username">admin</property>
        <property name="connection.password">12345</property>
        <!-- JDBC connection pool settings ... using built-in test pool -->
        <property name="connection.pool_size">10</property>
        <!-- Select our SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <!-- Echo the SQL to stdout -->
        <property name="show_sql">true</property>
        <!-- Set the current session context -->
        <property name="current_session_context_class">thread</property>
        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">validate</property>

        <mapping class="example4.heroesMap"></mapping>
    </session-factory>
</hibernate-configuration>

还有我的DB课程

package example4;

import org.hibernate.annotations.GeneratorType;

import javax.persistence.*;

@Entity
@Table(name = "heroes")
public class heroesMap {
    @Id
//    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @Column(name = "name")
    private String name;
    @Column(name = "level")
    private int level;
    @Column(name = "ultimate")
    private String ultimate;
}

错误说表定义中的类型不匹配,但看起来很相似,我做错了什么?错误文本:为类example4.heroesMap提供了错误类型的ID。预期:class java.lang. String,得到class java.lang.String
我想从表中读取记录,但它一直崩溃

public class Hibernate {
    Session session;
    Hibernate(){
        StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                                                .configure("hibernate.cfg.xml").build();
        Metadata meta = new MetadataSources(registry).getMetadataBuilder().build();
        SessionFactory factory = meta.getSessionFactoryBuilder().build();
        this.session = factory.openSession();
    }
    public String getRecord(String id){
        return this.session.get(heroesMap.class,id).toString();
    }
    public void close(){
        this.session.close();
    }
}
5sxhfpxr

5sxhfpxr1#

heroesMap类中,您已将id字段定义为int

private int id;

但是,在getRecord方法中,您将传递String作为ID:

public String getRecord(String id){
    return this.session.get(heroesMap.class,id).toString();
}

相关问题