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")) })
Related
I'm stuck at deal with this problem. I have 'Review Entity', and 'Heart Entitiy'. And I tried to show them homepage and detailpage separately!
Long countHeartByBookReviewId(Long bookReview_id);
i used jpa query method for showing how many heart it gets in details page..
and now i want to show review descending related to heart count in main page!
how can i make the code..?
#Entity
public class BookReview extends Timestamped {
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Id
private Long id;
...
#Column
private String review;
#JoinColumn(name = "member_id", nullable = false)
#ManyToOne(fetch = FetchType.EAGER)
private Member member;
#OneToMany(mappedBy = "bookReview" , cascade = CascadeType.REMOVE)
private List<Comment> comment;
#JsonIgnore
#OneToMany(mappedBy = "bookReview", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private List<Heart> heart;
and the other entitiy is here.
public class Heart {
#GeneratedValue(strategy = GenerationType.AUTO)
#Id
private Long id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "bookReview_id")
private BookReview bookReview;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "member_id")
private Member member;
and this is function for get menthod...
public ResponseDto<?> getHome() {
List<BookReview> book_review = book_reviewRepository.findAllByOrderByHeartDesc();
List<HomeResponseDto> book_reviewResponseDtoList = new ArrayList<>();
for (BookReview home : book_review) {
book_reviewResponseDtoList.add(HomeResponseDto.builder()
.id(home.getId())
.username(home.getMember().getUsername())
.thumbnail(home.getThumbnail())
.title(home.getTitle())
.author(home.getAuthor())
.publisher(home.getPublisher())
.review(home.getReview())
.heart(heartRepository.countHeartByBookReviewId(home.getId()))
.createdAt(home.getCreatedAt())
.modifiedAt(home.getModifiedAt())
.build()
);
}
return ResponseDto.success(book_reviewResponseDtoList);
}
please help me ......
I have a User Entity.
#Entity
#Table(name = "t_login_user")
public class User extends Auditable<Long> implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "user_id")
private Long id;
#Column(name = "user_uid")
private String userUid;
#Column(name = "user_name")
private String userName;
#OneToOne(fetch = FetchType.EAGER, optional = false)
#JoinColumn(name="primary_role_id")
private Role primaryRole;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "t_login_user_role_map", joinColumns = #JoinColumn(name = "user_id"), inverseJoinColumns = #JoinColumn(name = "role_id"))
private List<Role> roles;
}
My Role Entity is
#Entity
#Table(name = "t_login_role")
public class Role extends Auditable<Long> implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="role_id")
private Long roleId;
#Column(name="role_code")
private String roleCode;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "t_login_role_priv_map", joinColumns = #JoinColumn(name = "role_id"), inverseJoinColumns = #JoinColumn(name = "priv_id"))
private List<Privilege> privileges;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "t_login_role_menu_map", joinColumns = #JoinColumn(name = "role_id"), inverseJoinColumns = #JoinColumn(name = "menu_id"))
private List<Menu> menus;
}
My Menu Entity is
#Entity
#Table(name = "t_login_menu")
public class Menu extends Auditable<Long> implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="id")
private Long id;
#Column(name="menu_text")
private String menuText;
#Column(name="menu_icon")
private String menuIcon;
#Column(name="menu_url")
private String menuURL;
}
As you can see my Role has multiple Privileges and Multiple Menus. The problem I face is that when I have a code like
LoggedinUser liu = (LoggedinUser)authentication.getPrincipal();
List<Menu> menus = liu.getPrimaryRole().getMenus();
If I have two privileges say READ_DATA and WRITE_DATA
And three Menus 1. HOME 2.USER 3.PROFILE
my menus variable has a value of [HOME,HOME,USER, USER, PROFILE, PROFILE] (i.e. 2 privileges * 3 Roles)
I suspect that this is due to my Role entity having more than one #ManyToMany annotations.
I tried to search online and Stackoverflow but no results.
Anybody face this issue? Am i doing something fundamentally wrong?
Okay. I understand where the cross join happens. Since both the ManyToMany are being EAGER loaded, this is where the Cross Join Happens.
If I change to LAZY Load then the issue disappears. Slight performance hit on LAZY load, but thats fine since I do it only once and store the result in the session.
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") })})
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"))
})
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")