MySQL数据库中的表如下所示:

mysql> DESCRIBE customer;
+-------------+----------------------+------+-----+
| Field       | Type                 | Null | Key |
+-------------+----------------------+------+-----+
| customer_id | smallint(5) unsigned | NO   | PRI |
| first_name  | varchar(45)          | NO   |     |
| last_name   | varchar(45)          | NO   |     |
| address_id  | smallint(5) unsigned | NO   | MUL |
+-------------+----------------------+------+-----+

mysql> DESCRIBE address;
+-------------+----------------------+------+-----+
| Field       | Type                 | Null | Key |
+-------------+----------------------+------+-----+
| address_id  | smallint(5) unsigned | NO   | PRI |
| address     | varchar(50)          | NO   |     |
+-------------+----------------------+------+-----+

这就是我努力实现一对一关系的方式:
@Entity
@Table(name = "customer")
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int customer_id;

    @Basic
    private String first_name;

    @Basic
    private String last_name;

    @OneToOne(targetEntity = Address.class)
    @JoinColumn(name = "address_id")
    private Address address;

在Address.java中
@Entity
@Table(name = "address")
public class Address {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int address_id;

    @Basic
    private String address;

    @OneToOne(mappedBy = "address", targetEntity = Customer.class)
    private Customer customer;

我用一个简单的测试:
@Test
public void testGetAll() {
    PersistenceUtil.buildEntityManagerFactory();
    AddressDaoImpl addressDao = new AddressDaoImpl();
    List all = addressDao.getAll();
    System.out.println(all.iterator().next());
}

我得到:
java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: address is not mapped [FROM address]

我做错什么了?为什么不为地址实体提取客户?
编辑
下面是我的DAO类的代码:
package biz.tugay.saqila.dao;
/* User: [email protected] Date: 08/08/15 Time: 10:18 */

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import java.util.List;

public abstract class GenericDaoImpl<T> implements GenericDao<T> {

    @Override
    public List getAll() {
        EntityManager em = PersistenceUtil.getEntityManager();
        EntityTransaction transaction = em.getTransaction();
        transaction.begin();
        List<T> all = em.createQuery("FROM " + getTableName()).getResultList();
        transaction.commit();
        return all;
    }

}

public class AddressDaoImpl extends GenericDaoImpl<Address> {
    @Override
    public String getTableName() {
        return "address";
    }
}

最佳答案

JPQL(HQL)类和属性名是case sensitive。因此,在查询中,必须为Address实体使用正确的类名:

from Address ...

因此,请将实体名改为以大写字母A开头:
public class AddressDaoImpl extends GenericDaoImpl<Address> {
    @Override
    public String getTableName() {
        return "Address";
    }
}

关于java - 一对一 hibernate 未映射,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31918160/

10-10 03:04