JPA property java.net.URL

别等时光非礼了梦想. 提交于 2019-11-27 17:47:32

问题


HI,

I have an object which has a piece of URL-Information associated with it. Currently I save this URL in a simple String property, but java.net.URL would provide me with additional goodies such as detection of malformed URLs etc.

On the other hand I would consider it very ugly, if JPA simply created a LOB for the URL-Object. Does anyone know how a property of the type java.net.URL will be persisted to the database by compliant JPA providers?


回答1:


As per the JPA spec:

The persistent fields or properties of an entity maybe of the following types: Java primitive types; java.lang.String; other Java serializable types (including wrappers of the primitive types, java.math.BigInteger, java.math.BigDecimal, java.util.Date, java.util.Calendar[7], java.sql.Date, java.sql.Time, java.sql.Timestamp, user-defined serializable types, byte[], Byte[], char[], andCharacter[]); enums; entity types and/or collections of entity types; and embeddable classes (see section 2.1.5).

Plus the support for collections. But no primitive support of URL. They would however be supported as Serializable, which I guess would result in a LOB as you mentioned.

But you should be able to easily circumvent that: you can have the URL as a String in a field and a getter/setter that convert from String to URL though. Then you map the field with the annotation.

Or the opposite: the java.lang.URL in a field, and getter/setter to convert from URL to String, then you map the getter/setter with the annotation. I think it works as well.




回答2:


You can also use JPA AttributeConverter such as explain here to map a URL object into a String column (Hibernate does that out of the box)

Or, if you are only interrested in validation, you may use BeanValidation. There is a @URL annotation in HibernateValidator extension you can also create your own constraint such as explain here

I personnaly prefer the BeanValidation solution because considering url as java.net.URL bring some complexity : need for JPA AttributeConverter, JSF Converter, JAXB Adapter... while it is just for validation



来源:https://stackoverflow.com/questions/2355260/jpa-property-java-net-url

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