I'm facing problem on one to one relationship. I have 2 tables, one Article which has 1 FK "FICHE_ID" refrences to the second table's id Fiche(ID_FICHE) and the problem is that JPA is not mapping on the right field, it's taking ID_ARTICLE to map ID_FICHE instead of FICHE_ID.
This is the code below :
#Entity
#Table(name="ARTICLE")
public class Article implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="ID_ARTICLE")
Integer id=0;
#Column(name="ENTREPRISE")
private String entreprise;
#Column(name="CODE_ARTICLE")
private String code;
#Column(name="LIBELLE_ARTICLE")
private String libelle;
#Column(name="ROLE_READ")
private String role;
#Column(name="PRIX")
private int prix;
#Column(name="OBLIGATOIRE")
private String obligatoire;
#NaturalId
#Column(name="TAILLE_CODE")
private String tailleCode;
#NaturalId
#Column(name="FICHE_ID")
private Integer ficheId;
#OneToOne(fetch = FetchType.EAGER,mappedBy="article")
FicheArticle fiche;
And
#Entity
#Table(name="FICHE")
public class FicheArticle {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="ID_FICHE",insertable = false,updatable = false)
private Integer id=0;
#Lob
#Column(name="FICHE",insertable = false,updatable = false)
private byte[] fiche;
#Lob
#Column(name="FICHE")
private Blob ficheBlob;
#Column(name="ENTREPRISE")
private String entreprise;
#OneToOne
#JoinColumn(name="ID_FICHE", referencedColumnName = "FICHE_ID")
private Article article;
Please, can you help me ?
I am not positive I understand your question; but it looks like a few things need to be changed. Since the foreign key is held by the ARTICLE table, you cannot use mappedBy on the Article.fiche mapping. Instead, you should specify the appropriate join column on Article.fiche and mappedBy on Fiche.article:
#Entity
#Table(name = "ARTICLE")
public class Article implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID_ARTICLE")
Integer id = 0;
// ...
#OneToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "FICHE_ID", referencedColumnName = "ID_FICHE")
FicheArticle fiche;
And
#Entity
#Table(name = "FICHE")
public class FicheArticle {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID_FICHE", insertable = false, updatable = false)
private Integer id = 0;
// ...
#OneToOne(mappedBy = "fiche")
#JoinColumn(name="ID_FICHE", referencedColumnName = "FICHE_ID")
private Article article;
Also, I'm guessing Article.ficheId is not a #NaturalId for Article; so you should simply remove the field (and its mapping).
Related
I have a database diagram, which i need to implement in Entity classes
Diagram image
User entity:
#Entity
class User (
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
val idUser: Int = -1,
#Column(unique=true)
val name: String = "",
#Column(unique=true)
val email: String = "",
#Column(nullable = false)
val password: String = ""
)
Post entity:
User entity:
#Entity
data class Post (
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
val idPost: Int = -1,
#Column(nullable = false)
val title: String = "",
#Column(nullable = false)
val body: String = "",
#Column(nullable = false)
val date: String = Date().toString()
)
I just don't understand how to organize a relationship between tables.
Also IDEA reports an error when a table does not have Primary Key.
Help me with implementation of UserPost Entity class.
SOLVE
Okay, I have a solution, just add a data source (I used MySQL) and use Generate Kotlin Entities.kts then IDEA will automatically create all Entity classes. I think it is the most easy way.
You can define your entities as below with required details such as #columns on attributes and other details.
The below classes are just for reference and to guide on the path.
Please read more about Composite keys and refer the link https://www.baeldung.com/jpa-composite-primary-keys
#Entity
#IdClass(UserPost.class)
public class Post {
#Id
private int idPost;
#Id
private int idUser;
private String title;
private String body;
private LocalDateTime date;
}
#Entity
#IdClass(UserPost.class)
class User{
#Id
private int idPost;
#Id
private int idUser;
private String name;
private String email;
private String password;
}
class UserPost implements Serializable {
private static final long serialVersionUID = 1L;
private int idPost;
private int idUser;
//No-Args constructor and All-Args constructor
//hashcode
//equals
}
Its in java, In kotlin there will not be much diffrence. There is another way to implement the composite key using #Embeddable and #EmbeddableID
I used composit keys but I changed my mind and removed this kind of keys in my web application in NetBeans. But Glassfish says : the module has not been deployed, because of the invalid JoinColumns contents.
Exception Description: The #JoinColumns on the annotated element [field client] from the entity class [class x.ClientOrder] is incomplete. When the source entity class uses a composite primary key, a #JoinColumn must be specified for each join column using the #JoinColumns. Both the name and the referencedColumnName elements must be specified in each such #JoinColumn.
I have removed all of the tables from the DB, restarted the container, called the "Clean and Build" command to the project (it is succeed). But the EJB deployment fails. What should I do for the container forget the past?
The source code of entities:
#Entity
#Getter
#Setter
#Inheritance( strategy = InheritanceType.JOINED )
#DiscriminatorColumn( name = "roleType", discriminatorType = DiscriminatorType.STRING, length = 10 )
#NamedQuery( name=UserRole.QUERYNAME_GET_ROLE_BY_USERID_AND_TYPE, query = "SELECT ur FROM UserRole ur WHERE ur.userWR.id = :userID AND ur.roleType = :roleType" )
abstract public class UserRole implements Serializable
{
private static final long serialVersionUID = 1L;
public static final String QUERYNAME_GET_ROLE_BY_USERID_AND_TYPE = "userRole_getRoleByUserIDAndType";
#Id
#GeneratedValue( strategy = GenerationType.AUTO )
private int id;
#Column
private String roleType;
#Id
#ManyToOne
#JoinColumn( name="user_id", referencedColumnName = "id" )
private UserWithRoles userWR;
}
#Entity
#Data
#NamedQuery( name = Client.QUERYNAME_GET_ALL_CLIENTS, query="SELECT c FROM Client c" )
public abstract class Client extends UserRole
{
public static final String QUERYNAME_GET_ALL_CLIENTS = "client_GetAllClients";
}
#Entity
#Data
#NamedQuery( name=ClientOrder.QUERYNAME_GET_CLIENT_ORDERS, query = "SELECT co FROM ClientOrder co WHERE co.client = :userID" )
public class ClientOrder implements Serializable
{
private static final long serialVersionUID = 1L;
public static final String QUERYNAME_GET_CLIENT_ORDERS = "clientOrders_getClientOrders";
#Id
#GeneratedValue( strategy = GenerationType.AUTO )
private int id;
private String name;
#ManyToOne
#JoinColumn( name = "client_id", referencedColumnName = "id" )
private Client client;
#OneToMany( mappedBy = "clientOrder" )
private List<ClientOrderItem> orderItems;
}
OK. There was an error in the UserRole table. I have forgotten to remove the second #Id annotation on the userWR field. After I have removed it and rebuilt the app it deploys again.
Hello guys I have a problem mapping the typeOneToOne to its class. I have a Person class that a person is married and has an affair with the Same Person class but it is his wife. The foreign key is the name and surname.
#Table(name="PERSON")
public class Person implements Serializable{
#PrimaryKeyJoinColumns({#PrimaryKeyJoinColumn(name="coniuge",referencedColumnName="NAME"),#PrimaryKeyJoinColumn(name="coniuge",referencedColumnName="SURNAME")})
private Person coniuge = null;
#Id
#Column(name="NAME",nullable=false)
private String name;
#Id
#Column(name="SURNAME",nullable=false)
private String surname;
public Person getConiuge() {
return coniuge;}
The manager sevice:
public void aggiungiConiuge(Person coniugeA, Person coniugeB){
manager.getTransaction().begin();
Person cA = manager.find(Person.class, coniugeA);
Person cB = manager.find(Person.class, coniugeB);
cA.setConiuge(cB);
cB.setConiuge(cA);
manager.merge(cA);
manager.getTransaction().commit();
}
how can I solve the problem ?? On DB does not create the two columns (foreign key) with keys Primare's partner (name and surname)
As forename/surname is not guaranteed to be unique use a surrogate key and map as below:
#Table(name = "PERSON")
public class Person implements Serializable {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.AUTO) //or some other strategy
private Long id;
#OneToOne()
#JoinColumn(name = "coniuge_id")
private Person coniuge;
#Column(name = "NAME", nullable = false)
private String name;
#Column(name = "SURNAME", nullable = false)
private String surname;
public void setConiuge(Person coniuge) {
this.coniuge = coniuge;
coniuge.coniuge = this;
}
}
Two problems. 1, you are using PrimaryKeyJoinColumns instead of JoinColumns. 2, you specified a single "coniuge" field to be used as a foriegn key to referenced Person's Name and Surname fields. You need to specify a field for each.
Try:
#OneToOne
#JoinColumns({#JoinColumn(name="CONIUGE_NAME", referencedColumnName="NAME"),
#JoinColumn(name="CONIUGE_SURNAME", referencedColumnName="SURNAME")})
private Person coniuge;
This will allow you to keep using your current composite primary key. Alan's solution below to generate a unique id field should be used instead where it can though.
My JPQL JOIN query doesn't return any results.
I'm trying to join TargetBean and TipBean on the TargetBean primary key:
public class TargetBean implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Entity
public class TipBean implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#OneToOne
#PrimaryKeyJoinColumn
private TargetBean target;
My query looks like this:
List<Object[]> tipList =
(List<Object[]>)em.createQuery("SELECT tb.result, tg.actualResult "
+ "FROM TipBean tb JOIN tb.target tg")
.getResultList();
Do you notice something wrong with this query or what goes wrong?
Try removing the #PrimaryKeyJoinColumn annotation, I don't think it is appropriate in this context (it is used with inheritence).
I've these two Openjpa entities:
#Entity
#Table(name = "os_wfentry")
public class JPAWorkflowEntry implements WorkflowEntry, Serializable {
private static final long serialVersionUID = -755511983025049452L;
#Id
private long id;
#Column(name = "name")
private String workflowName;
#Column(name = "state")
private Integer workflowState;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "workflowEntry")
private final List<JPACurrentStep> currentSteps;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "workflowEntry")
private final List<JPAHistoryStep> historySteps;
... and this:
#Entity
#Table(name = "os_currentstep")
public class JPACurrentStep implements Serializable, Step {
private static final long serialVersionUID = -3662582760248954945L;
#Id
private Long id;
#Column(name = "action_Id")
protected Integer actionId;
#Column(name = "step_Id")
protected Integer stepId;
protected String caller;
#Column(name = "finish_Date")
#Temporal(TemporalType.TIMESTAMP)
protected Date finishDate;
#Column(name = "start_Date")
#Temporal(TemporalType.TIMESTAMP)
protected Date startDate;
#Column(name = "due_Date")
#Temporal(TemporalType.TIMESTAMP)
protected Date dueDate;
#Column
protected String owner;
protected String status;
#ManyToOne
protected JPAWorkflowEntry workflowEntry;
and when I run my application I've this SQL error:
ERROR: there is no unique constraint matching given keys for referenced table "os_wfentry" {stmnt 989537113 ALTER TABLE os_currentstep ADD FOREIGN KEY (workflowentry_id) REFERENCES os_wfentry (id) DEFERRABLE} [code=0, state=42830]
On my opinion it's all right, in fact tabels are "linked" by id that is unique, I don't figure out why it gives me this error.
It is trying to setup the foreign key relationship os_currentstep.workflowentry_id->os_wfentry.id but for this to be valid os_wfentry.id must be a valid candidate key which from SQL Server's point of view means it must either be the primary key or a non-nullable column covered by a unique constraint - the error is telling you that this is not the case so the foreign key can not be added.
I'm not familiar with Openjpa so I can't tell you how to fix that in its syntax. You need to mark id in os_wfentry as the primary key for that table (assuming it is) or add a unique index covering it.