Search code examples
javamysqlhibernatejpaeclipselink

Insert data using JPA one to one mapping along with mysql composite primary keys


i want to insert data using JPA one to one mapping along with composite primary key in mysql .Already lot of questions asked for the same topic in this forum, but that not helped for me.

But i got exceptions like "illegal argument exception is not a known entity type jpa" and "Table 'callredirect.callredirect_callredirectgroup' doesn't exist" My mysql tables:

CREATE TABLE IF NOT EXISTS `CallRedirect` (
  `redirect_id` varchar(20) NOT NULL,
  `ric` varchar(20) NOT NULL,
  `tgrp` varchar (20) NOT NULL,
  `loop_ind` varchar(4) NOT NULL,
  PRIMARY KEY (`redirect_id`));


CREATE TABLE IF NOT EXISTS `CallRedirectGroup` (
  `msisdn` varchar(20) NOT NULL,
  `redirect_id` varchar(20) NOT NULL ,
PRIMARY KEY (`msisdn`,`redirect_id`),
FOREIGN KEY (redirect_id) REFERENCES CallRedirect(redirect_id));    

CallRedirect.java:

package com.sample.rest.dao.entity;
import java.io.Serializable;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.QueryHint;
import javax.persistence.Table;

import org.codehaus.jackson.annotate.JsonProperty;
import org.eclipse.persistence.annotations.PrivateOwned;


@Entity
@NamedQueries({
        @NamedQuery(name = "getCallRedirectById", query = "SELECT a FROM CallRedirect a WHERE a.redirect_id=:redirect_id", hints = @QueryHint(name = "eclipselink.refresh", value = "true")),
        @NamedQuery(name = "getAllCallRedirect", query = "SELECT a FROM CallRedirect a order by a.redirect_id", hints = @QueryHint(name = "eclipselink.refresh", value = "true"))
       //@NamedQuery(name = "deleteCallRedirectById", query = "DELETE a FROM CallRedirect a WHERE a.redirect_id=:redirect_id", hints = @QueryHint(name = "eclipselink.refresh", value = "true"))
})


@Table(name = "callRedirect")
public class CallRedirect implements Serializable{

@Id
@JsonProperty("redirect_id")
@Column(name = "redirect_id")
private String redirect_id;

@Column(name = "ric")
@JsonProperty("ric")
private String ric;

@Column(name = "tgrp")
@JsonProperty("tgrp")
private String tgrp;

@Column(name = "loop_ind")
@JsonProperty("loop_ind")
private String loop_ind;



@OneToOne(mappedBy = "callRedirect", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@PrivateOwned
private List<CallRedirectGroup> callRedirectGroupEntity;


public CallRedirect() {
    super();
    } 

/**
 * @return the redirect_id
 */
public String getRedirectId()
{
    return redirect_id;
}

/**
 * @param redirect_id
 *            the redirect_id to set
 */
public void setRedirectId(String redirect_id)
{
    this.redirect_id = redirect_id;
}

/**
 * @return the ric
 */
public String getRic()
{
    return ric;
}

/**
 * @param ric
 *            the ric to set
 */
public void setRic(String ric)
{
    this.ric = ric;
}

/**
 * @return the tgrp
 */
public String getTgrp()
{
    return tgrp;
}

/**
 * @param tgrp
 *            the tgrp to set
 */
public void setTgrp(String tgrp)
{
    this.tgrp = tgrp;
}

/**
 * @return the loop_ind
 */
public String getLoopInd()
{
    return loop_ind;
}

/**
 * @param loop_ind
 *            the loop_ind to set
 */
public void setLoopInd(String loop_ind)
{
    this.loop_ind = loop_ind;
}

/**
 * @return the callRedirectGroupEntity
 */
 public List<CallRedirectGroup> getCallRedirectGroupEntity()
{
    return callRedirectGroupEntity;
} 

/**
 * @param callRedirectGroupEntity
 *            the callRedirectGroupEntity to set
 */
public void setCallRedirectGroupEntity(List<CallRedirectGroup> callRedirectGroupEntity)
{
    this.callRedirectGroupEntity = callRedirectGroupEntity;
}

@Override
public String toString()
{
    return "CallRedirect :: redirect_id: " + redirect_id + ", Ric : " + ric + ", Tgrp : " + tgrp + ", loop_ind : "
            + loop_ind;
}

}

CallRedirectGroup.java:

package com.sample.rest.dao.entity;
import java.io.Serializable;
import java.util.*;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedNativeQueries;
import javax.persistence.NamedNativeQuery;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.QueryHint;
import javax.persistence.Table;

import org.codehaus.jackson.annotate.JsonProperty;
import org.eclipse.persistence.annotations.PrivateOwned;


@Entity
@NamedQueries({
    @NamedQuery(name = "getRedirectIdByMSISDN", query = "SELECT a FROM CallRedirectGroup a WHERE a.msisdn=:msisdn", hints = @QueryHint(name = "eclipselink.refresh", value = "true"))
    //@NamedQuery(name = "getAllCallRedirect", query = "SELECT a FROM CallRedirectGroup a order by a.redirect_id", hints = @QueryHint(name = "eclipselink.refresh", value = "true")),
    })
@NamedNativeQueries({
    @NamedNativeQuery(
            name    =   "createNewCallRedirectGroup",
            query   =   "INSERT INTO CallRedirect(redirect_id,ric,tgrp,loop_ind) VALUES (?,?,?,?)"
            ,resultSetMapping = "updateResult"
    )
})

@Table(name = "CallRedirectGroup")
public class CallRedirectGroup implements Serializable{

@Id
@Column(name = "msisdn")
@JsonProperty("msisdn")
private String msisdn;


@OneToOne
@JoinColumn(name = "redirect_id")
private CallRedirect callRedirect;

public CallRedirectGroup() {
    super();
    } 
public String getMsisdn()
{
    return msisdn;
}

public void setMsisdn(String msisdn)
{
    this.msisdn = msisdn;
}

public CallRedirect getCallRedirect()
{
    return callRedirect;
}

public void setCallRedirect(CallRedirect callRedirect)
{
    this.callRedirect = callRedirect;
    /*List<CallRedirectGroup> list = new ArrayList<CallRedirectGroup>();
    list.add(this);
    this.callRedirect.setCallRedirectGroupEntity(list);*/
}
@Override
public String toString()
{
    return "CallRedirectGroup - " + callRedirect + ", Msisdn : " + msisdn;
}
}

CallRedirectDAO.java:

    public class CallRedirectDaoImpl implements CallRedirectDao{
@PersistenceContext(unitName = "CALLREDIRECT_PERSISTENCE_READ")
private EntityManagerFactory entityManagerFactoryRead = Persistence.createEntityManagerFactory("CALLREDIRECT_PERSISTENCE_READ");
EntityManager entityManager = entityManagerFactoryRead.createEntityManager();
public boolean createNewRedirectGroup(CallRedirectGroup callredirectgroup) {
    boolean result = false;
     try
        {


        List<CallRedirectGroup> list = new ArrayList<CallRedirectGroup>();
            list.add(callredirectgroup);
         CallRedirect callredirect = callredirectgroup.getCallRedirect();

         callredirect.setCallRedirectGroupEntity(list);
         entityManager.getTransaction().begin();


         entityManager.persist(callredirect);
         entityManager.persist(callredirectgroup);
         entityManager.getTransaction().commit();
         entityManager.flush();
         result = true;
    }
     catch (PersistenceException persistenceException)
        {
         result = false;
            if(entityManager.getTransaction().isActive())
                entityManager.getTransaction().rollback();
            LOGGER.log(Level.SEVERE, "Unexpected error while creating new callRedirectGroup: " +callredirectgroup);
        }
        catch (Exception e)
        {
            result = false;
            if(entityManager.getTransaction().isActive())
                entityManager.getTransaction().rollback();
            LOGGER.log(Level.SEVERE, " while creating new callRedirectGroup, Exception = ", e);
        }
        finally
        {
            entityManager.clear();
        }
        return result;

}

Persistence.xml:

    <?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
    <persistence-unit name="CALLREDIRECT_PERSISTENCE_READ"  transaction-type="JTA">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <jta-data-source>jdbc/callRedirectRead</jta-data-source>
        <class>com.sample.rest.dao.entity.CallRedirect</class>
        <class>com.sample.rest.dao.entity.CallRedirectGroup</class>
        <exclude-unlisted-classes>false</exclude-unlisted-classes>      
        <properties>
            <property name="eclipselink.jpa.uppercase-column-names" value="false"/>
        </properties>   
    </persistence-unit>
</persistence>

INPUT as JSON:

{
"callRedirect": {
"redirect_id": "RED002",
"ric": "ric1",
"tgrp": "tgrp1",
"loop_ind": "TES" 
},
    "msisdn": "887055"

}

Exception:

1.javax.persistence.RollbackException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.0.2.v20100323-r6872): org.eclipse.persistence.exceptions.DatabaseException Internal Exception: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Table 'callredirect.callredirect_callredirectgroup' doesn't exist Error Code: 1146 Call: INSERT INTO callRedirect_CallRedirectGroup (callRedirectGroupEntity_msisdn, CallRedirect_redirect_id) VALUES (?, ?) bind => [887055, RED002] Query: DataModifyQuery(sql="INSERT INTO callRedirect_CallRedirectGroup (callRedirectGroupEntity_msisdn, CallRedirect_redirect_id) VALUES (?, ?)")

2.java.lang.IllegalArgumentException: Object: CallRedirect :: redirect_id: RED003, Ric : ric1, Tgrp : tgrp1, loop_ind : TES is not a known entity type.


Solution

  • you are using OneToOne for list , you should be using OneToMany and ManyToOne

    @OneToMany(mappedBy = "callRedirect", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @PrivateOwned
    private List<CallRedirectGroup> callRedirectGroupEntity;
    
    
    
    @ManyToOne
    @JoinColumn(name = "redirect_id")
    private CallRedirect callRedirect;