4535992
4535992

Reputation: 418

Mapping varchar type of a SQL column to a java.net.URL of Java with Hibernate

I have a column (named "url") in a table whose values are URLs. Some are stored as "http://www.test.com" while other as some "blogspot.sometest.com" (the table is not mine, by the way, so I can't change the structure).

On my project, I stored the content of the "url" column as a java.net.URL type property of a structured object (e.g. Page(String name,URL url);). So, if is possible, I don't wanna modify the project.

I want, using Hibernate, to be able to get the single record with specific id. Exemple code:

 @Override
public T selectRow(Serializable id){
    T object = null;
    try {
        openSession();
        trns = session.beginTransaction();
        criteria = session.createCriteria(cl);
                 criteria.add(org.hibernate.criterion.Restrictions.eq("doc_id",id));
        //THIS LINE OF CODE LAUNCH THE EXCEPTION: org.hibernate.HibernateException: Unable to convert string [4bid.it] to URL : java.net.MalformedURLException: no protocol: 4bid.it 
       //BECAUSE FOR SOME OF THE URLS THERE IS NO PROTOCOL...
        List<T> results = criteria.list();
        //SAME WITH THIS
        object = (T) criteria.setFirstResult((Integer) id);

    //THE NEXT LINE OF CODE WORK BUT RETURN NULL FOR URL WITHOUT THE PROTOCOL
    object = (T) session.load(cl, id); 
    } catch (RuntimeException e) {
        if (trns != null) { trns.rollback();}
        SystemLog.exception(e);
    } finally {
        session.flush();
        session.close();
    }
    return object;
}

So, i can just create my specific java class for implements a org.hibenrate.UserType and try to resolve with that, but i read in the hibernate documentation that already exists a UrlType (https://docs.jboss.org/hibernate/orm/4.2/javadocs/org/hibernate/type/UrlType.html) and this UrlType just do the mapping between the varchar and the url, now i must be stupid, but i don't get it how can i use that for mapping the varchar of the table with the java.net.url object of my programm. If anyway you know some trick for intercept the value returned from hibernate and just append the string "http://" to that is welcome either.

Ty in advance. Greetings.

UPDATE 1: A brute force solution for my problem is just execute two SQL query: Before the CRUD Hibernate Operation:

UPDATE myTable SET url= CONCAT('http://',url) WHERE NOT url like 'http://%';

Run all the Hibernate Operation.

After the CRUD Hibernate operation:

UPDATE myTable SET url = REPLACE(url, 'http://', '') WHERE url LIKE '%http://%';

UPDATE2 i'have tried with @PreUpdate and @PrePersist annotation on the setUrl(Url url) like this:

@PreUpdate
@PrePersist
public void setUrl(URL url) {
    if(url.toString().contains("://")) {
        this.url = url;
    }else{
        try {
            this.url = new URL("http://"+url.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

Now work fine when i just make UPDATE,REMOVE,PERSIST operation , but if you want something like "@PreLoad" (note: this annotation not exists)for convert the sql value "www.test.com" to "http://www.test.com" before the storage on the java object the most simple thing i found is just use a hibernate interceptor.

Upvotes: 2

Views: 2102

Answers (1)

Vlad Mihalcea
Vlad Mihalcea

Reputation: 154010

The UrlType is already supported and it maps a VARCHAR column to a java.net.URL property.

All you need to do is to use a simple mapping as such:

@Column(name = "url")
private URL url;

Upvotes: 5

Related Questions