How do I persist a Java property of type Object using Hibernate?

左心房为你撑大大i 提交于 2019-12-31 03:51:20

问题


I have a Java class with a property like this

private Object myObj;

When I try to save the class using Hibernate annotations, I get the rather confusing error message "property mapping has wrong number of columns".

What is the correct approach to persisting a class containing a generic property such as this?


回答1:


As you said, the object can be image, video, and more.

If it is supposed to have only binary data, you can create another class, and transfer the data from this one. In the process of transferring you can convert the Object to byte[] (depending on the concrete type), and use a Lob data type (@Lob) for mapping it.

To extend this, if not only binary data is to be supported, your new object can have 2 fields - one in case of binary, and one (or more) in case of other types.

Anyway, the object as it is now, represents a quite unintelligent design, and it cannot be persisted properly without hassle.




回答2:


Don't use a generic Object attribute if you can help it. My first brush with Hibernate meant inheriting a project with oodles of things like this, and it was a world of pain. As Zoidberg says, using Object means that your model isn't easily serialised / versioned (an understatement if I'm honest).




回答3:


Change the type of your property:

private byte[] myObj;

This worked for me with Fluent NHibernate (albeit in C#) and an SQL field type of varbinary(max).

You can then expose this as an image, video, or whatever. An example of converting to an image in Java:

ImageIO.read(new ByteArrayInputStream(myObj));


来源:https://stackoverflow.com/questions/1941191/how-do-i-persist-a-java-property-of-type-object-using-hibernate

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