我有一个简单的Spring Boot应用程序。
实体:
package com.example.demo;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@Entity
@Table(name = "FRUIT")
@EntityListeners(AuditingEntityListener.class)
public class Fruit {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String name;
private String price;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String toString() {
return "{" + name + " : " + price + "}";
}
}
存储库:
package com.example.demo;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface FruitDao extends JpaRepository<Fruit, Long>{
public List<Fruit> findAll();
}
控制器:
package com.example.demo;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/fruit")
public class FruitController {
@Autowired
private FruitDao fruitDao;
@RequestMapping(value="/all", method=RequestMethod.GET)
public String findAllFruits(Model model) {
List<Fruit> fruits = fruitDao.findAll();
System.out.println("Fruits = " + fruits);
model.addAttribute("fruits", fruits);
return "allFruits";
}
}
application.properties:
server.port=8000
###
# Database Settings
###
spring.datasource.url=jdbc:h2:~/test
spring.datasource.platform=h2
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
###
# H2 Settings
###
spring.h2.console.enabled=true
spring.h2.console.path=/console
spring.h2.console.settings.trace=false
spring.h2.console.settings.web-allow-others=false
###
# Hibernate Settings
###
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.use_sql_comments=false
spring.jpa.properties.hibernate.format_sql=true
当我转到http://localhost:8000/fruit/all时,我在控制台输出中看到了这一点:
Hibernate:
select
fruit0_.id as id1_0_,
fruit0_.name as name2_0_,
fruit0_.price as price3_0_
from
fruit fruit0_
Fruits = []
基本上,查询是正确的但没有返回任何内容。 直接转到H2数据库并运行相同的查询,我确实得到了一些记录。我做错了什么?