85 lines
1.3 KiB
Markdown
85 lines
1.3 KiB
Markdown
# JPA-examples
|
|
|
|
### Entity annotation
|
|
|
|
```java
|
|
|
|
@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
|
|
|
|
```java
|
|
|
|
@Entity
|
|
@Table
|
|
public final class AnotherEntity {
|
|
//...
|
|
@ManyToMany(fetch = FetchType.EAGER)
|
|
@JoinColumn(name = "my_entity_id", nullable = false)
|
|
private Collection<MyEntityClass> entities;
|
|
}
|
|
```
|
|
|
|
### Collection of primitives
|
|
|
|
```java
|
|
//...
|
|
public final class AnotherEntity {
|
|
//...
|
|
@ElementCollection(fetch = FetchType.EAGER)
|
|
private Set<String> stringSet;
|
|
}
|
|
|
|
```
|
|
|
|
### Map field as another data type
|
|
|
|
```java
|
|
|
|
//...
|
|
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 ...
|
|
}
|
|
}
|
|
|
|
|
|
|
|
``` |