如何使用JPA继承制作Json结果(spring boot)

问题描述 投票:0回答:2

当我使用 JPA 继承表时,出现有关“findAll”的错误。

我是什么让 Json 结果像这样 ["asdf" : "adf", "asdf" : "asdf"]

但返回值类似于 [com.example.model.AccountEntity@57af674a]

控制器

@RequestMapping(value = "/getMyInfoall", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getMemberall(@RequestBody JSONObject sendInfo) throws IOException {

        List user = UserService.findAll();
        
        JSONObject result = new JSONObject();
        result.put("data", user);

        return result.toJSONString();
    }

服务

public List findAll() {
    List users = UserRepository.findAll();
    return users;
}

存储库

@Repository
public interface UserRepository extends JpaRepository<UserEntity, Long> {
}

实体

@Entity(name = "Users")
@Inheritance(strategy = InheritanceType.JOINED)
public class UserEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private int userkey;

    @Column(nullable = false, unique = true)
    private String id;

    @Column(nullable = false, length = 50)
    private String name;

    @Column(nullable = false)
    private String password;

    @Column(nullable = true)
    private String email;
}

@Entity(name = "Account")
public class AccountEntity extends UserEntity{

    @Column(nullable = false, unique = true)
    private String accountno;

    @Column(nullable = true)
    private String accountname;

    @Column(nullable = false)
    private int accountpw;

    @Column(nullable = false)
    private long balance;
}```
java json spring-boot jpa inheritance
2个回答
1
投票

我强烈建议使用 Spring 的默认值

HTTPMessageConverter
s,例如Jackson 用于 JSON。

从列表构建 JSON 数组

但是您也可以使用 JSON.org 的轻量级库,如 JSON-java README 中的指导:

  1. List
     转换为数组,例如
    UserEntity[]
    
    
  2. 从此 Java 数组创建一个
  3. JSONArray
     
  4. 使用方法
  5. toString() 返回格式化为字符串的 JSON 数组
    representation
List<UserEntity> userList = // a list returned from your database/repo UserEntity[] myArr = userList.toArray(new UserEntity[userList.size()]); // (1) convert this to an array JSONArray json = new JSONArray(myArr); // (2) follow the guide on JSON return json.toString(); // (3) return the JSON-array as string
    

0
投票
您应该将

UserEntity

 对象转换为 
UserDto
 DTO,然后将其返回到控制器中。依靠 
Jackson 而不是由您管理和创建的 JSONObject

public class UserDto { private String id; private String name; }
您的服务应该进行映射:

public List<UserDto> findAll() { List<UserEntity> users = UserRepository.findAll(); return users.stream().map(user -> // your mapping logic to UserDto object); }
你的控制器只需要返回它:

@RequestMapping(value = "/getMyInfoall", produces = MediaType.APPLICATION_JSON_VALUE) public List<UserDto> getMemberall(@RequestBody JSONObject sendInfo) throws IOException { return UserService.findAll(); }
您可以使用 

JSONObject sendInfo

 执行类似的操作,并将其替换为您自己的对象。

© www.soinside.com 2019 - 2024. All rights reserved.