为什么子实体的id在EclipseLink中的响应消息中返回0?

时间:2018-07-29 12:55:05

标签: jpa eclipselink one-to-one

我正在使用我的Member表和MemberRoles表之间的一对一关联。我希望他们在数据库中共享与PK和FK相同的ID,并做到了。但是我还有另一个问题。当我插入成员时,将同时插入一个MemberRole记录,并且该成员记录在返回响应中具有正确的ID,但是MemberRole ID不正确。它返回0,如下所示:

{
    "result": "Bulk user member saving is successfull. Members' informations are:",
    "memberList": [
        {
            "id": 2,
            "firstName": "Michael",
            "lastName": "Schumacher",
            "email": "ilkay.gune2l@kod5.org",
            "enabled": false,
            "memberLanguageCode": "tr",
            "roleOfMember": {
                "id": 0,
                "email": "ilkay.gune2l@kod5.org",
                "role": "ROLE_USER"
            }
        }
    ]
}

我的会员实体类:

package com.ilkaygunel.entities;

import java.time.LocalDateTime;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;

@Entity
@JsonInclude(Include.NON_NULL)
@NamedQueries({ @NamedQuery(name = "Member.findAll", query = "select m from Member m"),
        @NamedQuery(name = "Member.findByFirstName", query = "select m from Member m where m.firstName =:firstName"),
        @NamedQuery(name = "Member.findPasswordOfMember", query = "select m.password from Member m where m.id =:id"),
        @NamedQuery(name = "Member.findByActivationToken", query = "select m from Member m where m.activationToken =:activationToken"),
        @NamedQuery(name = "Member.findByEmail", query = "select m from Member m where m.email =:email") })
@Table(name = "MEMBER")
public class Member {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "MEMBER_ID")
    private long id;
    @Column(nullable = false)
    private String firstName;
    @Column(nullable = false)
    private String lastName;
    @Column(nullable = false, updatable = false)
    private String email;
    @Column(nullable = false, updatable = false)
    private boolean enabled;
    @Column(nullable = false)
    private String password;
    @Column(nullable = false)
    private String memberLanguageCode;
    @Column(updatable = false)
    @JsonIgnore
    private String activationToken;
    @Column(updatable = false)
    @JsonIgnore
    private LocalDateTime activationTokenExpDate;

    @OneToOne(cascade = CascadeType.ALL, mappedBy = "member", optional = false)
    @PrimaryKeyJoinColumn(name = "MEMBER_ID")
    private MemberRoles roleOfMember;

    @Override
    public String toString() {
        return String.format("Member [id=%d, firstName='%s', lastName='%s', email='%s']", id, firstName, lastName,
                email);
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
        if (null != roleOfMember) {
            roleOfMember.setId(id);
        }
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public MemberRoles getRoleOfMember() {
        return roleOfMember;
    }

    public void setRoleOfMember(MemberRoles roleOfMember) {
        this.roleOfMember = roleOfMember;
    }

    public String getActivationToken() {
        return activationToken;
    }

    public void setActivationToken(String activationToken) {
        this.activationToken = activationToken;
    }

    public LocalDateTime getActivationTokenExpDate() {
        return activationTokenExpDate;
    }

    public void setActivationTokenExpDate(LocalDateTime activationTokenExpDate) {
        this.activationTokenExpDate = activationTokenExpDate;
    }

    public String getMemberLanguageCode() {
        return memberLanguageCode;
    }

    public void setMemberLanguageCode(String memberLanguageCode) {
        this.memberLanguageCode = memberLanguageCode;
    }
}

还有我的MemberRoles实体类:

package com.ilkaygunel.entities;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.MapsId;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;

import com.fasterxml.jackson.annotation.JsonIgnore;

@Entity
@NamedQueries({
        @NamedQuery(name = "MemberRoles.findByEmail", query = "select mr from MemberRoles mr where mr.email = :email") })
@Table(name = "MEMBERROLES")
public class MemberRoles {
    @Id
    @Column(name = "MEMBERROLES_ID")
    private long id;
    private String email;
    private String role;

    @MapsId
    @OneToOne(optional = false)
    @JoinColumn(name = "MEMBERROLES_ID", unique = true, nullable = false, updatable = false)
    @JsonIgnore
    private Member member;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    public Member getMember() {
        return member;
    }

    public void setMember(Member member) {
        this.member = member;
    }
}

当我插入成员记录时,我在数据库上对其进行了检查,然后看到Member和MemberRoles记录具有相同的ID。但是,为什么响应消息中的MemberRoles区域的ID为0?

我的MemberSaveService类是这样的:

package com.ilkaygunel.service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.mail.MessagingException;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import com.ilkaygunel.constants.ConstantFields;
import com.ilkaygunel.entities.Member;
import com.ilkaygunel.entities.MemberRoles;
import com.ilkaygunel.exception.CustomException;
import com.ilkaygunel.exception.ErrorCodes;
import com.ilkaygunel.pojo.MemberOperationPojo;

@Service
public class MemberSaveService extends BaseService {

    public MemberOperationPojo addUserMember(List<Member> memberList) {
        return addBulkMember(memberList, ConstantFields.ROLE_USER.getConstantField());
    }

    public MemberOperationPojo addAdminMember(List<Member> memberList) {
        return addBulkMember(memberList, ConstantFields.ROLE_ADMIN.getConstantField());
    }

    public MemberOperationPojo addBulkMember(List<Member> memberList, String role) {
        Logger LOGGER = loggingUtil.getLoggerForMemberSaving(this.getClass());
        LOGGER.log(Level.INFO, resourceBundleMessageManager.getValueOfProperty(role + "_bulkMemberAddingMethod", "en"));
        MemberOperationPojo memberOperationPojo = new MemberOperationPojo();
        List<Member> savedMemberList = new ArrayList<>();
        try {
            memberUtil.checkEmailAddressAndLanguageOnMemberList(memberList, LOGGER);
            for (Member member : memberList) {
                addOneMember(member, role, LOGGER);
                savedMemberList.add(member);
            }
            memberOperationPojo.setResult(
                    resourceBundleMessageManager.getValueOfProperty(role + "_bulkMemberAddingSuccessfull", "en"));
            memberOperationPojo.setMemberList(memberUtil.removeFieldsFromReturningMember(savedMemberList));
            LOGGER.log(Level.INFO,
                    resourceBundleMessageManager.getValueOfProperty(role + "_bulkMemberAddingSuccessfull", "en")
                            + memberList);
        } catch (CustomException customException) {
            LOGGER.log(Level.SEVERE,
                    resourceBundleMessageManager.getValueOfProperty(role + "_bulkMemberAddingFaled", "en")
                            + customException.getErrorCode() + " " + customException.getErrorMessage());
            memberOperationPojo.setErrorCode(customException.getErrorCode());
            memberOperationPojo.setResult(customException.getErrorMessage());
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE,
                    resourceBundleMessageManager.getValueOfProperty(role + "_bulkMemberAddingFaled", "en")
                            + e.getMessage());
            memberOperationPojo.setErrorCode(ErrorCodes.ERROR_10.getErrorCode());
            memberOperationPojo.setResult(e.getMessage());
        }
        return memberOperationPojo;
    }

    private void addOneMember(Member member, String role, Logger LOGGER) throws MessagingException {
        MemberOperationPojo memberOperationPojo = new MemberOperationPojo();
        LOGGER.log(Level.INFO, resourceBundleMessageManager.getValueOfProperty(role + "_memberAddingMethod",
                member.getMemberLanguageCode()));
        member.setPassword(getHashedPassword(member.getPassword()));
        member.setEnabled(false);
        addMemberRolesObject(role, member);
        addActivationToken(member);
        memberFacade.create(member);
        // mailUtil.sendActivationMail(member.getEmail(), member.getActivationToken());
        memberOperationPojo.setResult(resourceBundleMessageManager.getValueOfProperty(role + "_memberAddingSuccessfull",
                member.getMemberLanguageCode()));
        LOGGER.log(Level.INFO, resourceBundleMessageManager.getValueOfProperty(role + "_memberAddingSuccessfull",
                member.getMemberLanguageCode()) + member);
    }

    private String getHashedPassword(String rawPassword) {
        return new BCryptPasswordEncoder().encode(rawPassword);
    }

    private void addMemberRolesObject(String role, Member member) {
        MemberRoles rolesOfMember = new MemberRoles();
        rolesOfMember.setRole(role);
        rolesOfMember.setEmail(member.getEmail());
        rolesOfMember.setMember(member);
        member.setRoleOfMember(rolesOfMember);
    }

    private void addActivationToken(Member member) {
        String activationToken = UUID.randomUUID().toString();
        member.setActivationToken(activationToken);

        LocalDateTime activationTokenExpDate = LocalDateTime.now().plusDays(1);
        // LocalDateTime activationTokenExpDate = LocalDateTime.now();//Use for expire
        // date test!
        member.setActivationTokenExpDate(activationTokenExpDate);
    }
}

我的Web服务端点类如下:

package com.ilkaygunel.restservice;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.ilkaygunel.entities.Member;
import com.ilkaygunel.pojo.MemberOperationPojo;
import com.ilkaygunel.service.MemberSaveService;

@RestController
@RequestMapping("/memberPostWebServiceEndPoint")
public class MemberSaveWebServiceEndPoint {
    @Autowired
    private MemberSaveService memberSaveService;

    @RequestMapping(value = "/saveUserMember", method = RequestMethod.POST)
    public ResponseEntity<MemberOperationPojo> saveUserMember(@RequestBody List<Member> memberList) {
        MemberOperationPojo memberOperationPojo = memberSaveService.addUserMember(memberList);
        return new ResponseEntity<MemberOperationPojo>(memberOperationPojo, HttpStatus.OK);
    }

    @RequestMapping(value = "/saveAdminMember", method = RequestMethod.POST)
    public ResponseEntity<MemberOperationPojo> saveAdminMember(@RequestBody List<Member> memberList) {
        MemberOperationPojo memberOperationPojo = memberSaveService.addAdminMember(memberList);
        return new ResponseEntity<MemberOperationPojo>(memberOperationPojo, HttpStatus.OK);
    }
}

0 个答案:

没有答案