How to map a PostgreSQL array with Hibernate
Hibernate does not support database arrays (e.g. ones mapped to java.sql.Array
) out of the box.
array
and primitive-array
types provided by Hibernate are for mapping Java arrays into backing table - they're basically a variation of one-to-many / collection-of-elements mappings, so that's not what you want.
Latest PostgreSQL JDBC driver (8.4.whatever) supports JDBC4 Connection.createArrayOf()
method as well as ResultSet.getArray()
and PreparedStatement.setArray() methods, though, so you can write your own UserType
to provide array support.
Here is a UserType implementation dealing with Oracle array that provides a good starting point, it's reasonably straightforward to adapt it to handle java.sql.Array
instead.
How to map a PostgreSQL text[] with Hibernate
There are several approaches you can take here. The first one is to pick a delimiter that will not be encountered within the filenames (usually :
or ;
depending on the system) and use a text field, instead of a an array, and just have some internal conversion
@Transient
private List<String> filename; // this is the data as convenient for you to use
@Column(nullable = false)
private String filenames; // this is the database column format
@PrePersist
@PreUpdate
private void toFilenameColumn() {
if (filename == null) {
filenames = "";
return;
}
StringBuilder sb = new StringBuilder();
String glue = "";
for (String fn : filename) {
sb.append(glue).append(fn);
glue = ";";
}
filenames = sb.toString();
}
@PostLoad
private void fromFilenameColumn() {
filename = Arrays.asList(filenames.split(";"));
}
But if you're set on using arrays, you can add this library to your project dependencies and define your column like so:
@Column(nullable = false, columnDefinition = "text[]")
private String[] filename;
The library is plug-and-play.
And finally you can do it the most standard way by defining another table with a one-to-many relation to the attachments table.
Related Topics
Alert Handling in Selenium Webdriver (Selenium 2) with Java
Java Calendar, Date, and Time Management for a Multi-Timezone Application
Why to Use Swingutilities.Invokelater in Main Method
Method Overloading and Choosing the Most Specific Type
How to Replace the Awt Eventqueue with Own Implementation
Can a Java File Have More Than One Class
Post Request Send JSON Data Java Httpurlconnection
Whitespace Matching Regex - Java
Are Static Variables Shared Between Threads
Clone() VS Copy Constructor VS Factory Method
Why Does Math.Round(0.49999999999999994) Return 1
Warning About Ssl Connection When Connecting to MySQL Database
Import Pem into Java Key Store
Sandbox Against Malicious Code in a Java Application
How to Serialize an Object into a String