0

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);
    }
}
2
  • 1
    have a look at unit testing, specifically at JUnit Commented May 22, 2019 at 8:32
  • What you want to use is docs.spring.io/spring-boot/docs/current/reference/htmlsingle/… in combination with junit to write a test. If not using tests, you'll have to create some thing to call your service or application. Maybe a rest endpoint that in turn vill fetch the data and also print as it's doing so. Commented May 22, 2019 at 8:46

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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);
    }
}

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.