[英]Printing a row from a database using Spring Data JPA, Hibernate and PostgreSQL
I would like to simply print a row from a database created automatically using Spring Boot JPA and Hibernate.我想简单地从使用 Spring Boot JPA 和 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.我正在尝试使用 main 函数打印一行,但问题是 main 函数中的 @Autowired 无法正常工作,因为它是静态的。
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);
}
}
The simplest way is to dump the queries to standard out is to add the following to application.properties:将查询转储到标准输出的最简单方法是将以下内容添加到 application.properties:
spring.jpa.show-sql=true
To beautify or pretty print the SQL, we can add:为了美化或漂亮地打印 SQL,我们可以添加:
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参考链接: https : //www.baeldung.com/sql-logging-spring-boot
Execute the following as Junit test:执行以下作为 Junit 测试:
@SpringBootTest
@RunWith(SpringRunner.class)
public class Test {
@Autowired
ForumRepository repo;
@Test
public voidtest(){
assertEquals(repo.findById(720).getId(), 720);
}
}
Just put @PostConstruct on your Test::test method if you want a really quick check.如果您想要快速检查,只需将 @PostConstruct 放在您的 Test::test 方法上。 Otherwise, as already mentioned, tests are the way to go.
否则,正如已经提到的,测试是要走的路。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.