I have a database table where I store URLs (http://google.com for example). The entity corresponding to the table has a URL type field, so I create a criteria query like the following:
CriteriaBuilder cb = ...
Path<URL> path = ...
cb.equal(path , new URL("http://google.com"));
This works as intended, however I want to be able to do something like this:
cb.like(path.<String>get("externalForm"), "%google%");
Obviously URL hasn’t got an externalForm field, but has a toExternalForm() method instead.
Is this kind of query possible with the API? If yes: how? Or is my best bet to map the URL column to String instead of URL?
No, you cannot call methods of persisted values in Criteria queries. JPQL do have same limitation. In the end both of those translate to the SQL query and calling method in arbitrary Java object does not fit too well in.
Also in your case it does not matter do we try to access this via field or method. Reason being that fields in java.net.URL are different from the persistent attributes mapped in your entities. URL fields are not directly persisted (so you cannot query them in SQL), Serializable objects are just persisted via serialization to byte array or similar.
Also, calling equals in java.net.URL can cause surprises: java.net.url Javadoc
Just go with the String as type and keep care that field in database is long enough also for surprisingly long urls.