1.3 KiB
1.3 KiB
JPA-examples
Entity annotation
@Entity
@Table
public final class MyEntityClass {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column
private float primitiveField;
@Column
private String primitiveField2;
}
References to another entities
@Entity
@Table
public final class AnotherEntity {
//...
@ManyToMany(fetch = FetchType.EAGER)
@JoinColumn(name = "my_entity_id", nullable = false)
private Collection<MyEntityClass> entities;
}
Collection of primitives
//...
public final class AnotherEntity {
//...
@ElementCollection(fetch = FetchType.EAGER)
private Set<String> stringSet;
}
Map field as another data type
//...
public final class AnotherEntity {
//...
@Column
@JSONProperty
@Convert(converter = CustomConverter.class)
private CustomType settings;
}
public class CustomType {
//...
}
/*
Convert custom type to string and vise versa
*/
@Converter
public static class CustomConverter implements AttributeConverter<CustomType, String> {
@Override
public String convertToDatabaseColumn(CustomType customType) {
// return ...
}
@Override
public CustomType convertToEntityAttribute(String dbData) {
// return ...
}
}