Home > Software engineering >  one to many and many to one mapping inserts null values in database
one to many and many to one mapping inserts null values in database

Time:10-25

I have 3 model classes as UserBean , PolicyBean and RequestedPoliciesForUserBean. userId is the primary key for userBean class. policyNo is the primary key for PolicyBean class. transactionId is the primary key for RequestedPoliciesForUserBean class. The three model classes are as below with getter and setters (not showing getters and setters for better readability)

@Table(name="users")
public class UserBean  {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY,generator = "native")
    @GenericGenerator(name = "native", 
                      strategy = "com.example.policymanagementsystem.idgenerator.UserIdGenerator",
                      parameters = {
                              @Parameter(name = UserIdGenerator.INCREMENT_PARAM, value = "50"),
                              @Parameter(name = UserIdGenerator.VALUE_PREFIX_PARAMETER,value="USER_"),
                              @Parameter(name = UserIdGenerator.NUMBER_FORMAT_PARAMETER, value ="d"),
                      })
    @Column(name="userId")
    private String userId;
    
    
    @Size(min = 2 , max = 30, message = "must have atleast 2 characters and maximum 30")
    @Column(name="name")
    private String name;
    
    
    @Column(name="age")
    private String age;
    
    
    @Column(name="city")
    private String city;
    
    
    @JsonFormat(shape = JsonFormat.Shape.STRING,pattern = "yyyy-MM-dd")
    @DateTimeFormat(pattern = "dd-MM-yyyy")
    @Column(name="dateOfBirth")
    private Date dateOfBirth;
    
    @Size(max = 10 , message = "phone number must have 10 numbers")
    @Column(name="phone")
    private String phone;
    
    @Email
    @Column(name="email")
    private String email;

    @Pattern(regexp="^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#&()–[{}]:;',?/*~$^ =<>]).{8,60}$", message = "password must have atleast 1 digit,1 upper case & 1 lower case letter,"
              "1 special character,"
              "no whitespace & minimum 8 & maximum 20 characters")
    @NotNull(message="password cannot be null")
    @Column(name="encodedPassword")
    private String password;
    
    @OneToMany(mappedBy = "users" , cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private Set<RequestedPoliciesForUserBean> requestedPoliciesForUserBean;
    
    
    @NotNull(message = "role cannot be null")
    @Column(name = "role")
    @Enumerated(EnumType.STRING)
    private Role role;
@Entity
@Table(name="policy")
public class PolicyBean {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY,generator = "native")
    @GenericGenerator(name = "native", 
                      strategy = "com.example.policymanagementsystem.idgenerator.PolicyIdGenerator",
                      parameters = {
                              @Parameter(name = PolicyIdGenerator.INCREMENT_PARAM, value = "50"),
                              @Parameter(name = PolicyIdGenerator.VALUE_PREFIX_PARAMETER,value="POLICY_"),
                              @Parameter(name = PolicyIdGenerator.NUMBER_FORMAT_PARAMETER, value ="d"),
                      })
    @Column(name="policyNo")
    private String policyNo;
    
    @Size(min = 2 , max = 30, message = "must have atleast 2 characters and maximum 30")
    @Column(name="planName")
    private String planName;
    
    @Min(value = 1, message = "tenure cannot be zero")
    @Column(name="tenure")
    private String tenure;
    
    @OneToMany(mappedBy = "policy" , cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private Set<RequestedPoliciesForUserBean> requestedPoliciesForUserBean;
@Entity
@Table(name="requestedpoliciesforuser")
public class RequestedPoliciesForUserBean {
    
    @GeneratedValue(strategy = GenerationType.IDENTITY,generator = "native")
    @GenericGenerator(name = "native", 
                      strategy = "com.example.policymanagementsystem.idgenerator.TransactionIdGenerator",
                      parameters = {
                              @Parameter(name = UserIdGenerator.INCREMENT_PARAM, value = "50"),
                              @Parameter(name = UserIdGenerator.VALUE_PREFIX_PARAMETER,value="TRANS_"),
                              @Parameter(name = UserIdGenerator.NUMBER_FORMAT_PARAMETER, value ="d"),
                      })
    @Column(name="transactionId")
    @Id
    private String transactionId;
    
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "userId", nullable = false)
    private UserBean users;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "policyNo", nullable = false)
    private PolicyBean policy;
    
    @Column(name = "planName")
    private String planName;
    
    @Column(name = "tenure")
    private String tenure;
    
    @Enumerated(EnumType.STRING)
    private PolicyStatus policyStatus;

I have three database tables as users, policy, requestedpoliciesforusers. userId(primary key in users table) and policyNo(primary key in policy table) are the foreign keys references for requestedpoliciesforusers table. One user can request for multiple policies and when user will request policy the data will get inserted in requestedpoliciesforusers table along with userId and policNo.Somewhat the scenario will be as below. | User | Policy | |------|--------| | 1 | A | | 1 | B | | 2 | A | | 3 | B | | 1 | C | But hibernate is inserting null values for userId and policyNo but all other fields are getting inserted properly. Below is the screenshot for the same. Database

My Postman request is as below:

{
    "userId":"USER_02902",
    "policyNo":"POLICY_00001",
    "planName":"Recurring Deposit Plan",
     "tenure":"20"
}

Please suggest why null values are getting inserted in database. Any changes required in one to many or many to one mapping. Thanks in Advance!

RequestedPoliciesForUserController

@RestController
@RequestMapping("/user")
public class RequestedPoliciesForUserController {
    
    @Autowired
    private RequestedPoliciesForUserService requestedPoliciesForUserService;
    

    @PutMapping(path="/policy/request",consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
 public PolicyResponses requestPolicy(@RequestBody RequestedPoliciesForUserBean requestedPoliciesForUser) {
        PolicyResponses policyResponses = new PolicyResponses();
        boolean isPolicyRequested = requestedPoliciesForUserService.requestPolicy(requestedPoliciesForUser);
        if(isPolicyRequested) {
            policyResponses.setStatusCode(200);
            policyResponses.setMessage("request sent");
            policyResponses.setDescription("Policy request sent successfully");
        }
        return policyResponses;
    }
}

RequestedPoliciesForUserServiceImpl

@Service
public class RequestedPoliciesForUserServiceImpl implements RequestedPoliciesForUserService {

    @Autowired
    RequestedPoliciesForUserDAO requestedPoliciesForUserDAO;
    
    @Override
    
    public boolean requestPolicy(RequestedPoliciesForUserBean requestedPoliciesForUserBean) {
        // TODO Auto-generated method stub
        return requestedPoliciesForUserDAO.requestPolicy(requestedPoliciesForUserBean);
    }

}

RequestedPoliciesForUserDAOImpl

@Repository
public class RequestedPoliciesForUserDAOImpl implements RequestedPoliciesForUserDAO {
    
    @PersistenceUnit
    private EntityManagerFactory entityManagerFactory;
    
    @Override
    public boolean requestPolicy(RequestedPoliciesForUserBean requestedPoliciesForUserBean) {
        
        
            EntityManager entityManager = null;
             EntityTransaction entityTransaction = null;
            boolean isPolicyRequested = false;
            
            try {
                entityManager=entityManagerFactory.createEntityManager();
                entityTransaction=entityManager.getTransaction();
                entityTransaction.begin();
                System.out.println(requestedPoliciesForUserBean);
              
                requestedPoliciesForUserBean.setPolicyStatus(PolicyStatus.PENDING);
                entityManager.persist(requestedPoliciesForUserBean);
                entityTransaction.commit();
                entityManager.close();
                isPolicyRequested =true;
        } catch (Exception e) {
            e.printStackTrace();
        }
            return false;
        } // end of requestPolicy()
    }

Postman Response

{
    "statusCode": 0,
    "message": null,
    "description": null,
    "policyList": null
}

CodePudding user response:

Create PK argument constructor in both the PolicyBean and UserBean classes. Also, the request in postman is not matching the RequestedPoliciesForUserBean. You pass userId and the class has users, policyNo and the class have policy.

UserBean constructor:

public UserBean(String userId) {
    this.userId = userId;
}

PolicyBean constructor:

public PolicyBean(String policyNo) {
    this.policyNo = policyNo;
}

Change your request JSON to:

{
    "users": "USER_02902",
    "policy": "POLICY_00001",
    "planName": "Recurring Deposit Plan",
    "tenure": "20"
}

It will save data in all columns of your requestedpoliciesforuser table. Also instead of using entitymanager directly use JPA. Spring Data JPA

  • Related