package com.example.demo.config; import com.example.demo.model.Comp; import com.example.demo.model.Person; import org.apache.catalina.User; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.rest.core.config.RepositoryRestConfiguration; import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer; import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapter; /** * @Author:LJ * @Description:为了解决Spring Data Rest不暴露ID字段的问题。 * 参考:http://tommyziegler.com/how-to-expose-the-resourceid-with-spring-data-rest/ * @Date: 2018/3/21 * @Modified By: */ @Configuration public class SpringDataRestConfig { @Bean public RepositoryRestConfigurer repositoryRestConfigurer() { return new RepositoryRestConfigurerAdapter() { @Override public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) { config.exposeIdsFor(User.class, Person.class, Comp.class); } }; } }
场景问题如下:
<!--通过REST 风格接口 暴露Spring Data数据库表--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-rest</artifactId> </dependency>
package com.example.demo.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class User { @Id @GeneratedValue private long id; @Column(nullable = false, unique = true) private String userName; @Column(nullable = false) private String password; @Column(nullable = false) private int age; public long getId() { return id; } public User setId(long id) { this.id = id; return this; } public String getUserName() { return userName; } public User setUserName(String userName) { this.userName = userName; return this; } public String getPassword() { return password; } public User setPassword(String password) { this.password = password; return this; } public int getAge() { return age; } public User setAge(int age) { this.age = age; return this; } }
package com.example.demo.repository; import com.example.demo.model.User; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<User, Long> { User findById(long id); void deleteById(long id); }
运行http://localhost:8080/users,结果
{ "_embedded" : { "user" : [ { "age" : "12", "password":"12345", "user_name":"lisi" }, { "age" : "25", ...... }