how to get entities with many to may dependency - sql

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.

Related

Deadlock when we we have dependent entities in hibernate and try to update table using multiple threads in Vertica

I have two java classes. Father.java and Children.java
#Entity
#Table(name = "FATHER")
#JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
class Father implements Cloneable
{
#Id
#Column(name = "father_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long fatherId;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinColumn(name = "father_id")
#Fetch(value = FetchMode.SUBSELECT)
private List<Children> children = new ArrayList<Children>();
//getter and setters and public constructors
}
#Entity
#Table(name = "Children")
class Children implements Comparable<Children>
{
#JsonIgnore
#Id
#Column(name = "children_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long child_id;
#JsonIgnore
#Column(name = "father_id")
private long fatherId;
//public constructors and getters and setters
}
public interface RelationDao{
public Father update() throws Exception;
}
#Repository("relationDao")
#EnableTransactionManagement
#Transactional
public RelationDaoImpl{
#Override
#Transactional("txManager")
public Father update(Father father)
{
father = merge(father);
//added retry logic as well also father is updated with a new child which is why merge
}
}
I receive the Deadlock X exception if several threads visit the same table (entity father) to updates with distinct row entries, even though the records are different.
Is there any way to fix why the entire table locks up instead than just one row?
Even though I haven't updated or added anything to the code, the transaction isolation level is SERIALIZABLE.
DB system is Vertica
Explained here, if anyone is coming here to check why Vertica doesn’t support row level locks for updates or delete. https://stackoverflow.com/a/69917383/8799862
So I used synchronized to perform thread-safe updates and deletes.

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

Hibernate LazyLoading initialization of List

I've typical User and Comment-Models. One user has more comments.
On one usecase i want to get only a user from db, without comments.
I thought, as soon i tell "getComments()", so only in this moment, my List will initialized with
something like "select comment from Comment c where c.userId = 1" from Hibernate.
But my List of comments will be initialized everytime when i say findyById or "select user from User".
#Entity
#Getter #Setter
#ToString(exclude = {"comments")
#Builder
#AllArgsConstructor
#NoArgsConstructor
public class User implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
#Builder.Default
#OneToMany(mappedBy="user", fetch = FetchType.LAZY)
private List<Comment> comments = new ArrayList<>();
}
My Comment Model:
#Entity
#Getter #Setter
#Builder
#AllArgsConstructor
#NoArgsConstructor
public class Comment implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
#Builder.Default
#ManyToOne(fetch = FetchType.LAZY)
private User user; }
UserRepository:
public interface UserRepository extends JpaRepository<User, Long> {
#Query("SELECT user FROM User user WHERE user.id =:id")
Optional<User> findUserById(#Param("id") long id); }
When i tell:
userRepository.findUserById(1);
So i see at first only one select-statment for user.
Few seconds later i see next statment for comment, but i did not tell "user.getComments()"
So how can i get User-Model without any Lazy-List's with related Object?

Glassfish says incomplete JoinColumns

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.

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();
}