Why does not it work SequenceGenerator in Spring Boot? - spring-boot

I make a blog on Spring Boot + Spring Date
There is a post, user, comment, and entities that contain links between them.
For each of these 6 entities, I added the annotation
#SequenceGenerator (name = "...", sequenceName = "...", allocationSize = 1)
Also created in the Database additionally hibernate_sequencе
However, the following problems arise.
When I add a post (with id = 1) and delete it, and then create a new post, it is already with id 2, not id 1
When I try to add a comment to it,then throws an error that usually occurs if there is no SequenceGenerator.
Error:
ERROR: insert or update on table "posts_comments" violates foreign key constraint "posts_comments_post_id_fkey"
DETAIL: Key (post_id) = (5) is not present in table
Why?
add comment in CommentService
public void create(Comments new_comment,Long parent_id, String login, int post_id)
{
Users user=userService.findByLogin(login);
Posts post=postsRepository.findById((long) post_id).get();
if((parent_id!=null)&&(commentsRepository.existsById(parent_id)))
{
Comments parentComment=commentsRepository.findById(parent_id).get();
parentComment.getChildComment().add(new_comment);
commentsRepository.save(parentComment);
}
new_comment.setOwnerpost(post);
new_comment.setOwner(user);
commentsRepository.save(new_comment);
}
Comment
#Entity
#Table(name = "comments")
#Setter
#Getter
#NoArgsConstructor
#AllArgsConstructor
public class Comments implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#SequenceGenerator(name = "clientsIdSeq1", sequenceName = "comments_id_seq", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE,generator="comments_id_seq")
private Long id;
#Column(name = "title")
private String title;
#Column(name = "content")
private String content;
#Column(name = "date_create")
private LocalDate dateCreate;
#Column(name = "count_like")
private Long countLike;
#Column(name = "count_dislike")
private Long counterDislike;
#OneToMany(fetch= FetchType.EAGER,cascade=CascadeType.ALL ,orphanRemoval=true )
#JoinTable(name = "parentchild_comment",
joinColumns = #JoinColumn(name= "parent_id"),
inverseJoinColumns = #JoinColumn(name= "child_id"))
#Fetch(value = FetchMode.SUBSELECT)
private List<Comments> childComment;
#ManyToOne(fetch= FetchType.EAGER,cascade=CascadeType.ALL )
#JoinTable(name = "users_comments",
joinColumns = #JoinColumn(name= "comment_id"),
inverseJoinColumns = #JoinColumn(name= "user_id"))
#JsonIgnoreProperties({"listPost", "listComment"})
private Users owner;
#ManyToOne(fetch= FetchType.EAGER,cascade = {CascadeType.REFRESH })
#JoinTable(name = "posts_comments",
joinColumns = #JoinColumn(name= "post_id"),
inverseJoinColumns = #JoinColumn(name= "comment_id"))
#JsonIgnoreProperties({"listComments"})
private Posts ownerpost;
}
Post
#Entity
#Table(name = "posts")
#Setter
#Getter
#NoArgsConstructor
#AllArgsConstructor
public class Posts implements Serializable {
#Id
#Column(name = "id")
#SequenceGenerator(name = "clientsIdSeq4", sequenceName = "posts_id_seq", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE,generator ="posts_id_seq" )
private Long id ;
#Column(name = "title")
private String title;
#Column(name = "content")
private String content;
#Column(name = "date_create")
private LocalDate dateCreate;
#Column(name = "count_like")
private Long countLike;
#Column(name = "count_dislike")
private Long counterDislike;
#OneToMany(mappedBy = "ownerpost",fetch= FetchType.EAGER,cascade=CascadeType.ALL,orphanRemoval=true )
#Fetch(value = FetchMode.SUBSELECT)
#JsonIgnoreProperties("childComment")
private List<Comments> listComments;
#ManyToOne(fetch= FetchType.EAGER,cascade=CascadeType.REFRESH)
#JoinTable(name = "users_posts",
joinColumns = #JoinColumn(name= "post_id"),
inverseJoinColumns = #JoinColumn(name= "user_id"))
#JsonIgnoreProperties({"listPost", "listComment"})
private Users owner;
}
User
#Entity
#Table(name = "users")
#Setter
#Getter
#NoArgsConstructor
#AllArgsConstructor
public class Users implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#SequenceGenerator(name = "clientsIdSeq5", sequenceName = "users_id_seq", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "users_id_seq")
private Long id;
#Column(name = "login")
private String login;
#Column(name = "password")
private String password;
#ManyToOne(optional = false, cascade = CascadeType.REFRESH)
#JoinColumn(name = "position_id")
private Position position;
#OneToMany(mappedBy = "owner",fetch= FetchType.EAGER,cascade=CascadeType.ALL,orphanRemoval=true )
#JsonIgnoreProperties("listComments")
#Fetch(value = FetchMode.SUBSELECT)
private List<Posts> listPost;
#OneToMany(mappedBy = "owner",fetch= FetchType.EAGER,cascade=CascadeType.ALL,orphanRemoval=true )
#JsonIgnoreProperties("childComment")
#Fetch(value = FetchMode.SUBSELECT)
private List<Comments> listComment;
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Users)) return false;
Users users = (Users) o;
if (!Objects.equals(id, users.id)) return false;
if (!Objects.equals(login, users.login)) return false;
if (!Objects.equals(password, users.password)) return false;
if (!Objects.equals(position, users.position)) return false;
if (!Objects.equals(listPost, users.listPost)) return false;
return Objects.equals(listComment, users.listComment);
}
#Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (login != null ? login.hashCode() : 0);
result = 31 * result + (password != null ? password.hashCode() : 0);
result = 31 * result + (position != null ? position.hashCode() : 0);
result = 31 * result + (listPost != null ? listPost.hashCode() : 0);
result = 31 * result + (listComment != null ? listComment.hashCode() : 0);
return result;
}
}
my code https://dropmefiles.com/pdv48
Insomnia with with requests https://dropmefiles.com/jPOgB

You mixed the name and the sequence name. The generator attribute must be then name not the sequenceName
#SequenceGenerator(name = "clientsIdSeq1", sequenceName = "comments_id_seq", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator="clientsIdSeq1")

Related

Sending file and JSON in a many-to-many relationship

I have a model called EPI that has a many to many relationship with Model Images, I am not able to do the #PostMapping for this object.
see my code
EPI Entity:
#Entity
#Data
#NoArgsConstructor
#AllArgsConstructor
#Builder
#Table(name = "EPI")
public class EPI implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "Id_EPI")
private UUID id;
#Column(name = "Nome", nullable = false, length = 100)
private String nome;
#Column(name = "Marca", nullable = false, length = 100)
private String marca;
#Column(name = "CA", nullable = false, length = 100)
private String ca;
#Column(name = "Descricao", nullable = false)
private String descricao;
#Column(name = "Foto")
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(name = "epi_images",
joinColumns = {
#JoinColumn(name = "epi_id")
},
inverseJoinColumns = {
#JoinColumn(name = "image_id")
})
private Set<ImageModel> foto;
#Column(name = "Quantidade", nullable = false)
private Integer quantidade;
}
Image Entity:
#Entity
#Data
#NoArgsConstructor
#AllArgsConstructor
#Builder
#Table(name = "image_model")
public class ImageModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private UUID id;
private String name;
#Column(name = "type")
private String type;
#Column(name = "image_data", unique = false, nullable = false, length = 100000)
private byte[] imageData;
}
Controller EPI:
#PostMapping("/addNewEPI")
public ResponseEntity<Object> salvarFEPI(#RequestPart("image")MultipartFile file,
#RequestPart("epiModel") EPI epi) throws IOException {
try {
ImageModel foto = productImageService.uploadImage(file);
epi.setFoto((Set<ImageModel>) foto);
return ResponseEntity.status(HttpStatus.CREATED).body(epiService.save(epi));
} catch (Exception e){
System.out.println(e.getMessage());
return null;
}
Service Image:
public ImageModel uploadImage(MultipartFile file) throws IOException {
ImageModel image = new ImageModel();
image.setName(file.getOriginalFilename());
image.setType(file.getContentType());
image.setImageData(ImageUtility.compressImage(file.getBytes()));
return image;
}
As I am passing the parameters in Postman:
enter image description here
Return from Spring Boot:
enter image description here
If anyone can help me I would be very grateful!
I tried passing the parameters in different ways. I just want it to populate my tables passing the parameters of the EPI entity and the Image file.
enter image description here

Why hibernate is throwing constraintViolationException?

Order Entity
#Entity
#Table(name = "Order",
indexes = {
#Index(name = "ORDER_X1", columnList = "REFERENCE_ID,SOURCE_ID"),
#Index(name = "ORDER_X2", columnList = "TYPE,STATUS")
}
)
#DiscriminatorColumn(name="PROCESSOR_TYPE", discriminatorType=DiscriminatorType.STRING, length = 80)
#SequenceGenerator(name="orderSeq", sequenceName="ORDER_SEQ")
#Inheritance(strategy= InheritanceType.JOINED)
public abstract class OrderEntity implements Serializable {
#Id
#GeneratedValue(strategy= GenerationType.SEQUENCE, generator="orderSeq")
private Long id;
#ManyToMany(cascade={CascadeType.MERGE})
#JoinTable(
name = "FILE_ORDER_MAP",
joinColumns = {#JoinColumn(name = "ORDER_ID")},
inverseJoinColumns = {#JoinColumn(name = "FILE_ID")}
)
private Set<TransferFile> transferFiles = new HashSet<>();
#Column(name = "TYPE")
#Enumerated(EnumType.STRING)
private OrderType type;
#Column(name = "AMOUNT", precision = 12, scale = 2)
private LcMoney amount;
#Column(name = "STATUS")
#Enumerated(EnumType.STRING)
private OrderStatus reconStatus;
#Type(type = LcUtc.JPA_JODA_TIME_TYPE)
#Column(name = "STATUS_D", nullable = false)
#LcDateTimeUtc()
private DateTime reconStatusDate;
#Column(name = "REFERENCE_ID")
private Long referenceId;
#Column(name = "SOURCE_ID")
private Long sourceId;
#Column(name = "ACCOUNT_ID")
private Long accountId;
#Column(name = "PROCESSOR_TYPE", insertable = false, updatable = false)
#Enumerated(EnumType.STRING)
private OrderProcessorType processorType;
#Type(type = LcUtc.JPA_JODA_TIME_TYPE)
#Column(name = "TX_EXECUTION_D")
#LcDateTimeUtc()
private DateTime executedDate;
#Type(type = LcUtc.JPA_JODA_TIME_TYPE)
#Column(name = "CREATE_D")
#LcDateTimeUtc()
private DateTime createDate;
#Column(name = "IS_ON_DEMAND")
#Type(type = "yes_no")
private boolean isOnDemand;
#ManyToOne(fetch = FetchType.LAZY, optional = true, cascade = {CascadeType.PERSIST})
#JoinColumn(name="PAYER_ID", nullable=true)
private Payer payer;
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "ORDER_ID", referencedColumnName = "ID")
private List<OrderTransaction> orderTransactions;
#OneToMany(cascade = {CascadeType.ALL})
#JoinColumn(name = "ORDER_ID", referencedColumnName = "ID",
foreignKey = #ForeignKey(name = "FK_ORDER")
)
private List<MatchResult> matchResults;
#Version
#Column(name = "VERSION")
private Integer version;
#Embedded
#AttributeOverrides({
#AttributeOverride(name = "externalSourceId", column = #Column(name = "TRANS_EXT_SRC_ID")),
#AttributeOverride(name = "externalId", column = #Column(name = "TRANS_EXT_REF_ID"))
})
private LcExternalIdEntity transExtId;
#PreUpdate
#PrePersist
public void beforePersist() {
if (reconStatusDate != null) {
reconStatusDate = reconStatusDate.withZone(DateTimeZone.UTC);
}
if (executedDate != null) {
executedDate = executedDate.withZone(DateTimeZone.UTC);
}
if (createDate != null) {
createDate = createDate.withZone(DateTimeZone.UTC);
}
}
// getters and setters
}
//controller method
public Response processFile(){
// separate trasaction
service.readFileAndCreateOrders(); // read files and create orders in new status
List<Order> newOrders = service.getNewOrders();
for( Order order: newOrders){
service.processOrder(order); // separate transaction
}
}
#Transaction
void processOrder(OrderEntity order){
matchResultJpaRepository.save(orderEntity.id);
log.info("Saving matchId={} for order={}", match.getId(), order.getId());
// create new transaction and add to order
OrderTransaction transaction = createNewTransaction(order);
order.getTransactions().add(transaction);
order.setStatus("PROCESSED");
log.info("Saving Order id={}, Type={}, Status={} ", order.getId(), order.getType(), order.getStatus());
orderRepository.save(order);
}
I am seeing this below error.
ORA-01407: cannot update ("PAYMENTS"."MATCH_RESULT"."ORDER_ID") to NULL
This endpoing is not exposed to user. There is a batch job which invokes this endpoint.
This code has been there for atleast a year and this is the first time i am seeing this.
This happened only once and for only one call. I am seeing both the logs printed. I am puzzled why I am seeing above error complaining about NULL order id. From the logs, we can confirm that the order id is definitely not null.
Any idea why this is happening? What can be done to fix this?

How to fix Error ManyToMany in #RestController?

I'm an entity Story:
#Entity
#Table(name = "story", schema = "")
#Data
public class Story implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "sID", unique = true, nullable = false)
private Long sID;
#Column(name = "vnName", nullable = false)
private String vnName;
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "_scategory",
joinColumns = {#JoinColumn(name = "sID", nullable = false)},
inverseJoinColumns = {#JoinColumn(name = "cID", nullable = false)})
private List<Category> categoryList;
}
And Entity Category:
#Entity
#Table(name = "category", schema = "", uniqueConstraints = {#UniqueConstraint(columnNames = {"cMetatitle"}),
#UniqueConstraint(columnNames = {"cName"})})
#Data
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "cID", unique = true, nullable = false)
private Integer cID;
#Column(name = "cName", unique = true, nullable = false, length = 150)
private String cName;
#ManyToMany(mappedBy = "categoryList")
private List<Story> storyList;
}
But when I grab the Story in RestController, I get the following error message:
WARN http-nio-8080-exec-9
o.s.w.s.m.s.DefaultHandlerExceptionResolver:234 - Failure while trying
to resolve exception
[org.springframework.http.converter.HttpMessageNotWritableException]
java.lang.IllegalStateException: Cannot call sendError() after the
response has been committed
Can anybody show me how to fix it? Thank you!

Spring JpaRepository manyToMany bidirectional should save instead of update

if got a language table and a system table with a many-to-many relationship:
Language:
#JsonAutoDetect
#Entity
#Table(name = "language")
public class Language implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "language_id", nullable = false)
private int languageId;
#Column(name = "language_name", nullable = false)
private String languageName;
#Column(name = "language_isocode", nullable = false)
private String languageIsoCode;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "system_language", joinColumns = {#JoinColumn(name = "language_id", updatable = false)},
inverseJoinColumns = {
#JoinColumn(name = "system_id", updatable = false)}, uniqueConstraints = {
#UniqueConstraint(columnNames = {
"language_id",
"system_id"
})})
private List<System> systems;
public Language() {
}
// GETTER & SETTERS
// ....
}
System
#JsonAutoDetect
#Entity
#Table(name = "system")
public class System implements Serializable {
#Id
#Column(name = "system_id", nullable = false)
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer systemId;
#Column(name = "system_name", nullable = false, unique = true)
private String systemName;
#OneToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "university_id", nullable = false)
private University university;
#JoinColumn(name = "calender_id", nullable = false)
#OneToOne(fetch = FetchType.EAGER)
private Calendar calender;
#OneToMany(mappedBy = "system")
#LazyCollection(LazyCollectionOption.FALSE)
private List<SystemUserRole> systemUserRoleList;
#OneToMany(mappedBy = "system")
#LazyCollection(LazyCollectionOption.FALSE)
private List<Role> roleList;
#OneToOne(mappedBy = "system")
#LazyCollection(LazyCollectionOption.FALSE)
private CsmUserEntity csmUserEntity;
#ManyToMany(mappedBy = "systems")
#LazyCollection(LazyCollectionOption.FALSE)
private List<Language> languages;
public System() {
}
// GETTER & SETTERS
// ....
}
When im writing a first dataset (systemId=1, language_id=20) into the table, everything works fine. But when i try to write a second dataset with the same language_id but with other system_id (systemId=2, language_id=20), then the existing dataset gets updated. But i want to have a new dataset instead. What can i do?
Thanks in advance!

how to delete or save a many to many relationship in hibernate & spring

i have a many to many relationship between 2 tables.
below are the two tables with mappings.
StaffSearchCriteria is used to search staffs having skills selected.
this search criteria is persisted in DB so that we can again lookup it later.
the issue i am facing is that i am not able to properly save this data.
i am not understanding the "cascade" part of the mapping.
due to which, if i do " Cascade.ALL ", the data is saved properly, but when i delete the search criteria, then it also deletes the Skill entries associated with it, which is wrong.
i just want that if i delete Skill, StaffSearchCriteria entry should not get deleted and similarly for the Skill;
Only the selected data should be deleted and its entry in the mapping table.
the other table should not be affected by that action.
StaffSearchCriteria
#Entity
#Table(name = "staff_search_criteria")
#NamedQueries({
#NamedQuery(name = "StaffSearchCriteria.findAll", query = "SELECT s FROM StaffSearchCriteria s")})
public class StaffSearchCriteria implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Long id;
#Basic(optional = false)
#NotNull
#Column(name = "version")
private long version;
#Lob
#Size(max = 2147483647)
#Column(name = "description")
private String description;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 200)
#Column(name = "name")
private String name;
#ManyToMany(mappedBy = "staffSearchCriteriaCollection", cascade = {CascadeType.MERGE, CascadeType.PERSIST}, fetch = FetchType.LAZY)
private Collection<Skill> skillCollection;
==================================================
Skill
#Entity
#Table(name = "skill")
#NamedQueries({
#NamedQuery(name = "Skill.findAll", query = "SELECT s FROM Skill s")})
public class Skill implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Long id;
#Basic(optional = false)
#NotNull
#Column(name = "version")
private long version;
#Lob
#Size(max = 2147483647)
#Column(name = "description")
private String description;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
#Column(name = "name")
private String name;
#JoinTable(name = "mission_skill", joinColumns = {
#JoinColumn(name = "skill_id", referencedColumnName = "id")}, inverseJoinColumns = {
#JoinColumn(name = "mission_skills_id", referencedColumnName = "id")})
#ManyToMany(fetch = FetchType.LAZY)
private Collection<Mission> missionCollection;
#JoinTable(name = "staff_search_criteria_skill", joinColumns = {
#JoinColumn(name = "skill_id", referencedColumnName = "id")}, inverseJoinColumns = {
#JoinColumn(name = "staff_search_criteria_skills_id", referencedColumnName = "id")})
#ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST}, fetch = FetchType.LAZY)
private Collection<StaffSearchCriteria> staffSearchCriteriaCollection;
Save method
public StaffSearchCriteria saveStaffSearchCriteria(StaffSearchCriteria staffSearchCriteria) {
logger.info(" [StaffSearchCriteriaDAOImpl] saveStaffSearchCriteria method called. - staffSearchCriteria = " + staffSearchCriteria);
Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(staffSearchCriteria);
return staffSearchCriteria;
}
delete method
public void deleteStaffSearchCriteria(Long id) {
logger.info(" [StaffSearchCriteriaDAOImpl] deleteStaffSearchCriteria method called. - id = " + id);
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("FROM StaffSearchCriteria ssc where ssc.id = " + id);
if(null != query.uniqueResult()){
StaffSearchCriteria staffSearchCriteria = (StaffSearchCriteria)query.uniqueResult();
session.delete(staffSearchCriteria);
}
}
Please help me here.What am i doing wrong?
Finally i solved it. what i did was as follows.
1. In controller, i found out which skills were removed from previous saved data.
2. passed that list of Skill as well as the StaffSearchCriteria to the service save method.
3. in Service, i iterated over each skill to be removed and removed the staffSearchCriteria object from it and saved it.
4. then passed the staff search criteria to dao and used saveOrUpdate method.
Below are the code snippets.
1.Controller
List<Skill> skillList2 = new ArrayList<Skill>();
if(null != request.getParameterValues("skillCollection")){
for(String skillId : request.getParameterValues("skillCollection")){
if((!skillId.equals(null)) && skillId.length() > 0){
Skill skill = skillService.findSkillById(Long.parseLong(skillId));
// skill will be lazily initialized :(
// initialize it
skill.setStaffSearchCriteriaCollection(staffSearchCriteriaService.getAllStaffSearchCriteriaBySkillId(skill.getId()));
// set staff search criteria in each skill. because it is the owner
if(null != skill.getStaffSearchCriteriaCollection()){
skill.getStaffSearchCriteriaCollection().add(staffSearchCriteria);
}else{
List<StaffSearchCriteria> staffSearchCriteriaList = new ArrayList<StaffSearchCriteria>();
staffSearchCriteriaList.add(staffSearchCriteria);
skill.setStaffSearchCriteriaCollection(staffSearchCriteriaList);
}
skillList2.add(skill);
}
}
}
staffSearchCriteria.setSkillCollection(skillList2);
// Remove OLD skills also. plz. :)
List<Skill> skillList3 = null;
if(null != staffSearchCriteria && staffSearchCriteria.getId() != null && staffSearchCriteria.getId() > 0){
// this skillList3 will contain only those which are removed.
skillList3 = skillService.getAllSkillByStaffSearchCriteriaId(staffSearchCriteria.getId());
skillList3.removeAll(skillList2);
}
// now set staffSearchCriteriacollection and then pass it.
List<Skill> removedskillList = new ArrayList<Skill>();
if(null != skillList3){
for(Skill skill : skillList3){
skill.setStaffSearchCriteriaCollection(staffSearchCriteriaService.getAllStaffSearchCriteriaBySkillId(skill.getId()));
removedskillList.add(skill);
}
}
// now pass to service and save these skills after removing this staff search criteria from them.
staffSearchCriteria = staffSearchCriteriaService.saveStaffSearchCriteria(staffSearchCriteria, removedskillList);
2.Service
if(null != removedskillList && removedskillList.size() > 0){
for(Skill skill : removedskillList){
skill.getStaffSearchCriteriaCollection().remove(staffSearchCriteria);
skillDAO.saveSkill(skill);
}
}
return staffSearchCriteriaDAO.saveStaffSearchCriteria(staffSearchCriteria);
3.DAO
Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(staffSearchCriteria);
4.Entity Class - Skill
#JoinTable(name = "staff_search_criteria_skill", joinColumns = {
#JoinColumn(name = "skill_id", referencedColumnName = "id")}, inverseJoinColumns = {
#JoinColumn(name = "staff_search_criteria_skills_id", referencedColumnName = "id")})
#ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.LAZY)
private Collection<StaffSearchCriteria> staffSearchCriteriaCollection = new ArrayList<StaffSearchCriteria>();
5.Entity Class - StaffSearchCriteria
#ManyToMany(mappedBy = "staffSearchCriteriaCollection", fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
private Collection<Skill> skillCollection = new ArrayList<Skill>();
Hope this helps.

Resources