Spring JPA实体和Lombok

7

我使用Spring创建了项目。

dependencies {
    compile('org.springframework.boot:spring-boot-starter-cache')
    compile('org.springframework.boot:spring-boot-starter-data-jpa')
    compile('org.springframework.boot:spring-boot-starter-data-rest')
    compile('org.springframework.boot:spring-boot-devtools')
    compile('org.projectlombok:lombok')
    compile('org.springframework.boot:spring-boot-starter-thymeleaf')
    compile('org.springframework.boot:spring-boot-starter-web')
    compile('org.codehaus.groovy:groovy')
    runtime('com.h2database:h2')
    runtime('mysql:mysql-connector-java')
    testCompile('org.springframework.boot:spring-boot-starter-test') 
    testCompile('org.springframework.restdocs:spring-restdocs-mockmvc')
}

application.properties:

spring.data.rest.base-path=/api

spring.datasource.url=jdbc:mysql://localhost/secret_backend
spring.datasource.username=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update

实体类:

package com.app.Entity

import lombok.Data

import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.Id
import javax.persistence.Table

@Data
@Entity
@Table(name = "cities")
public class City {

    private @Id @GeneratedValue Long id;
    private String slug;
    private String title;
    private String titleShort;

    private City() {}

    /*public String getSlug(){
        return slug;
    }*/

    public City(String slug) {
        this.slug = slug;
    }
}

当我访问localhost:8080/api/cities时,我没有看到来自数据库的实际数据:
{
  "_embedded": {
    "cities": [
      {
        "_links": {
          "self": {
            "href": "http://localhost:8080/api/cities/7"
          },
          "city": {
            "href": "http://localhost:8080/api/cities/7"
          }
        }
      },
      {
        "_links": {
          "self": {
            "href": "http://localhost:8080/api/cities/8"
          },
          "city": {
            "href": "http://localhost:8080/api/cities/8"
          }
        }
      },
...

只有当我向实体添加getter时,才能看到数据,但是根据lombok文档,@Data注释必须为所有实体属性生成getter和setter。

你有检查实际输出吗?Lombok 是否已经对类进行了处理?此外,Lombok 只在编译时需要,而非运行时。 - highstakes
实际输出是什么? 也许有一些Java(Spring)新手的信息? 而且Lombok在compile('org.projectlombok:lombok')中。 - Cawa
我的意思是,检查已编译的 .class 文件,看看方法是否已添加到其中(使用 Java 反编译器或 'javap' 命令)。编译依赖项意味着它将包含在生成的构件中,这将是提供的范围(您需要在 Gradle 中使用插件),但这并不重要。 - highstakes
你应该尝试在你的类上独立运行lombok。它是一个注解预处理器,如果不正确地执行可能会干扰其他预处理器。 - highstakes
刚刚创建了一些只有@Data注解的额外类,编译后的类也没有getter和setter。 - Cawa
显示剩余2条评论
1个回答

1

将City.groovy重命名为City.java,现在它可以正常工作了。感谢@highstakes的帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接