@Entity
public class MyModel {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private int age;
public MyModel() {}
public MyModel(String name, int age) {
this.name = name;
this.age = age;
}
}
import org.springframework.data.jpa.repository.JpaRepository;
public interface MyModelRepository extends JpaRepository<MyModel, Long> {
}
@Component
public class MyCommandLineRunner implements CommandLineRunner {
@Autowired
private ObjectMapper objectMapper;
@Autowired
private MyModelRepository myModelRepository;
@Override
public void run(String... args) throws Exception {
MyModel model = new MyModel("John", 30);
myModelRepository.save(model);
MyModel retrievedModel = myModelRepository.findById(model.getId()).orElse(null);
if (retrievedModel != null) {
System.out.println("Retrieved model from database:");
String json = objectMapper.writeValueAsString(retrievedModel);
System.out.println(json);
}
}
}
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
@Bean
public CommandLineRunner dataFetcher() {
return new DataFetcher();
}
private static class DataFetcher implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
String apiUrl = "https://jsonplaceholder.typicode.com/posts/1";
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject(apiUrl, String.class);
System.out.println(response);
}
}
}