1

我正在开发一个使用 Spring MVC 和 JPA 的 Web 项目,它是使用 MAVEN 构建的。不知何故,我不确定我是否正确完成了 JPA 配置,因为我在启动网络时遇到了这个错误

Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: User is not mapped [from User]

我以这种方式在 MYSQL 中创建了表:

mysql> desc users;

+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| username | varchar(10) | NO   | PRI |         |       |
| password | varchar(32) | YES  |     | NULL    |       |
| enabled  | int(11)     | YES  |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

我以这种方式声明了用户实体:

@Entity
@Table(name="users")
public class User {
    @Id
    @Column(name="username")
    private String username;

    @Column(name="password")
    private String password;

    @Column(name="enabled")
    private Integer enabled;

我有这个配置datasource.xml

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/test"/>
    <property name="username" value="root"/>
    <property name="password" value="root"/>
</bean>

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
    <property name="dataSource" ref="dataSource"/>
    <property name="packagesToScan" value="org.huahsin.ProjectA.*" />
</bean>

<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
    <property name="databasePlatform" value="org.hibernate.dialect.MySQLInnoDBDialect" />
    <property name="showSql" value="true" />
</bean>

这就是 DAO 将如何调用持久对象:

@Repository
public class UserDao implements IUserDao {

   @PersistenceUnit
   private EntityManagerFactory emf;

   public User findByUsername(String username) {

      List<User> l = (List<User>) emf.createEntityManager().createQuery("from User");
      ...
   }
}
4

1 回答 1

3

packagesToScan需要一个包名称列表。org.huahsin.ProjectA.*不是有效的包名。确保在此属性中指定实体的包(或任何超级包)。

于 2013-11-02T14:20:23.093 回答