Hibernate @OneToMany throws MySQLSyntaxErrorException: You have an error in your SQL syntax

≯℡__Kan透↙ 提交于 2019-12-06 07:11:27

There is a . that's causing the SQL query issue:

. as col_6_0_ from CONTACT contact0

The mappings are wrong anyway, so you need to fix that first. If you want to know how to map a bidirectional @OneToMany association, you really need to read this article.

Since the ContactPhone already maps the FK on the child-side:

@ManyToOne
@JoinColumn(name = "CONTACT_ID")
private Contact contact;

The parent-side, need to use mappedBy instead:

@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "contact")
@OrderBy("id ASC")
private Set<ContactPhone> phones = new HashSet<>(); 

But, that's not all.

Why do you use FetchType.EAGER for a collection. That's either a Code Smell or an Anti-Pattern. Use lazy loading instead.

Since you are using a Set, you need to make sure you implement equals and hashCode properly. If you have a natural id (international phone number is unique), you should use that. Otherwise, you can use the entity identifier but only if you do this trick.

Update

Also, you can not select a collection in a DTO projection like this:

SELECT new com.tim.core.dto.client.MinimalContactDTO(c.id, c.version, c.name, c.title, c.email, c.createdDate, **c.phones**)

Remember that the ResultSet is like a spreadsheet, not like a graph of objects.

What you need to do is change you DTO like this:

public MinimalContactDTO(
    Long id, Long version, String name, String title, String email, 
    Date createdDate, ContactPhone phone) {
    ...
}

Now, you can only pass one phone at a time:

SELECT new com.tim.core.dto.client.MinimalContactDTO(
    c.id, c.version, c.name, c.title, c.email, c.createdDate, p)
from CONTACT c 
JOIN c.phones p
where 
( 
    c.localRecordStatus IS NULL OR 
    c.localRecordStatus IN (:openStatusList) )
) 

Then, you can transform the table-like ResutSet into a graph using Hibernate ResultTransformer. Check out this article for more details on how you can do that.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!