jpa many to many with additional column and composite key - java

I have 2 tables :folder(simple primary key) and document(composite primary key)
I want a join table named folder_documents which will contains the id of both tables with additional columns
There is my entities:
Folder
#Entity
#Table(name = "folder")
public class Folder {
#Id
#SequenceGenerator(name = "folder_seq_gen", sequenceName = "FOLDER_SEQ", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "folder_seq_gen")
private long id;
#Column
private Date date;
#OneToMany(mappedBy = "folder_documents_compositeKey.folder",
cascade = CascadeType.ALL)
private Set<Folder_Documents> folder_documents;
Document
#Entity
#Table(name="document")
public class Document {
#EmbeddedId
private DocumentID documentCompositeKey;
#Column
private Date date;
DocumentID(composite key)
#Embeddable
public class DocumentID implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String id;
private String matricule;
Folder_Document ( join table)
#Entity
#Table(name = "folder_documents")
#AssociationOverrides({
#AssociationOverride(name = "folder_documents_compositeKey.folder",
joinColumns = #JoinColumn(name = "folder_id")),
#AssociationOverride(name = "folder_documents_compositeKey.document",
joinColumns = #JoinColumn(name = "doc_id" , referencedColumnName = "id")), // error mapping there
#AssociationOverride(name = "folder_documents_compositeKey.document",
joinColumns = #JoinColumn(name = "matricule" , referencedColumnName = "matricule"))})// error mapping there
public class Folder_Documents {
#EmbeddedId
private Folder_Documents_ID folder_documents_compositeKey = new Folder_Documents_ID();
#Column
private Date date;
#Column
private String status;
Folder_documents_id(composite key)
#Embeddable
public class Folder_Documents_ID implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#ManyToOne(cascade = CascadeType.ALL)
private Folder folder;
#ManyToOne(cascade = CascadeType.ALL)
private Document document;
The problem is i can't map the Document compositeKey in Folder_Documents' s #AssociationOverrides attributes because hibernate don't find the composite key id and matricule properties in Document . Folder references is fine .
There is the stacktrace:
Caused by: org.hibernate.AnnotationException: referencedColumnNames(matricule) of com.renault.entity.Folder_Documents_ID.folder_documents_compositeKey.document referencing com.renault.entity.Document not mapped to a single property

Resolved , the syntax of the AssociationOverride annotation was wrong
Correct syntax :
AssociationOverrides({
#AssociationOverride(name = "folder_documents_compositeKey.folder", joinColumns = #JoinColumn(name = "folder_id")),
#AssociationOverride(name = "folder_documents_compositeKey.document", joinColumns = {
#JoinColumn(name = "doc_id" , referencedColumnName = "id") ,
#JoinColumn(name = "matricule" , referencedColumnName = "matricule") })})

Related

How to set value for all OneToMany entities?

I have an ClientUser entity with #OneToMany field customField:
#Entity
#Data
public class ClientUser {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(
name = "client_user_custom_field",
joinColumns = #JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "field_id", referencedColumnName = "id"))
private Collection<ClientFieldValue> customFields;
}
And a ClientFieldValue entity:
#Entity
#Data
public class ClientFieldValue {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
private String value;
}
How can I create ClientFieldValue's for all existing ClientUser?
I know that I can do smth like:
final Iterable<ClientUser> clientUsers = userRepository.findAll();
clientUsers.forEach(clientUser ->
clientUser.setCustomFields(Collections.singleton(new ClientFieldValue())));
userRepository.saveAll(clientUsers);
But I don't want to query all and save them after set.
Is there another way to do this?

Java Spring + Hibernate "Cannot add or update a child row"

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (ravermeister.artist_recordlabel, CONSTRAINT FK_9dgdyft45droyopxsqijwb1dx FOREIGN KEY (artist_id) REFERENCES artist (id))
Artist class
#Entity
#Repository
#Data
#NoArgsConstructor(force = true)
public class Artist {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "artist_firstname")
private String artist_firstname;
#Column(name = "artist_secondname")
private String artist_secondname;
#Column(name = "artist_nickname")
private String artist_nickname;
#ManyToMany (fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
#JoinTable(name = "artist_recordlabel", joinColumns = #JoinColumn(name = "artist_id"),
inverseJoinColumns = #JoinColumn(name = "label_id"))
private Set<RecordLabel> recordLabels;
#ManyToMany (fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
#JoinTable (name = "artist_musicrelease", joinColumns = #JoinColumn (name = "artist_id"),
inverseJoinColumns = #JoinColumn (name = "musicrelease_id"))
private Set <MusicRelease> musicReleaseSet;
and RecordLabel class
#Entity
#Repository
#Data
#NoArgsConstructor(force = true)
public class RecordLabel {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "label_name")
private String label_name;
#Column(name = "label_country")
private String label_country;
#ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
#JoinTable(name = "artist_recordlabel", joinColumns = #JoinColumn(name = "label_id"),
inverseJoinColumns = #JoinColumn(name = "artist_id"))
private Set<Artist> artistsList;
Please follow this guide for a many-to-many relation
http://www.baeldung.com/hibernate-many-to-many
I think this error means that you are trying to insert/update into RecordLabel table a artist_id value that does not exist in Artist table.

Nested n:m + attributes JPA

I have a strange need in a project. Joining two n:m+attributes table (I will present the behavior with dummy attributes).
FirstTable (idPlace, idAddress,idSchool, wage) joined 1:m;
SecondTable (idPlace, idAddress,idSchool, qty, idEnterprise)
EDIT (example schema):
Of course that I have the tables Place, Address, School, Enterprise with theirs respective Ids, gets, sets and attributes implemented in the entity classes.
CODE:
Place
#Entity
#Table(name = "Place")
public class Place implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "idLine")
private Long idLine;
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "pk.place")
private List<FirstTable> firstTables;
}
Address
#Entity
#Table(name = "Address")
public class Address implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "idAddress")
private Long idAddress;
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "pk.address")
private List<FirstTable> firstTables;
}
School
#Entity
#Table(name = "School")
public class School implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "idSchool")
private Long idSchool;
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "pk.school")
private List<FirstTable> firstTables;
}
FirstTable
#Entity
#Table(name = "FirstTable")
#AssociationOverrides({ #AssociationOverride(name = "pk.school", joinColumns = #JoinColumn(name = "idSchool")),
#AssociationOverride(name = "pk.address", joinColumns = #JoinColumn(name = "idAddress")),
#AssociationOverride(name = "pk.place", joinColumns = #JoinColumn(name = "idPlace")) })
public class FirstTable implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#EmbeddedId
protected FirstTablePK pk = new FirstTablePK();
}
FirstTablePK
#Embeddable
public class FirstTablePK implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#ManyToOne
private Address address;
#ManyToOne
private Place place;
#ManyToOne
private School school;
}
The above mentioned tables and joins are working perfectly. Now I want to join the FirstTable with the Second Table.
Enterprise
#Entity
#Table(name = "Enterprise")
public class Enterprise implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "idEnterprise")
private Long idEnterprise;
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "pk.enterprise")
private List secondTables;
}
Now for the SecondTable I've followed the same logic to connect to the Enterprise. For connecting with the FirstTable I've tried this:
#Entity
#Table(name = "SecondTable")
#AssociationOverrides({
#AssociationOverride(name = "pk.firstTable", joinTable = #JoinTable(
name = "FirstTable", inverseJoinColumns = {
#JoinColumn(name = "idSchool", referencedColumnName = "idSchool"),
#JoinColumn(name = "idAddress", referencedColumnName = "idAddress"),
#JoinColumn(name = "idPlace", referencedColumnName = "idPlace") })),
#AssociationOverride(name = "pk.enterprise", joinColumns = #JoinColumn(name = "idEnterprise")) })
public class SecondTable implements Serializable{}
Something is not working in my annotation, I'm trying to do an inverseJoin to the FirstTable table. The compilation shows this error:
"org.hibernate.AnnotationException: A component cannot hold properties split into 2 different tables"
I've tried to provide a MV example.
Thanks in advance and I really need your help.
Hours later and many tries before I've managed to solve the problem. Actually the solution was much simpler that I was thinking initially.
Here it is:
#AssociationOverride(name = "pk.firstTable", joinColumns = {
#JoinColumn(name = "idSchool"),
#JoinColumn(name = "idAddress"),
#JoinColumn(name = "idPlace") }),
#AssociationOverride(name = "pk.enterprise", joinColumns = #JoinColumn(name = "idEnterprise")) })

Many-to-many relationship with composite keys, extra column in Hibernate

I have 3 data table:
Applications {id_app, version, name}
Customers {org_id, name}
Associations {id_app, version, org_id, state}.
Applications has a composite primary key (id_app, version), the primary key for Customers is org_id and Associations has a composite primary key (id_app, version, org_id).
In my java application I have the following classes:
#Entity
#Table(name = "Applications")
#IdClass(ApplicationId.class)
public class Application implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "ID_APP", nullable = false)
private String idApp;
#Id
#Column(name = "VERSION", nullable = false)
private String version;
#Column(name = "NAME")
private String name;
#OneToMany(mappedBy = "idPk.appPk", fetch = FetchType.LAZY) // cascade = CascadeType.ALL)
private List<Association> custApps;
// getters and setters
}
public class ApplicationId implements Serializable {
private static final long serialVersionUID = 1L;
private String idApp;
private String version;
//hashcode and equals
}
#Entity
#Table(name = "CUSTOMERS")
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "ORG_ID", unique = true, nullable = false)
private Integer orgID;
#Column(name = "NAME")
private String name;
#OneToMany(mappedBy="idPk.customerPk", fetch = FetchType.LAZY)
private List<Association> custApps;
//getters and setters
}
#Entity
#Table(name = "ASSOCIATIONS")
#AssociationOverrides({
#AssociationOverride(name = "idPk.appPk", joinColumns = #JoinColumn(name = "ID_APP")),
#AssociationOverride(name = "idPk.appPk", joinColumns = #JoinColumn(name = "VERSION")),
#AssociationOverride(name = "idPK.customerPk", joinColumns = #JoinColumn(name = "ORG_ID"))
})
public class Association implements Serializable {
private static final long serialVersionUID = 1L;
private AssociationId idPk = new AssociationId();
private String state;
public Association() {
super();
}
#EmbeddedId
public AssociationId getIdPk() {
return idPk;
}
#Transient
public Customer getCustomerPk() {
return idPk.getCustomerPk();
}
#Transient
public Application getAppPk() {
return idPk.getAppPk();
}
#Column(name = "STATE")
public String getState() {
return state;
}
//setters , hashCode and equals
}
#Embeddable
public class AssociationId implements Serializable {
private static final long serialVersionUID = 1L;
private Application appPk;
private Customer customerPk;
// here is the problem ?
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumns({ #JoinColumn(name = "ID_APP", referencedColumnName = "ID_APP"),
#JoinColumn(name = "VERSION", referencedColumnName = "VERSION") })
public Application getAppPk() {
return appPk;
}
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name="ORG_ID")
public Customer getCustomerPk() {
return customerPk;
}
//setter, hashCode and equals
}
What are the correct annotation? The relationship is many to many between Application and Customers and I create the Association table for that and for the extra column "state".
Now I receive this error: A Foreign key refering sla.model.Application from sla.model.Association has the wrong number of column. should be 2 .
Please help.
Done. I change the following:
In Association class:
#AssociationOverrides({
#AssociationOverride(name = "idPk.appPk", joinColumns = { #JoinColumn(name = "ID_APP", referencedColumnName = "ID_APP"),
#JoinColumn(name = "VERSION", referencedColumnName = "VERSION") }),
#AssociationOverride(name = "idPK.customerPk", joinColumns = #JoinColumn(name = "ORG_ID"))
})

Select records without parent with Hibernate using Criteria API

How select records without parent with Hibernate using Criteria API?
Here is my Java code for select with parents
getSessionFactory().getCurrentSession().createCriteria(Category.class).add(
Restrictions.eq("parent", new Category(parentId))).list();
Category Java code
#Entity
#Table(name = "CATEGORY")
public class Category implements NamedModel{
#Id
#Column(name = "CATEGORY_ID")
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#OneToOne(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY)
#JoinTable(name = "CATEGORY_RELATIONS",
joinColumns = {
#JoinColumn(name = "CATEGORY_RELATIONS_CATEGORY_ID", referencedColumnName = "CATEGORY_ID")},
inverseJoinColumns = {
#JoinColumn(name = "CATEGORY_RELATIONS_PARENT_ID", referencedColumnName = "CATEGORY_ID")})
private Category parent;
#OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER, mappedBy = "parent")
private List<Category> children;//...
}
CategoryRelations Java code
#Entity
#Table(name = "CATEGORY_RELATIONS")
#IdClass(CategoryRelations.CategoryRelationsPrimaryKey.class)
public class CategoryRelations implements Serializable {
#Id
#Column(name = "CATEGORY_RELATIONS_CATEGORY_ID")
private long categoryId;
#Id
#Column(name = "CATEGORY_RELATIONS_PARENT_ID")
private long parentId;
#Entity
#IdClass(CategoryRelationsPrimaryKey.class)
public static class CategoryRelationsPrimaryKey implements Serializable {
private long categoryId;
private long parentId;
}
}
You can use Restriction#isNull(propertyName) function for your requirements.
Restrictions.isNull("parent")

Categories