How to map Set of Entities to a comma separated string in DB

I would like to know how to solve the following problem in Hibernate 6.6.

Given the following column definition:

@Column(name = "ids")
protected Set<Transport> ids;

In the database ids is a varchar and contains a comma separated sequence of transport shortnames (= natural keys). Eg. car,bike,train. The Transport entity is immutable.

How do I solve the translation between Set and csv shortnames as the database representation?

You can use an AttributeConverter<Set, String> implementation that implements the logic with which you would want your entities serialized into CSV format. Then you would just need to annotate your field with the @Convert annotation.

See Hibernate’s user guide for more information.

Serializing is not the biggest issue. It’s the deserialization where I require a session to get the entities. AttributeConverter (for good reasons) does not provide this information.

I would advise you against doing that, but if you really want to do this, you can inject an EntityManager into your converter and call EntityManager#getReference() to construct proxies.

I understand. So how would you solve the problem I stated in my initial post in a better way? Ideally I’d like Hibernate to handle the conversion of Set vs. Csv-String.

There simply is no good way to solve this in the Hibernate ORM layer IMO. Maybe when we have support for @JoinArray mappings you could leverage a custom JdbcType to do the translation between comma separated list to an array, but until then, I think the best way forward is that you use a list of ids and transform that to a list of entities on-load or even on-demand.