I have two tables as specified below. I want to write a query to get all the contacts of a particular group.(According to group id). Please help me.
Thanks in advance.
1.this contacts table , which has many has many to many relationship with contact groups table.
#Entity
#Table(name="contacts")
public class Contacts implements Serializable {
private Long id;
private String userId;
private String emailId;
private Set<ContactGroups> contactGroups;
private String firstName;
private String lastName;
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name="user_id")
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
#Column(name="email_id")
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
#ManyToMany(targetEntity = ContactGroups.class, cascade = {CascadeType.ALL},fetch=FetchType.EAGER)
#JoinTable(name="contact_group",
joinColumns=#JoinColumn(name="c_id", referencedColumnName="id"),
inverseJoinColumns=#JoinColumn(name="g_id", referencedColumnName="id")
)
public Set<ContactGroups> getContactGroups() {
return contactGroups;
}
public void setContactGroups(Set<ContactGroups> contactGroups) {
this.contactGroups = contactGroups;
}
#Column(name="first_name")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name="last_name")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
#Entity
#Table(name="contact_groups")
public class ContactGroups implements Serializable{
private Long id;
private String groupName;
private String userName;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name="user_name")
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
#Column(name="group_name")
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
}
select c from Contacts c
inner join c.contactGroups group
where group.id = :groupId
But everything would be simpler if
you named your entities ContactGroup and Contact (without the final s)
you mapped the association as a bidirectional one. It would allow getting the ContactGroup by ID, and just call getContacts() to get its contacts.
select c from Contacts c, ContactGroups g
where c.contactGroups.id = g.id
and g.id = 'whatever id you want'
Related
I have a problem with my Spring application- am practicing ManyToMany Relationship.
I made two Entity- student, and groups for them- everything is good but when am trying to display them in postman i have spaghetti result like :
{"id":4,"lastName":"guzik","groups":[{"id":1,"groupName":"grupka","students":
....(shorter version, its about 1000 lines)
[{"id":1,"lastName":"smith","groups":[{}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}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]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}]}{"timestamp":"2022-04-25T08:25:31.387+00:00","status":200,"error":"OK","path":"/api/student/4"}
What am doing wrong ?
enter code here
#RestController
#RequestMapping("/api")
public class MainController{
#Autowired
GroupRepo groupRepo;
#Autowired
StudentRepo studentRepo;
#GetMapping("/student/{id}")
ResponseEntity<?> getStudent(#PathVariable long id){
Optional<Students> student=studentRepo.findById(id);
return ResponseEntity.ok().body(student);
}
#GetMapping("/group/{id}")
ResponseEntity<?> getGroup(#PathVariable long id){
Optional<Groupssss> group=groupRepo.findById(id);
return ResponseEntity.ok().body(group);
}
#GetMapping("/student/{id}/groups")
ResponseEntity<?> studentGroups(#PathVariable long id){
Students student=studentRepo.findById(id).orElseThrow(()-> new UsernameNotFoundException("student not found"));
return ResponseEntity.ok().body(student.getGroups());
}
#PostMapping("/add")
#Transactional
ResponseEntity<?> addStudentToGroup(#RequestHeader long id) throws Exception{
Students student=studentRepo.findById(id)
.orElseThrow(()-> new UsernameNotFoundException("student not found"));
Groupssss group=groupRepo.findByGroupName("grupka").orElseThrow(Exception::new);
student.addGroup(group);
studentRepo.save(student);
return ResponseEntity.ok().build();
}
#Entity
public class Groupssss {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String groupName;
#ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
},
mappedBy = "groups")
private Set<Students> students=new HashSet<>();
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public void setStudents(Set<Students> students) {
this.students = students;
}
public Set<Students> getStudents() {
return students;
}
public String getGroupName() {
return groupName;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
#Entity
#Table(name="students")
public class Students {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
long id;
String firstName;
String lastName;
#ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
#JoinTable(name="student_group",
joinColumns = #JoinColumn(name="student_id"),
inverseJoinColumns = #JoinColumn(name="group_id"))
Set<Groupssss> groups=new HashSet<>();
public Students(){}
public Students(String firstName, String lastName){
this.firstName=firstName;
this.lastName=lastName;
}
public void addGroup(Groupssss group){
this.groups.add(group);
group.getStudents().add(this);
}
public Set<Groupssss> getGroups() {
return groups;
}
public String getLastName() {
return lastName;
}
public String getName() {
return firstName;
}
public void setGroups(Set<Groupssss> groups) {
this.groups = groups;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setName(String firstName) {
this.firstName = firstName;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
If you use ManyToMany relationship, It calls the Parent and the Child entity recursively when you try to get List of it. There must be ignorance in child entity like:
In Parent entity you could call #JsonManagedReference
In Child entity you could call #JsonBackReference
Documentation is here:
Bidirectional Relationships
public class User {
public int id;
public String name;
#JsonManagedReference
public List<Item> userItems;
}
public class Item {
public int id;
public String itemName;
#JsonBackReference
public User owner;
}
Or you can use #JsonIgnore on top of the Parent declaration in Child entity. Some of the case it gets worst when you use JsonIgnore.
Documentation is here:
Jackson Ignore Properties
public class MyDto {
private String stringValue;
#JsonIgnore
private int intValue;
private boolean booleanValue;
public MyDto() {
super();
}
}
Or use #JsonIgnoreProperties when you need to ignore many fields
#JsonIgnoreProperties(value = { "intValue" })
public class MyDto {
private String stringValue;
private int intValue;
private boolean booleanValue;
public MyDto() {
super();
}
}
!Enjoy
I have entity Account, Role, AccountRole.
#Entity
public class Account {
#Id
private String loingId;
private String username;
private String password;
private String email;
private boolean enable;
#OneToMany(mappedBy = "account", orphanRemoval = true)
private List<AccountRole> accountRoles = new ArrayList<>();
public String getLoingId() {
return loingId;
}
public void setLoingId(String loingId) {
this.loingId = loingId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public List<AccountRole> getAccountRoles() {
return accountRoles;
}
public void setAccountRoles(List<AccountRole> accountRoles) {
this.accountRoles = accountRoles;
}
public void addAccountRoles(AccountRole accountRoles) {
if (this.accountRoles == null){
this.accountRoles = new ArrayList<>();
}
this.accountRoles.add(accountRoles);
accountRoles.setAccount(this);
}
public void removeAccountRoles(){
this.accountRoles = null;
}
}
#Entity
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String description;
private boolean enable;
#OneToMany(mappedBy = "role")
private List<AccountRole> accountRoles = new ArrayList<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public List<AccountRole> getAccountRoles() {
return accountRoles;
}
public void setAccountRoles(List<AccountRole> accountRoles) {
this.accountRoles = accountRoles;
}
}
#Entity
public class AccountRole implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#ManyToOne
#JoinColumn(name = "account_id")
private Account account;
#ManyToOne
#JoinColumn(name = "role_id")
private Role role;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
}
To create account with role is OK.
There is a problem in update.
I want to delete the existing Role and only add the changed Role when the Role of the Account is changed. However, existing data is not deleted from the AccoutRole table.
How can I solve the problem?
springBootVersion = '1.5.3.RELEASE'
java 1.8
gradle dependencies
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.boot:spring-boot-starter-data-jpa')
testCompile('org.springframework.boot:spring-boot-starter-test')
runtime ('org.mariadb.jdbc:mariadb-java-client')
}
A couple of ideas:
Thought 1: Try using cascade
Yes, JPA 2.0 should handle this with orphanRemoval = true, but let's just see if that works. I think that it is not because you aren't creating an orphan here. The mapping is still "valid" from a relational perspective.
#OneToMany(mappedBy = "account", cascade = CascadeType.ALL) // or CascadeType.REMOVE
private List<AccountRole> accountRoles = new ArrayList<>();
Thought 2: Try setting the account roles to an empty hashmap instead first:
account.setAccountRoles(new HashMap<AccountRole>());
account.getAccountRoles().add(accountRole);;
I have the following Entity classes UserEntity and TicketEntity. A User has many tickets and many tickets can belong to a user. My question is, is there a way to automatically load all the tickets belonging to a pertaining user by using Hibernate or do I have to manually load all the entity relationships from the DB? I think the .load() does this but I'm not quite sure. In my case could I do something like
userEntity.load()
Any help is appreciated, thanks
UserEntity.java
package com.issuetracking.domain;
/**
*/
import java.util.List;
import javax.persistence.*;
#Entity
#Table(name="user")
public class UserEntity {
#Id
#Column(name="user_id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name="firstname")
private String firstname;
#Column(name="lastname")
private String lastname;
#Column(name="username")
private String username;
#Column(name="email")
private String email;
#Column(name="password")
private String password;
#Transient
private String confirmpassword;
#Column(name="verified")
private boolean verified;
#Column(name="role_id")
private int role_id;
#OneToMany(fetch = FetchType.LAZY)
private List<TicketEntity> tickets;
//Getters/Setters
public List<TicketEntity> getTickets() {
return tickets;
}
public void setTickets(List<TicketEntity> tickets) {
this.tickets = tickets;
}
public int getRole_id() {
return role_id;
}
public void setRole_id(int role_id) {
this.role_id = role_id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getConfirmpassword() {
return confirmpassword;
}
public void setConfirmpassword(String confirmpassword) {
this.confirmpassword = confirmpassword;
}
public boolean isVerified() {
return verified;
}
public void setVerified(boolean verified) {
this.verified = verified;
}
}
TicketEntity.java
package com.issuetracking.domain;
import java.util.Date;
import javax.persistence.*;
#Entity
#Table(name="ticket")
public class TicketEntity {
#Id
#Column(name="ticket_id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name="title")
private String title;
#Column(name="description")
private String description;
#Column(name="date_created")
#Temporal( TemporalType.TIMESTAMP )
private Date date_created;
#Column(name="status_id")
private int status_id;
//private TicketStatus status;
#Column(name="urgency_id")
private int urgency_id;
#ManyToOne
#JoinColumn(name="user_id", insertable=false, updatable=false)
private UserEntity belongs_to;
#ManyToOne
#JoinColumn(name="user_id", insertable=false, updatable=false)
private UserEntity assigned_to;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getDate_created() {
return date_created;
}
public void setDate_created(Date date_created) {
this.date_created = date_created;
}
public int getStatus_id() {
return status_id;
}
public void setStatus_id(int status_id) {
this.status_id = status_id;
}
public int getUrgency_id() {
return urgency_id;
}
public void setUrgency_id(int urgency_id) {
this.urgency_id = urgency_id;
}
public UserEntity getBelongs_to() {
return belongs_to;
}
public void setBelongs_to(UserEntity belongs_to) {
this.belongs_to = belongs_to;
}
public UserEntity getAssigned_to() {
return assigned_to;
}
public void setAssigned_to(UserEntity assigned_to) {
this.assigned_to = assigned_to;
}
}
A User has many tickets and many tickets can belong to a user.
In this case relationship should be ManyToMany
My question is, is there a way to automatically load all the tickets belonging to a pertaining user
Use EAGER FetchType instead of LAZY , Like
#OneToMany(fetch = FetchType.EAGER)
private List<TicketEntity> tickets;
iam getting foregin key value null in db.iam using jpa.
i have two tables,one is user another one is review.i want to store user id value in review table.review table iam getting null for user_id column.plz help me how to store the user id value ...
thanks
this is my api class for user
public interface User
{
public int getId();
public void setId(int id);
public String getFirstName();
public void setFirstName(String firstName);
public String getLastName();
public void setLastName(String lastName);
}
and this is my review api class
public interface Review
{
public int getId();
public void setId(int id);
public String getReview();
public void setReview(String review);
public User getUserId();
public void setUserId(User userId);
}
and this is my model class for review
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private int id;
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
#Basic(optional = true)
#Column(name = "reviews")
private String review;
public String getReview()
{
return review;
}
public void setReview(String review)
{
this.review = review;
}
#OneToOne(targetEntity = com.movi.db.model.UserImpl.class, cascade = CascadeType.ALL)
#JoinColumn(name = "user_id")
private User userId;
public User getUserId()
{
return userId;
}
public void setUserId(User userId)
{
this.userId = userId;
}
this is my my dao method
public boolean createReview(Review review)
{
em.getTransaction().begin();
em.persist(review);
em.getTransaction().commit();
return true;
}
this is my action class
private ReviewImpl review;
private String userReview;
private String reply;
private String send;
private User user;
//setters and getters
if(reply!=null)
{
review.setUserId(user);
if(service.createReview(review))
System.out.println("created review successful");
else
System.out.println("creation failed");
return "userreview";
}
I have created one model class
#Entity
#Table(name = "tblcoustomer")
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "tblcoustomer_cid_gen")
#SequenceGenerator(name = "tblcoustomer_cid_gen", sequenceName = "tblcoustomer_cid_seq")
#Column(name = "cid")
private int id;
#ManyToOne(targetEntity = FinancialMonth.class, fetch = FetchType.EAGER)
#JoinColumn(name = "monthId", nullable = false)
private FinancialMonth monthId;
#ManyToOne(targetEntity = Company.class, fetch = FetchType.EAGER)
#JoinColumn(name = "companyId", nullable = false)
private Company companyId;
#ManyToOne(targetEntity = CustomerType.class, fetch = FetchType.EAGER)
#JoinColumn(name = "customerType", nullable = false)
private CustomerType customerType;
private String firstName;
private String lastName;
private String gender;
private int age;
private String designation;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public FinancialMonth getMonthId() {
return monthId;
}
public void setMonthId(FinancialMonth monthId) {
this.monthId = monthId;
}
public Company getCompanyId() {
return companyId;
}
public void setCompanyId(Company companyId) {
this.companyId = companyId;
}
public CustomerType getCustomerType() {
return customerType;
}
public void setCustomerType(CustomerType customerType) {
this.customerType = customerType;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
}
now when I am trying to load this object using #ModelAttribute I am getting error
#RequestMapping(value = "/saveCustomer")
public ModelAndView addUser(HttpServletRequest request,
#ModelAttribute("custome") Customer customer) {
Map<String, Object> model = new HashMap<String, Object>();
return new ModelAndView("addCustomer", model);
}
I konw I have to override #initBinder but how do I bind can any one please help me I am getting this error
I can not answer your question without knowing the exception, but there is an typo in your code that may cause an problem:
you have:
public ModelAndView addUser(HttpServletRequest request,
#ModelAttribute("custome") Customer customer)
But I think it should be model attribute "customer" with an "r" at the end.
public ModelAndView addUser(HttpServletRequest request,
#ModelAttribute("customer") Customer customer)