Skip to content

Instantly share code, notes, and snippets.

@hoangnd-monkey
Created December 4, 2023 05:40
Show Gist options
  • Select an option

  • Save hoangnd-monkey/a15561afef878f53d64579dd9f5654d4 to your computer and use it in GitHub Desktop.

Select an option

Save hoangnd-monkey/a15561afef878f53d64579dd9f5654d4 to your computer and use it in GitHub Desktop.
JPA IdClass and ManyToOne
public class JpaApplication {
@Bean
CommandLineRunner commandLineRunner(AuthorService authorService, ModelRepository modelRepository) {
return args -> {
ModelField f1 = ModelField.builder()
.filedName("f1").build();
ModelField f2 = ModelField.builder()
.filedName("f2").build();
Model model1 = Model.builder()
.modelName("model1")
.fields(List.of(f1, f2)).build();
var m1 = modelRepository.save(model1);
log.info(m1.getId());
m1.getFields().forEach(f -> log.info(f.getFiledName()));
var m2 = modelRepository.findFirstById(m1.getId()).get();
log.info(m2.getId());
m2.getFields().forEach(f -> log.info(f.getFiledName()));
};
}
public static void main (String[] args) {
SpringApplication.run(JpaApplication.class, args);
}
}
@Entity
@Getter
@AllArgsConstructor
@NoArgsConstructor
@Builder
@NamedEntityGraph(name = "Model.withModelFields",
attributeNodes = @NamedAttributeNode("fields")
)
public class Model {
@Id
@GeneratedValue(strategy = GenerationType.UUID)
UUID id;
String modelName;
@OneToMany(mappedBy = "model", fetch = FetchType.LAZY)
List<ModelField> fields;
}
@Entity
@IdClass(value = ModelFieldPk.class)
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Getter
public class ModelField {
@Id
String filedName;
@Id
@ManyToOne
Model model;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ModelFieldPk implements Serializable {
String filedName;
UUID model;
}
@Repository
public interface ModelRepository extends JpaRepository<Model, UUID> {
@EntityGraph(value = "Model.withModelFields")
Optional<Model> findFirstById (UUID id);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment