A typical JPA entity looks like:
@Entity
public class Person {
@Id
private int id;
private String name;
private int age;
private Calendar anniversary;
...
}
Note that the data type is not annotated on any of the member attributes.
I just read a note around Hibernate being not so usable with Scala’s data types and wondered if we could write some adaptors. I know we can write UserTypes for Scala types and UserCollectionTypes for Scala’s collections so adaptors may be possible.
The question I have is can I configure these data types somehow so JPA will automatically associate them with corresponding Scala types (e.g. BigDecimal‘s user type with BigDecimal attributes), without having to annotate each attribute with @Type?
What you’re missing is that the JPA (in most implementations) maps to a relational database so it will map to an SQL type. Thus if you’re looking at the entity above it will map to a serialized object if you specify it, but more commonly it will map to a structure.
Let’s play with your entity and add an Account to it:
If I run a JPQL query
"SELECT p FROM Person p"I’m going to get->In the database that’s going to look like:
The “custom type” just ended up as a collection of primitives in another table. Generally speaking that’s what you want with the JPA. You’re trying to map to a RDBMS 99% of the time and you’re trying to not use
javax.sqlbecause you might end up cutting yourself in frustration at the checked exceptions.Basically: think of it as the database instead of your custom type. That’s what the JPA is doing. All the dialects you see in Hibernate or Eclipselink etc… are doing just that. Taking primatives and then saying “When you said
LongI meanBigIntegerWhen you saidStringI thinkVARCHAR(2048). However you can refine those defaults with annotations like @Column soI’d highly recommend you look at a dialect for a database you know and read the code. It isn’t too bad. Hibernate has fantastic documentation for beginners. If you don’t know SQL learn it asap if you’re working with the JPA. You’ll need it.