【问题标题】:Why i dont get data from database with sping boot-jpa?为什么我不使用 spring boot-jpa 从数据库中获取数据?
【发布时间】:2018-07-17 22:44:40
【问题描述】:

我创建了一个模型类,叫做 user:

@Entity
@Table(name = "user")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "username")
private String username;
@Column(name = "created", columnDefinition="TIMESTAMP")
private LocalDateTime created;
@Column(name = "updated", columnDefinition="TIMESTAMP")
private LocalDateTime updated;
}

控制器类:

@RestController
@RequestMapping("/user")
public class UserController {
@RequestMapping(method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public List<User> getUserList(){
    System.err.println("Get user list");
    List<User> all = userRepository.findAll();
    System.err.println("all = " + all);
    return all;
}
}

我的属性文件:

 spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase? serverTimezone=UTC
 spring.datasource.username=root
 spring.datasource.password=root
 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
 spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
 spring.jpa.hibernate.ddl-auto=update
 spring.jpa.properties.hibernate.show_sql=true
 spring.jpa.properties.hibernate.format_sql=true

在邮递员中,我向:localhost:8080/user 发送了一个获取请求,第一个系统错误显示...休眠显示 sql,但我没有获取用户。我试着只传回一个字符串,它工作正常。如果我想用户: userRepository.findAll() 它只是在加载......但什么也不做。在存储库文件中,我使用 jparepository 的扩展。 有什么问题?感谢您的帮助!

【问题讨论】:

  • 您说first system error,但您没有指定或包含任何错误或堆栈跟踪。包含这些信息会很有帮助,这样可以充分限制答案以帮助指导您找到解决方案。

标签: java hibernate spring-boot spring-data-jpa


【解决方案1】:

没有来自 Spring 和/或 Hibernate 的日志很难猜测,但我会根据您提供的代码发布一些可能的原因:

  1. 您实际上是否在 8.0 版中使用 MySQL Connector/J?在旧版本 (5.1) 中,正确的驱动程序类是 com.mysql.jdbc.Driver,8.0 将其更改为 com.mysql.cj.jdbc.Driver

  2. 您的构建工具(maven 或 gradle)中是否明确定义了 MySQL Connector/J 依赖项? Spring默认是不会拉进来的,给它推荐一个版本就好了。

  3. 您的 JDBC URI 中有一个额外的空格,不知道这是否可行。

  4. 我建议将 java.sql.Timestamp 类用于实体中的时间值,而不是 Java 8 DateTime 类型。 Java 8 类型导致 ORM 解决方案存在很多问题。您可以直接在 Java 8 Instant 对象和 Timestamp 对象之间进行转换。这些将作为数字(例如bigint)存储在您的数据库中,因此不再需要列定义。

【讨论】:

    猜你喜欢
    • 2021-08-23
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    • 2021-02-25
    • 2020-10-27
    • 2018-04-16
    • 1970-01-01
    • 2014-10-21
    相关资源
    最近更新 更多