Reputation: 43
I would like to simply print a row from a database created automatically using Spring Boot JPA and Hibernate. I am missing something on how to do it and did not find it online. The reason why I am trying is mostly for testing if the connection to the database is working and also that the function to retrieve data are working.
I am trying to print a row using the main function, but the problem is that @Autowired in the main function does not work as I would like because it's static.
The class where the Forum object is defined.
@Entity
@Table(name = "forum")
public class Forum {
@Id
private long id;
@Column(name = "title")
private String title;
@Column(name = "creationDate")
@Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
//GETTER AND SETTER
}
//The interface where I define some data retrieval functions.
@Repository
public interface ForumRepository extends CrudRepository<Forum, Long> {
List<Forum> findAll();
Forum findById(long id);
}
@Service
public class Test {
@Autowired
ForumRepository repo;
public Forum test(){
return repo.findById(760);
}
}
Upvotes: 0
Views: 2617
Reputation: 741
Just put @PostConstruct on your Test::test method if you want a really quick check. Otherwise, as already mentioned, tests are the way to go.
Upvotes: 0
Reputation: 876
Execute the following as Junit test:
@SpringBootTest
@RunWith(SpringRunner.class)
public class Test {
@Autowired
ForumRepository repo;
@Test
public voidtest(){
assertEquals(repo.findById(720).getId(), 720);
}
}
Upvotes: 0
Reputation: 1044
The simplest way is to dump the queries to standard out is to add the following to application.properties:
spring.jpa.show-sql=true
To beautify or pretty print the SQL, we can add:
spring.jpa.properties.hibernate.format_sql=true
To also print parameters use logging instead:
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
Reference link: https://www.baeldung.com/sql-logging-spring-boot
Upvotes: 1