[英]Printing a row from a database using Spring Data JPA, Hibernate and PostgreSQL
我想简单地从使用 Spring Boot JPA 和 Hibernate 自动创建的数据库中打印一行。 我错过了一些关于如何做的东西,也没有在网上找到。 我尝试的原因主要是为了测试与数据库的连接是否正常以及检索数据的功能是否正常。
我正在尝试使用 main 函数打印一行,但问题是 main 函数中的 @Autowired 无法正常工作,因为它是静态的。
定义论坛对象的类。
@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);
}
}
将查询转储到标准输出的最简单方法是将以下内容添加到 application.properties:
spring.jpa.show-sql=true
为了美化或漂亮地打印 SQL,我们可以添加:
spring.jpa.properties.hibernate.format_sql=true
要打印参数,请改用日志记录:
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
执行以下作为 Junit 测试:
@SpringBootTest
@RunWith(SpringRunner.class)
public class Test {
@Autowired
ForumRepository repo;
@Test
public voidtest(){
assertEquals(repo.findById(720).getId(), 720);
}
}
如果您想要快速检查,只需将 @PostConstruct 放在您的 Test::test 方法上。 否则,正如已经提到的,测试是要走的路。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.