Need to make a selection of data from the related tables of the many-to-many relationship type.
How can you make data selection from tables in a many-to-many relationship
using jpa?
Gives an ERROR error: Table 'tets.usergroup' does not exist.
I was looking for the answer in Google, but Google did not help. I tried to prescribe the essence differently, it also did not help.
#Entity
#Table(name = "USERS")
public class User {
private long id;
private String username;
private String password;
private String email;
private Set<UserGroup> userGroups = new HashSet<UserGroup>();
public User() {
}
public User(String username, String password, String email) {
this.username = username;
this.password = password;
this.email = email;
}
public void addGroup(UserGroup group) {
this.userGroups.add(group);
}
#Id
#GeneratedValue
#Column(name = "USER_ID")
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
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;
}
#OneToMany(mappedBy = "user")
public Set<UserGroup> getUserGroups() {
return userGroups;
}
public void setUserGroups(Set<UserGroup> groups) {
this.userGroups = groups;
}
public void addUserGroup(UserGroup userGroup) {
this.userGroups.add(userGroup);
}
}
UserGroup class
#Entity
#Table(name = "USERS_GROUPS")
public class UserGroup {
private long id;
private User user;
private Group group;
// additional fields
private boolean activated;
private Date registeredDate;
#Id
#GeneratedValue
#Column(name = "USER_GROUP_ID")
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "USER_ID")
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "GROUP_ID")
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
public boolean isActivated() {
return activated;
}
public void setActivated(boolean activated) {
this.activated = activated;
}
#Column(name = "REGISTERED_DATE")
#Temporal(TemporalType.DATE)
public Date getRegisteredDate() {
return registeredDate;
}
public void setRegisteredDate(Date registeredDate) {
this.registeredDate = registeredDate;
}
}`#Entity
#Table(name = "GROUPS")
public class Group {
private long id;
private String name;
private Set<UserGroup> userGroups = new HashSet<UserGroup>();
public Group() {
}
public Group(String name) {
this.name = name;
}
#Id
#GeneratedValue
#Column(name = "GROUP_ID")
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;
}
#OneToMany(mappedBy = "group")
public Set<UserGroup> getUserGroups() {
return userGroups;
}
public void setUserGroups(Set<UserGroup> groups) {
this.userGroups = groups;
}
public void addUserGroup(UserGroup userGroup) {
this.userGroups.add(userGroup);
}
}`
And some exception
ERROR: Table 'tets.usergroup' doesn't exist
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:82)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:61)
at org.hibernate.loader.Loader.getResultSet(Loader.java:2040)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1837)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1816)
at org.hibernate.loader.Loader.doQuery(Loader.java:900)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:342)
at org.hibernate.loader.Loader.doList(Loader.java:2526)
at org.hibernate.loader.Loader.doList(Loader.java:2512)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2342)
at org.hibernate.loader.Loader.list(Loader.java:2337)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:338)
at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:1833)
at org.hibernate.internal.AbstractSessionImpl.list(AbstractSessionImpl.java:231)
at org.hibernate.internal.SQLQueryImpl.list(SQLQueryImpl.java:157)
at net.codejava.hibernate.Many2ManyTester.select_filter(Many2ManyTester.java:184)
at net.codejava.hibernate.Many2ManyTester.main(Many2ManyTester.java:216)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'tets.usergroup' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4190)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4122)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2570)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2731)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2818)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2157)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2324)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:56)
... 15 more
I saw that you config the entity with table name:
#Table(name = "USERS_GROUPS")
but the error is:
error: Table 'tets.usergroup' does not exist
So maybe you made wrong query. Or you can find all places which use 'usergroup'
Related
I am trying to delete an object in my database having a foreign key row in other table the error is IllegalArgumentException occurred calling getter of com.techpro.webstat.models.Role.username; nested exception is org.hibernate.PropertyAccessException
i have 2 entities :
import javax.persistence.*;
#Entity
#Table(name = "users")
public class User {
public Role ro;
public int user_id;
public String username;
public String password;
public int enabled = 1;
public User() {
}
public User(String username, String password, int enabled) {
this.username = username;
this.password = password;
this.enabled = enabled;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "username", referencedColumnName = "username", insertable = false, updatable = false)
public Role getRo() {
return ro;
}
public void setRo(Role ro) {
this.ro = ro;
}
#Column(name = "username")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Column(name = "password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name = "enabled")
public int getEnabled() {
return enabled;
}
public void setEnabled(int enabled) {
this.enabled = enabled;
}
}
import javax.persistence.*;
import java.io.Serializable;
#Entity
#Table(name = "user_roles")
public class Role implements Serializable {
public int user_role_id;
public String username;
public String role;
public User user;
public void setUser_role_id(int user_role_id) {
this.user_role_id = user_role_id;
}
#OneToOne(mappedBy = "ro", cascade = CascadeType.ALL)
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Role(String username, String role) {
this.username = username;
this.role = role;
}
public Role() {
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public int getUser_role_id() {
return user_role_id;
}
#Column(name = "username")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Column(name = "role")
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
and this is my code to delete user object :
#RequestMapping( value = "/deleteuserid/{user_id}", method = RequestMethod.GET)
public ModelAndView doDelete(#PathVariable("user_id") int user_id){
ModelAndView mv = new ModelAndView("redirect:/utilisateurs");
appRepo.delete(user_id);
return mv;
}
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 this error nested exception is org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): app.Spring.domain.UserDetails.
I now have this user table and in profile i want to edit this UserDetails.
i was trying with GeneratedValue but this doing random id that not associate with user_id also checked generator but this method also dont work.There is so many options so i am lost now.Can someone show some method to mapp this two entities?
User
#Entity
#Table(name = "USERS")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
#Column(name = "user_id")
private Long user_id;
#NotBlank
#Size(min = 5, max = 20)
private String username;
#NotBlank
#Size(min = 8, max = 20)
private String password;
private String email;
private String name;
private String surname;
#OneToOne(cascade = CascadeType.ALL)
#PrimaryKeyJoinColumn
private UserDetails userDetail;
public User() {
}
public User(Long user_id, String username, String email, String name,
String surname, UserDetails userDetail, String password) {
super();
this.user_id = user_id;
this.username = username;
this.email = email;
this.name = name;
this.surname = surname;
this.userDetail = userDetail;
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Long getUser_id() {
return user_id;
}
public final void setUser_id(Long user_id) {
this.user_id = user_id;
}
public void setId(Long user_id) {
this.user_id = user_id;
}
#Column(name = "username")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Column(name = "password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
User_Details
#Entity
#Table(name = "user_address")
public class UserDetails {
public UserDetails() {
super();
// TODO Auto-generated constructor stub
}
#Id
#Column(name = "user_id")
private Long id;
private String adres1;
private String adres2;
private String city;
private String postcode;
#OneToOne
#PrimaryKeyJoinColumn
private User user;
public UserDetails(Long id, String adres1, String adres2, String city,
String postcode, User user) {
super();
this.id = id;
this.adres1 = adres1;
this.adres2 = adres2;
this.city = city;
this.postcode = postcode;
this.user = user;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getAdres1() {
return adres1;
}
public void setAdres1(String adres1) {
this.adres1 = adres1;
}
public String getAdres2() {
return adres2;
}
public void setAdres2(String adres2) {
this.adres2 = adres2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public void setId(Long id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
LOGIC
#RequestMapping(value = "/userDetails", method = RequestMethod.GET)
public String showForm(Model model,
#RequestParam(value = "id", defaultValue = "-1") Long id,
HttpSession session) {
app.Spring.domain.UserDetails va = (id > 0) ? reg.getAdress(id)
: new UserDetails();
model.addAttribute("detal", va);
return "userDetails";
}
#RequestMapping(value = "/userDetails", method = RequestMethod.POST)
public String submit(Model model, #ModelAttribute("detal") UserDetails va,
BindingResult result) {
validator.validate(va, result);
if (result.hasErrors()) {
return "userDetails";
}
reg.saveOrUpdateUserDetails(va);
return "profile";
}
I don't know how to do this with annotations but you might try to manually assign the (hopefully then already present) id fetched from user in the UserDetails entity in the #PrePresist annotated method.
User
#Entity
#Table(name = "USERS")
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
#Column(name = "user_id")
private Long user_id;
#NotBlank
#Size(min = 5, max = 20)
private String username;
#NotBlank
#Size(min = 8, max = 20)
private String password;
private String email;
private String name;
private String surname;
#OneToOne(mappedBy = "user")
private UserDetails userDetail;
User_detail
#Entity
#Table(name = "user_address")
public class UserDetails {
public UserDetails() {
super();
// TODO Auto-generated constructor stub
}
#Id
private Long id;
private String adres1;
private String adres2;
private String city;
private String postcode;
#OneToOne
#JoinColumn(name = "user_id")
private User user;
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;
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'