如何解决从POST / GET请求返回到Spring Boot应用的JSON对象中外键的空值
竞技场的好人!
我遇到了问题,希望您能向我解释我的代码的问题所在。 构建Spring Boot应用程序:对于这个开发阶段,一切都很好,除了我没有从HTTP获取请求的事实之外,这些都是我数据库中现有外键的字段值。我在Google和StackOverflow上度过了一天,没有发现任何提示。
我使用Entity-DTO-ResponceModel--RequestModel模式将数据从有效负载传输到数据库,再传输回数据库。 我使用modelmapper.class进行类之间的映射。 在ServiceImplementation类中执行的所有业务逻辑。
因此,我的实体之间存在多对一关系,这里有一个小问题。通过请求后,我创建了一个新用户,同时创建了用户的私有Group和Event(在UserServiceImpl.class中进行了此操作)。
立即在数据库中创建的所有内容都没有问题。然后,我得到了该新用户的对象,对其进行了转换,并作为响应发送回了前端。所以我有了JSON对象,并在Postman中看到了它。所有字段均已到位,但缺少数据库中存在的几个值,并替换为null。
具体来说-我在此JSOn对象中获取了“ author_id”,“ admin_id”和“ group_id”的空值
{
"publicUserId": "FgKP0BTGqI94nEY","name": "Alex","phone": "222222","email": "333@gmail.com","userMoto": "Go-go forward","usersTodos": null,"usersEvents": [
{
"publicEventId": "zRmVNyS9A32OWPW","nameEvent": "Private","description": "Your lovely private event","dateTimeEventCreated": "2020-08-14T17:13:38.989+00:00","eventTodos": [],"author_id": null,"group_id": null
}
],"usersGroups": [
{
"publicGroupId": "GUDAIeKShEJEOE3","nameGroup": "Private","descriptionGroup": "Your lovely private group","admin_id": null,"groupEvents": [
{
"publicEventId": "zRmVNyS9A32OWPW","group_id": null
}
],"groupTodos": null,"setUsers": []
}
]
}
这些值确实存在于数据库中:
请查看我的课程(我只发布相关课程)。
UserUserClass
@Entity(name = "users_table")
public class UserEntity implements Serializable {
private static final long serialVersionUID = -7109290743784846300L;
//******************Attributes********************
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long databaseUserId;
@Column(nullable = false)
@NaturalId
private String publicUserId;
@Column(nullable = false,length = 50)
private String name;
@Column(nullable = false,length = 10)
private String phone;
@Column(nullable = false,length = 20)
private String email;
@Column(nullable = false,length = 150)
private String userMoto;
@Column (nullable = false,length = 150)
private String encryptedPassword;
//***************** ASSOCIATIONS *******************
@OnetoMany(mappedBy = "creatorDetails",cascade = CascadeType.ALL)
private List<TodoEntity> usersTodos;
@OnetoMany(mappedBy = "adminDetails",cascade = CascadeType.ALL)
private List<GroupEntity> usersGroups;
@OnetoMany(mappedBy = "creatorDetails",cascade = CascadeType.ALL,fetch = FetchType.LAZY)
private List<EventEntity> usersEvents;
// -------------------many_to_many----------------------
@ManyToMany(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
@JoinTable(name = "event_users",joinColumns = {@JoinColumn(name = "event_id")},inverseJoinColumns = {@JoinColumn(name = "user_id")} )
private Set <EventEntity> setEvents = new HashSet<>();
@ManyToMany(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
@JoinTable(name = "group_users",joinColumns = {@JoinColumn(name = "group_id")},inverseJoinColumns = {@JoinColumn(name = "user_id")} )
private Set <GroupEntity> setGroups = new HashSet<>();
UserDto.class
import java.io.Serializable;
import java.util.List;
import lab.alex.todo.io.entity.TodoEntity;
import lab.alex.todo.ui.model.responce.EventResponceModel;
import lab.alex.todo.ui.model.responce.GroupResponceModel;
public class UserDto implements Serializable {
private static final long serialVersionUID = -4403819017131408502L;
// ******************Attributes********************
private long databaseUserId;
private String publicUserId;
private String name;
private String phone;
private String email;
private String userMoto;
private String password;
private String encryptedPassword;
// *****************Association*******************
private List<TodoDto> usersTodos;
private List<EventResponceModel> usersEvents;
private List<GroupResponceModel> usersGroups;
// **************** Accessors **********************
UserResponceModel.class
public class UserResponceModel {
//******************Attributes********************
private String publicUserId;
private String name;
private String phone;
private String email;
private String userMoto;
private List<TodoResponceModel> usersTodos;
private List<EventResponceModel> usersEvents;
private List<GroupResponceModel> usersGroups;
//****************Accessors************************
EventEntity.class
@Entity
@Table(name="events_table")
public class EventEntity implements Serializable{
private static final long serialVersionUID = 2697897580625213781L;
//******************Attributes********************
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long databaseEventId;
@Column(nullable = false)
@NaturalId
private String publicEventId;
@Column(nullable = false,length = 50)
private String nameEvent;
@Column(length = 100)
private String description;
@Column (nullable = false,length = 30)
@JsonFormat(shape = Shape.STRING,pattern = "dd-MM HH:mm,timezone = UTC")
private Date dateTimeEventCreated;
//*****************Association*******************
@OnetoMany(mappedBy = "eventDetails",cascade = CascadeType.ALL)
private List<TodoEntity> eventTodos;
//---------------------------
@ManyToOne
@JoinColumn(name = "author_id",nullable = false,referencedColumnName = "publicUserId")
private UserEntity creatorDetails;
@ManyToOne
@JoinColumn(name = "group_id",referencedColumnName = "publicGroupId")
private GroupEntity eventGroupDetails;
//---------------------------------
@ManyToMany(fetch = FetchType.LAZY,mappedBy = "setEvents")
private Set <UserEntity> setUsers = new HashSet<>();
EventDto.class
public class EventDto {
//********************Attributes***************
private long databaseEventId;
private String publicEventId;
private String nameEvent;
private String description;
private Date dateTimeEventCreated;
//*****************Association*******************
private List<TodoDto> eventTodos;
//---------------------------
private String author_id;
private String group_id;
EventResponceModel.class
public class EventResponceModel {
//********************Attributes***************
private String publicEventId;
private String nameEvent;
private String description;
private Date dateTimeEventCreated;
//*****************Association*******************
private List<TodoResponceModel> eventTodos;
//---------------------------
private String author_id;
private String group_id;
用于POSTrequest的控制器
@PostMapping
public UserResponceModel createuser(@RequestBody UserDetailsRequestModel userDetailsRequestModel) throws Exception {
UserDto userDto = mapper.map(userDetailsRequestModel,UserDto.class);
UserDto createdUser = userService.createuser(userDto);
UserResponceModel returnValue = mapper.map(createdUser,UserResponceModel.class);
return returnValue;
该控制器的服务方法。在这里,我创建了新用户及其私有组和事件。 提醒一下-一切都将毫无问题地保存到数据库中。
@Service
public class UserServiceImpl implements UserService {
// ********************* DJs *********************
@Autowired
UserRepository userRepository;
@Autowired
GroupRepository groupRepository;
@Autowired
EventRepository eventRepository;
@Autowired
Utils utils;
@Autowired
modelmapper mapper;
@Autowired
BCryptPasswordEncoder passwordEncoder;
// **************** Methods ***************
@Override
public UserDto createuser(UserDto userDto) throws Exception {
UserDto returnValue = new UserDto();
if (userRepository.findByEmail(userDto.getEmail()) != null)
throw new Exception("User already exists!");
UserEntity newUser = mapper.map(userDto,UserEntity.class);
// Set Public_User_Id and encrypt users password
String publicUserId = utils.generatePublicId();
String encryptedPassword = passwordEncoder.encode(userDto.getpassword());
newUser.setPublicUserId(publicUserId);
newUser.setEncryptedPassword(encryptedPassword);
// Save new user to DB
UserEntity createdUser = userRepository.save(newUser);
// ********************* Create new Private group *********************
GroupEntity newPrivateGroup = new GroupEntity();
// Set the Admin Id
newPrivateGroup.setAdminDetails(userRepository.findByPublicUserId(publicUserId));
// Set the name as Private
newPrivateGroup.setNameGroup("Private");
// Set the description
newPrivateGroup.setDescriptionGroup("Your lovely private group");
// Set public id
newPrivateGroup.setPublicGroupId(utils.generatePublicId());
// Save new Group to DB
GroupEntity createdGroup = groupRepository.save(newPrivateGroup);
// ******************** Create Private Event ************************
EventEntity newPrivatEvent = new EventEntity();
// Set the Author Database Id (foreign Key)
newPrivatEvent.setCreatorDetails(userRepository.findByPublicUserId(publicUserId));
// Set Group Details
newPrivatEvent.setEventGroupDetails(createdGroup);
// set name as Private
newPrivatEvent.setNameEvent("Private");
// Set the description
newPrivatEvent.setDescription("Your lovely private event");
// Set Public_Event_Id
newPrivatEvent.setPublicEventId(utils.generatePublicId());
// Set Date created as current date
newPrivatEvent.setDateTimeEventCreated(new Date());
// Set an mpty List of todos
newPrivatEvent.setEventTodos(new ArrayList<TodoEntity>());
// Save new Event to DB
EventEntity createdEvent = eventRepository.save(newPrivatEvent);
// ***************** Add created Event to the List of Events in the cretedGroup
List<EventEntity> listEvents = new ArrayList<>();
listEvents.add(createdEvent);
createdGroup.setGroupEvents(listEvents);
// Update created Group
createdGroup = groupRepository.save(createdGroup);
// Add created Group and Event to the lists of groups and events of this user
createdUser.setUsersEvents(listEvents);
List<GroupEntity> listGroups = new ArrayList<>();
listGroups.add(createdGroup);
createdUser.setUsersGroups(listGroups);
// Update createdUser,convert and send back
createdUser = userRepository.save(createdUser);
returnValue = mapper.map(createdUser,UserDto.class);
return returnValue;
}
请给我指出问题出在哪里。我唯一的猜测是这是ModellMapper问题。并且我需要创建一个自定义映射器。但我对此感到怀疑
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。