Hibernate可选@ManyToOne,带有多个@JoinColumn

时间:2016-02-15 18:03:03

标签: sql hibernate jpa join orm

我有这个架构:

+---------+-----------+
| Cust_No | Cust_Name |
+---------+-----------+
|   12345 | ACME Inc. |
|   54321 | Foo Corp. |
+---------+-----------+

+---------+---------+--------+
| Addr_No | Cust_No | Street |
+---------+---------+--------+
|   10000 |   12345 | Broad. |
+---------+---------+--------+

+---------+---------+---------+-------------+
| Cntr_No | Cust_no | Addr_No | Description |
+---------+---------+---------+-------------+
|   98765 |   12345 |    NULL | PlatService |
|   56789 |   12345 |   10000 | GoldService |
|   45678 |   54321 |    NULL | SlvrService |
+---------+---------+---------+-------------+

和这个实体:

@Entity
public class Customer {
    @Id
    @Column(name = "Cust_No")
    private Long number;

    @OneToMany
    @JoinColumn(name = "Cust_No", referencedColumnName = "Cust_No")
    private List<Address> addresses;
}

@Entity
@IdClass(AddressKey.class)
public class Address {
    @Id
    @Column(name = "Addr_No")
    private Long id;

    @Id
    @Column(name = "Cust_No")
    private Long customerId;

    @Column(name = "Street")
    private String street;
}

@Entity
public class Contract {
    @Id
    @Column(name = "Cntr_No")
    private Long id;

    @ManyToOne
    @JoinColumn(name = "Cust_No" referencedColumnName = "Cust_No", insertable = false, updateable = false)
    private Customer customer;

    @ManyToOne
    @JoinColumns({
        @JoinColumn(name = "Cust_No", referencedColumnName = "Cust_No",
        @JoinColumn(name = "Addr_No", referencedColumnName = "Addr_No"
    })
    @NotFound(action = NotFoundAction.IGNORE)
    private Address address;

    @Column(name = "Description")
    private String description;
}

Contract可能与CustomerCustomer + Address相关联。首先,似乎Hibernate需要@NotFound注释,否则会抛出类似:EntityNotFoundException: Unable to find Address with id 54321之类的异常而且这很奇怪,因为@ManyToOne默认应该是optional = true

然后,当我通过Contract查询Customer.name时,Hibernate使用CROSS JOIN排除了Contract Addr_No NULL的所有@ManyToOne }。由于默认情况下LEFT JOIN是可选的,因此我希望Contract包括nullAddress LEFT OUTER JOIN es。

使用带有明确@ManyToOne的JPQL,但我无法访问查询的构建过程(使用Criteria API构建)。

问题是:为什么可选CROSS JOIN使用array ( PDO::MYSQL_ATTR_INIT_COMMAND => "SET lc_time_names='de_DE',NAMES utf8" ) ?这是一个错误吗?

0 个答案:

没有答案