Glassfish says incomplete JoinColumns - glassfish

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.

Related

How to create Entity class with composite kays (Kotlin, Spring boot)

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

One to one with referencedColumnName mapping on wrong field

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).

how to get entities with many to may dependency

This is project entity which I need to get by current user Id:
#Entity
#Table(name = "project")
public class Project implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToMany
#JoinTable(name = "project_user",
joinColumns = #JoinColumn(name="projects_id", referencedColumnName="id"),
inverseJoinColumns = #JoinColumn(name="users_id", referencedColumnName="id"))
private Set<User> users = new HashSet<>();
}
this is user entity whichs Id I'll use to get products:
#Entity
#Table(name = "jhi_user")
public class User extends AbstractAuditingEntity implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToMany(mappedBy = "users")
private Set<Project> projects = new HashSet<>();
}
Repositories classes extend JpaRepository class. How I can get all projects for current user Id?
Native SQL statement that I can use is:
SELECT * FROM project WHERE id IN (SELECT projects_id FROM project_user WHERE users_id = ?);
It should be as simple as this...
User user = userRepository.findById(100L);
Set<Projects> projects = user.getProjects();
Because of your mapping, JPA takes care of the rest.

JPA Entity with hierachy relationship

I have the following Entity
#Entity
public class Project implements Serializable {
#Id
private Integer project_id;
private String project_name;
other attributes
#OneToOne
#JoinColumn(name = "lead_emp_no", referencedColumnName = "emp_no")
private Employee projectLead;
// but the following two relationships need to be a connect by:
#OneToOne
#JoinColumn(name = "lead_boss_emp_no", referencedColumnName = "emp_no")
private Employee projectLeadBoss;
#OneToOne
#JoinColumn(name = "lead_bosses_boss_emp_no", referencedColumnName = "emp_no")
private Employee projectLeadBossesBoss;
With this setup, we have to manually maintain the employee numbers for the Lead's boss and the Lead's Boss's boss. This relationship is [somewhat] already available knowing the projectLead employee:
The Employee Entity is as follows:
#Entity
public class Employee implements Serializable {
#Id
private Integer emp_no;
private Integer bosses_emp_no;
Is it possible to get my Project entity to connect to the boss and bosses Employee based on projectLead? In single query I'd like to get a table of all projects and their lead's hierarchy. I'm open to entity redesign.
You can replace the bosses_emp_no in Employee should with a more helpful boss:
#Entity
public class Employee implements Serializable {
#Id
private Integer emp_no;
#OneToOne
#JoinColumn(name = "boss_emp_no", referencedColumnName = "emp_no")
private Employee boss;
Then you simply add a couple of delegating methods to Project
public Employee getProjectLeadBoss() {
return this.projectLead.getBoss();
}
public Employee getProjectLeadBossesBoss() {
return this.getProjectLeadBoss().getBoss();
}

JPA mapping #OneToOne own class

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.