hibernate实体管理器-querysyntaxexception:foobar未Map

nnvyjq4y  于 2021-07-07  发布在  Java
关注(0)|答案(3)|浏览(255)

我要走了 org.hibernate.hql.internal.ast.QuerySyntaxException 尝试使用entitymanager执行查询时。
我在javase应用程序中使用hibernate单机版。我没有使用xml配置。
这就是如何获取会话和entitymanager(设置变量是 Map<String, String> ):

StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder();
registryBuilder.applySettings(settings);
registry = registryBuilder.build();
MetadataSources sources = new MetadataSources(registry);
Metadata metadata = sources.getMetadataBuilder().build();
sessionFactory = metadata.getSessionFactoryBuilder().build();

Session session = sessionFactory.openSession();
EntityManager em = session.getEntityManagerFactory().createEntityManager();

这是我的实体类:

@Entity
@Table(name = "playeraccount")
public class PlayerAccount {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "playerId")
    private String playerId;
    @Column(name = "balance")
    private Double balance;

    [getters, setters...]
}

表sql:

CREATE TABLE PlayerAccount (
    id BIGINT NOT NULL UNIQUE PRIMARY KEY,
    playerId VARCHAR(255) NOT NULL UNIQUE,
    balance DOUBLE NOT NULL DEFAULT 0.0
);

最后一个问题是:

TypedQuery<PlayerAccount> q = em.createQuery("SELECT a FROM PlayerAccount a WHERE a.playerId = :uuid", PlayerAccount.class);
q.setParameter("uuid", uuid);
PlayerAccount acc = q.getSingleResult();

整个例外是:

java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: PlayerAccount is not mapped [SELECT a FROM PlayerAccount a WHERE a.playerId = :uuid]
00jrzges

00jrzges1#

Configuration configuration = new Configuration();
EntityScanner.scanPackages("my.com.entities", "my.com.other.entities")
    .addTo(configuration);
SessionFactory sessionFactory = configuration.buildSessionFactory();

我错过了关于缺少xml的部分:)

List<Class<?>> classes = EntityScanner
        .scanPackages("my.com.entities", "my.com.other.entities").result();

MetadataSources metadataSources = new MetadataSources();
for (Class<?> annotatedClass : classes) {
    metadataSources.addAnnotatedClass(annotatedClass);
}

SessionFactory sessionFactory = metadataSources.buildMetadata()
    .buildSessionFactory();

hibernate可以扫描包来自动创建sessionfactory吗?

bqujaahr

bqujaahr2#

使用标准方法创建 EntityManagerFactory 即:

Persistence.createEntityManagerFactory("PersistenceUnitName", settings)

你可以将其投射或展开到 SessionFactory 如果你愿意的话。另外,确保 persistence.xml 包含实体类的fqn。如果要使用hibernate本机API,还可以遵循以下教程:https://docs.jboss.org/hibernate/orm/current/quickstart/html_single/#tutorial_annotations

tvokkenx

tvokkenx3#

您的查询应该是:“select*from playeraccount a where a.playerid=:uuid”

相关问题