How can I delete a single object from a list of objects in One to Many Hibernate Mapping using Criteria API?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I am trying to store details of a user along with his favorite team details also. He can change his favorite team any time.
An user can have several properties, among which he can have multiple Favorite Teams.



Thus, I have made a UserEntity class with a set of FavoriteTeam class as follow (which is obviously one to many mapping)



@OneToMany(cascade=CascadeType.ALL)
@JoinTable(name="LookupTable",
joinColumns=@JoinColumn(name="userID", referencedColumnName="id"),
inverseJoinColumns=@JoinColumn(name="favTeamId", referencedColumnName="teamId",unique=true))
private Set<FavouriteTeamEntity> favouriteTeamEntities;




When someone adds a new favorite team, it works fine. But problem arises when someone removes a team from its list.
Currently i am follow this approach where I am deleting the entire user object along with its child and again reinsert all details except the removed favorite team from the set.



    Session session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<UserEntity> criteriaQuery = criteriaBuilder.createQuery(UserEntity.class);
Root<UserEntity> sRoot = criteriaQuery.from(UserEntity.class);
criteriaQuery.select(sRoot);
criteriaQuery.where(criteriaBuilder.equal(sRoot.get("id"),userID));
UserEntity i = session.createQuery(criteriaQuery).uniqueResult();

UserBean userBean = new UserBean();
userBean.setEmail(i.getEmail());
userBean.setId(i.getId());
userBean.setName(i.getName());

Set<FavouriteTeam> fSet= new HashSet<>();
i.getFavouriteTeamEntities().forEach((x) -> {
FavouriteTeam fTeam = new FavouriteTeam();
fTeam.setAltCityName(x.getAltCityName());
fTeam.setCity(x.getCity());
fTeam.setTeamId(x.getId());
fTeam.setTricode(x.getTricode());
fTeam.setFullName(x.getFullName());
fSet.add(fTeam);
});
userBean.setFavouriteTeam(fSet);
session.delete(i);
tx.commit();

Transaction tx1 = session.beginTransaction();
UserEntity userEntity = new UserEntity();
userEntity.setEmail(userBean.getEmail());
userEntity.setId(userBean.getId());
userEntity.setName(userBean.getName());
session.persist(userEntity);
tx1.commit();

userBean.getFavouriteTeam().forEach((fff) -> {
fff.setUserId(signIn.getId());
if(String.valueOf(fff.getTeamId()).equals(teamId)) {
continue;
}else {
this.insertTeamAsFavoriteTeam(fff);
}

});
session.close();




My insertTeamAsFavoriteTeam is as follows :



    public String insertTeamAsFavoriteTeam(FavouriteTeam favouriteTeam) {
Session session = this.sessionFactory.openSession();
UserEntity userEntity = (UserEntity) session.get(UserEntity.class, USER_ID);
Transaction tx = session.beginTransaction();
if (userEntity != null) {
Set<FavouriteTeamEntity> lEntities = sEntity.getFavouriteTeamEntities();
FavouriteTeamEntity favouriteTeamEntity = new FavouriteTeamEntity();
favouriteTeamEntity.setId(favouriteTeam.getTeamId());
favouriteTeamEntity.setAltCityName(favouriteTeam.getAltCityName());
favouriteTeamEntity.setCity(favouriteTeam.getCity());
favouriteTeamEntity.setFullName(favouriteTeam.getFullName());
favouriteTeamEntity.setTricode(favouriteTeam.getTricode());
lEntities.add(favouriteTeamEntity);
userEntity.setFavouriteTeamEntities(lEntities);
}
session.save(userEntity);
tx.commit();
session.close();
}




I Know my approach is wrong but as a work around I have use this approach. If anyone has some good approach please share.
And also I am facing issue when I delete a user, corresponding its favorite team in favorite Team table gets deleted, which I don't want. I want to delete a particular team from the set or the lookup table.



Thanks in advance










share|improve this question























  • To remove a favorite team from the list... just do that: remove the favorite team from the list. For example: user.getFavoriteTeams().removeIf(team -> team.id.equals(idToRemove));. To avoid deleting teams when you delete a use, remove the cascade=CascadeType.ALL from your annotation. That what cascading does: you do something on the user, and it does the same thing on the linked favorite teams.

    – JB Nizet
    Nov 22 '18 at 20:19











  • okay i got it with the CascadeType.ALL part but I don't think removing the team from list will actually remove the team from the lookup table

    – Debjyoti Pandit
    Nov 22 '18 at 20:22











  • i want favTeam to be delete from lookup table - which means mapping between a user and this team should get removed rest all remain same

    – Debjyoti Pandit
    Nov 22 '18 at 20:23











  • Yes, I understand that. I already understood it before writing my previous comment.

    – JB Nizet
    Nov 22 '18 at 20:24













  • so please help me with a nice solution. above written code is not upto the standard

    – Debjyoti Pandit
    Nov 22 '18 at 20:26


















0















I am trying to store details of a user along with his favorite team details also. He can change his favorite team any time.
An user can have several properties, among which he can have multiple Favorite Teams.



Thus, I have made a UserEntity class with a set of FavoriteTeam class as follow (which is obviously one to many mapping)



@OneToMany(cascade=CascadeType.ALL)
@JoinTable(name="LookupTable",
joinColumns=@JoinColumn(name="userID", referencedColumnName="id"),
inverseJoinColumns=@JoinColumn(name="favTeamId", referencedColumnName="teamId",unique=true))
private Set<FavouriteTeamEntity> favouriteTeamEntities;




When someone adds a new favorite team, it works fine. But problem arises when someone removes a team from its list.
Currently i am follow this approach where I am deleting the entire user object along with its child and again reinsert all details except the removed favorite team from the set.



    Session session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<UserEntity> criteriaQuery = criteriaBuilder.createQuery(UserEntity.class);
Root<UserEntity> sRoot = criteriaQuery.from(UserEntity.class);
criteriaQuery.select(sRoot);
criteriaQuery.where(criteriaBuilder.equal(sRoot.get("id"),userID));
UserEntity i = session.createQuery(criteriaQuery).uniqueResult();

UserBean userBean = new UserBean();
userBean.setEmail(i.getEmail());
userBean.setId(i.getId());
userBean.setName(i.getName());

Set<FavouriteTeam> fSet= new HashSet<>();
i.getFavouriteTeamEntities().forEach((x) -> {
FavouriteTeam fTeam = new FavouriteTeam();
fTeam.setAltCityName(x.getAltCityName());
fTeam.setCity(x.getCity());
fTeam.setTeamId(x.getId());
fTeam.setTricode(x.getTricode());
fTeam.setFullName(x.getFullName());
fSet.add(fTeam);
});
userBean.setFavouriteTeam(fSet);
session.delete(i);
tx.commit();

Transaction tx1 = session.beginTransaction();
UserEntity userEntity = new UserEntity();
userEntity.setEmail(userBean.getEmail());
userEntity.setId(userBean.getId());
userEntity.setName(userBean.getName());
session.persist(userEntity);
tx1.commit();

userBean.getFavouriteTeam().forEach((fff) -> {
fff.setUserId(signIn.getId());
if(String.valueOf(fff.getTeamId()).equals(teamId)) {
continue;
}else {
this.insertTeamAsFavoriteTeam(fff);
}

});
session.close();




My insertTeamAsFavoriteTeam is as follows :



    public String insertTeamAsFavoriteTeam(FavouriteTeam favouriteTeam) {
Session session = this.sessionFactory.openSession();
UserEntity userEntity = (UserEntity) session.get(UserEntity.class, USER_ID);
Transaction tx = session.beginTransaction();
if (userEntity != null) {
Set<FavouriteTeamEntity> lEntities = sEntity.getFavouriteTeamEntities();
FavouriteTeamEntity favouriteTeamEntity = new FavouriteTeamEntity();
favouriteTeamEntity.setId(favouriteTeam.getTeamId());
favouriteTeamEntity.setAltCityName(favouriteTeam.getAltCityName());
favouriteTeamEntity.setCity(favouriteTeam.getCity());
favouriteTeamEntity.setFullName(favouriteTeam.getFullName());
favouriteTeamEntity.setTricode(favouriteTeam.getTricode());
lEntities.add(favouriteTeamEntity);
userEntity.setFavouriteTeamEntities(lEntities);
}
session.save(userEntity);
tx.commit();
session.close();
}




I Know my approach is wrong but as a work around I have use this approach. If anyone has some good approach please share.
And also I am facing issue when I delete a user, corresponding its favorite team in favorite Team table gets deleted, which I don't want. I want to delete a particular team from the set or the lookup table.



Thanks in advance










share|improve this question























  • To remove a favorite team from the list... just do that: remove the favorite team from the list. For example: user.getFavoriteTeams().removeIf(team -> team.id.equals(idToRemove));. To avoid deleting teams when you delete a use, remove the cascade=CascadeType.ALL from your annotation. That what cascading does: you do something on the user, and it does the same thing on the linked favorite teams.

    – JB Nizet
    Nov 22 '18 at 20:19











  • okay i got it with the CascadeType.ALL part but I don't think removing the team from list will actually remove the team from the lookup table

    – Debjyoti Pandit
    Nov 22 '18 at 20:22











  • i want favTeam to be delete from lookup table - which means mapping between a user and this team should get removed rest all remain same

    – Debjyoti Pandit
    Nov 22 '18 at 20:23











  • Yes, I understand that. I already understood it before writing my previous comment.

    – JB Nizet
    Nov 22 '18 at 20:24













  • so please help me with a nice solution. above written code is not upto the standard

    – Debjyoti Pandit
    Nov 22 '18 at 20:26














0












0








0








I am trying to store details of a user along with his favorite team details also. He can change his favorite team any time.
An user can have several properties, among which he can have multiple Favorite Teams.



Thus, I have made a UserEntity class with a set of FavoriteTeam class as follow (which is obviously one to many mapping)



@OneToMany(cascade=CascadeType.ALL)
@JoinTable(name="LookupTable",
joinColumns=@JoinColumn(name="userID", referencedColumnName="id"),
inverseJoinColumns=@JoinColumn(name="favTeamId", referencedColumnName="teamId",unique=true))
private Set<FavouriteTeamEntity> favouriteTeamEntities;




When someone adds a new favorite team, it works fine. But problem arises when someone removes a team from its list.
Currently i am follow this approach where I am deleting the entire user object along with its child and again reinsert all details except the removed favorite team from the set.



    Session session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<UserEntity> criteriaQuery = criteriaBuilder.createQuery(UserEntity.class);
Root<UserEntity> sRoot = criteriaQuery.from(UserEntity.class);
criteriaQuery.select(sRoot);
criteriaQuery.where(criteriaBuilder.equal(sRoot.get("id"),userID));
UserEntity i = session.createQuery(criteriaQuery).uniqueResult();

UserBean userBean = new UserBean();
userBean.setEmail(i.getEmail());
userBean.setId(i.getId());
userBean.setName(i.getName());

Set<FavouriteTeam> fSet= new HashSet<>();
i.getFavouriteTeamEntities().forEach((x) -> {
FavouriteTeam fTeam = new FavouriteTeam();
fTeam.setAltCityName(x.getAltCityName());
fTeam.setCity(x.getCity());
fTeam.setTeamId(x.getId());
fTeam.setTricode(x.getTricode());
fTeam.setFullName(x.getFullName());
fSet.add(fTeam);
});
userBean.setFavouriteTeam(fSet);
session.delete(i);
tx.commit();

Transaction tx1 = session.beginTransaction();
UserEntity userEntity = new UserEntity();
userEntity.setEmail(userBean.getEmail());
userEntity.setId(userBean.getId());
userEntity.setName(userBean.getName());
session.persist(userEntity);
tx1.commit();

userBean.getFavouriteTeam().forEach((fff) -> {
fff.setUserId(signIn.getId());
if(String.valueOf(fff.getTeamId()).equals(teamId)) {
continue;
}else {
this.insertTeamAsFavoriteTeam(fff);
}

});
session.close();




My insertTeamAsFavoriteTeam is as follows :



    public String insertTeamAsFavoriteTeam(FavouriteTeam favouriteTeam) {
Session session = this.sessionFactory.openSession();
UserEntity userEntity = (UserEntity) session.get(UserEntity.class, USER_ID);
Transaction tx = session.beginTransaction();
if (userEntity != null) {
Set<FavouriteTeamEntity> lEntities = sEntity.getFavouriteTeamEntities();
FavouriteTeamEntity favouriteTeamEntity = new FavouriteTeamEntity();
favouriteTeamEntity.setId(favouriteTeam.getTeamId());
favouriteTeamEntity.setAltCityName(favouriteTeam.getAltCityName());
favouriteTeamEntity.setCity(favouriteTeam.getCity());
favouriteTeamEntity.setFullName(favouriteTeam.getFullName());
favouriteTeamEntity.setTricode(favouriteTeam.getTricode());
lEntities.add(favouriteTeamEntity);
userEntity.setFavouriteTeamEntities(lEntities);
}
session.save(userEntity);
tx.commit();
session.close();
}




I Know my approach is wrong but as a work around I have use this approach. If anyone has some good approach please share.
And also I am facing issue when I delete a user, corresponding its favorite team in favorite Team table gets deleted, which I don't want. I want to delete a particular team from the set or the lookup table.



Thanks in advance










share|improve this question














I am trying to store details of a user along with his favorite team details also. He can change his favorite team any time.
An user can have several properties, among which he can have multiple Favorite Teams.



Thus, I have made a UserEntity class with a set of FavoriteTeam class as follow (which is obviously one to many mapping)



@OneToMany(cascade=CascadeType.ALL)
@JoinTable(name="LookupTable",
joinColumns=@JoinColumn(name="userID", referencedColumnName="id"),
inverseJoinColumns=@JoinColumn(name="favTeamId", referencedColumnName="teamId",unique=true))
private Set<FavouriteTeamEntity> favouriteTeamEntities;




When someone adds a new favorite team, it works fine. But problem arises when someone removes a team from its list.
Currently i am follow this approach where I am deleting the entire user object along with its child and again reinsert all details except the removed favorite team from the set.



    Session session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<UserEntity> criteriaQuery = criteriaBuilder.createQuery(UserEntity.class);
Root<UserEntity> sRoot = criteriaQuery.from(UserEntity.class);
criteriaQuery.select(sRoot);
criteriaQuery.where(criteriaBuilder.equal(sRoot.get("id"),userID));
UserEntity i = session.createQuery(criteriaQuery).uniqueResult();

UserBean userBean = new UserBean();
userBean.setEmail(i.getEmail());
userBean.setId(i.getId());
userBean.setName(i.getName());

Set<FavouriteTeam> fSet= new HashSet<>();
i.getFavouriteTeamEntities().forEach((x) -> {
FavouriteTeam fTeam = new FavouriteTeam();
fTeam.setAltCityName(x.getAltCityName());
fTeam.setCity(x.getCity());
fTeam.setTeamId(x.getId());
fTeam.setTricode(x.getTricode());
fTeam.setFullName(x.getFullName());
fSet.add(fTeam);
});
userBean.setFavouriteTeam(fSet);
session.delete(i);
tx.commit();

Transaction tx1 = session.beginTransaction();
UserEntity userEntity = new UserEntity();
userEntity.setEmail(userBean.getEmail());
userEntity.setId(userBean.getId());
userEntity.setName(userBean.getName());
session.persist(userEntity);
tx1.commit();

userBean.getFavouriteTeam().forEach((fff) -> {
fff.setUserId(signIn.getId());
if(String.valueOf(fff.getTeamId()).equals(teamId)) {
continue;
}else {
this.insertTeamAsFavoriteTeam(fff);
}

});
session.close();




My insertTeamAsFavoriteTeam is as follows :



    public String insertTeamAsFavoriteTeam(FavouriteTeam favouriteTeam) {
Session session = this.sessionFactory.openSession();
UserEntity userEntity = (UserEntity) session.get(UserEntity.class, USER_ID);
Transaction tx = session.beginTransaction();
if (userEntity != null) {
Set<FavouriteTeamEntity> lEntities = sEntity.getFavouriteTeamEntities();
FavouriteTeamEntity favouriteTeamEntity = new FavouriteTeamEntity();
favouriteTeamEntity.setId(favouriteTeam.getTeamId());
favouriteTeamEntity.setAltCityName(favouriteTeam.getAltCityName());
favouriteTeamEntity.setCity(favouriteTeam.getCity());
favouriteTeamEntity.setFullName(favouriteTeam.getFullName());
favouriteTeamEntity.setTricode(favouriteTeam.getTricode());
lEntities.add(favouriteTeamEntity);
userEntity.setFavouriteTeamEntities(lEntities);
}
session.save(userEntity);
tx.commit();
session.close();
}




I Know my approach is wrong but as a work around I have use this approach. If anyone has some good approach please share.
And also I am facing issue when I delete a user, corresponding its favorite team in favorite Team table gets deleted, which I don't want. I want to delete a particular team from the set or the lookup table.



Thanks in advance







java database hibernate criteria hibernate-onetomany






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 22 '18 at 20:10









Debjyoti PanditDebjyoti Pandit

137




137













  • To remove a favorite team from the list... just do that: remove the favorite team from the list. For example: user.getFavoriteTeams().removeIf(team -> team.id.equals(idToRemove));. To avoid deleting teams when you delete a use, remove the cascade=CascadeType.ALL from your annotation. That what cascading does: you do something on the user, and it does the same thing on the linked favorite teams.

    – JB Nizet
    Nov 22 '18 at 20:19











  • okay i got it with the CascadeType.ALL part but I don't think removing the team from list will actually remove the team from the lookup table

    – Debjyoti Pandit
    Nov 22 '18 at 20:22











  • i want favTeam to be delete from lookup table - which means mapping between a user and this team should get removed rest all remain same

    – Debjyoti Pandit
    Nov 22 '18 at 20:23











  • Yes, I understand that. I already understood it before writing my previous comment.

    – JB Nizet
    Nov 22 '18 at 20:24













  • so please help me with a nice solution. above written code is not upto the standard

    – Debjyoti Pandit
    Nov 22 '18 at 20:26



















  • To remove a favorite team from the list... just do that: remove the favorite team from the list. For example: user.getFavoriteTeams().removeIf(team -> team.id.equals(idToRemove));. To avoid deleting teams when you delete a use, remove the cascade=CascadeType.ALL from your annotation. That what cascading does: you do something on the user, and it does the same thing on the linked favorite teams.

    – JB Nizet
    Nov 22 '18 at 20:19











  • okay i got it with the CascadeType.ALL part but I don't think removing the team from list will actually remove the team from the lookup table

    – Debjyoti Pandit
    Nov 22 '18 at 20:22











  • i want favTeam to be delete from lookup table - which means mapping between a user and this team should get removed rest all remain same

    – Debjyoti Pandit
    Nov 22 '18 at 20:23











  • Yes, I understand that. I already understood it before writing my previous comment.

    – JB Nizet
    Nov 22 '18 at 20:24













  • so please help me with a nice solution. above written code is not upto the standard

    – Debjyoti Pandit
    Nov 22 '18 at 20:26

















To remove a favorite team from the list... just do that: remove the favorite team from the list. For example: user.getFavoriteTeams().removeIf(team -> team.id.equals(idToRemove));. To avoid deleting teams when you delete a use, remove the cascade=CascadeType.ALL from your annotation. That what cascading does: you do something on the user, and it does the same thing on the linked favorite teams.

– JB Nizet
Nov 22 '18 at 20:19





To remove a favorite team from the list... just do that: remove the favorite team from the list. For example: user.getFavoriteTeams().removeIf(team -> team.id.equals(idToRemove));. To avoid deleting teams when you delete a use, remove the cascade=CascadeType.ALL from your annotation. That what cascading does: you do something on the user, and it does the same thing on the linked favorite teams.

– JB Nizet
Nov 22 '18 at 20:19













okay i got it with the CascadeType.ALL part but I don't think removing the team from list will actually remove the team from the lookup table

– Debjyoti Pandit
Nov 22 '18 at 20:22





okay i got it with the CascadeType.ALL part but I don't think removing the team from list will actually remove the team from the lookup table

– Debjyoti Pandit
Nov 22 '18 at 20:22













i want favTeam to be delete from lookup table - which means mapping between a user and this team should get removed rest all remain same

– Debjyoti Pandit
Nov 22 '18 at 20:23





i want favTeam to be delete from lookup table - which means mapping between a user and this team should get removed rest all remain same

– Debjyoti Pandit
Nov 22 '18 at 20:23













Yes, I understand that. I already understood it before writing my previous comment.

– JB Nizet
Nov 22 '18 at 20:24







Yes, I understand that. I already understood it before writing my previous comment.

– JB Nizet
Nov 22 '18 at 20:24















so please help me with a nice solution. above written code is not upto the standard

– Debjyoti Pandit
Nov 22 '18 at 20:26





so please help me with a nice solution. above written code is not upto the standard

– Debjyoti Pandit
Nov 22 '18 at 20:26












0






active

oldest

votes












Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53437502%2fhow-can-i-delete-a-single-object-from-a-list-of-objects-in-one-to-many-hibernate%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53437502%2fhow-can-i-delete-a-single-object-from-a-list-of-objects-in-one-to-many-hibernate%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Biblatex bibliography style without URLs when DOI exists (in Overleaf with Zotero bibliography)

ComboBox Display Member on multiple fields

Is it possible to collect Nectar points via Trainline?