Hibernate ERROR: Unknown column in delete query (mapping many2many via embedded) - java

I have 2 entities (User and Group) in a many-to-many relantionship. Therefore, I created the table IsIn, which is composed by userId, groupId (composed primary key) and 2 extra fields (typeId and isBlocked). I followed Vlad Mihalcea's tutorial on how to map the entities in such a situation -> see here
However, when I try to delete a user or a group, it doesn't work. I get the following error:
ERROR: Unknown column 'groups0_.user_userId' in 'field list'
javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
I will post below my classes.
UserGroupId (Embedded)
package Embedded;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import java.io.Serializable;
import java.util.Objects;
#Embeddable
public class UserGroupId implements Serializable {
#Column(name = "userId")
private int userId;
#Column(name = "groupId")
private int groupId;
public UserGroupId() {}
public UserGroupId(int userId, int groupId) {
this.userId = userId;
this.groupId = groupId;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
return false;
UserGroupId that = (UserGroupId) o;
return Objects.equals(userId, that.userId) &&
Objects.equals(groupId, that.groupId);
}
#Override
public int hashCode() {
return Objects.hash(userId, groupId);
}
}
IsIn
package entity;
import Embedded.UserGroupId;
import javax.persistence.*;
import java.util.Objects;
#Entity
#Table(name = "isin")
public class IsIn {
#EmbeddedId
private UserGroupId id;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("userId")
private User user;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("groupId")
private Group group;
#OneToOne
#JoinColumn(name = "typeId")
private UserType typeId;
#Column(name = "isBlocked", nullable = false)
private boolean isBlocked;
public IsIn() {}
public IsIn(User user, Group group) {
this.user = user;
this.group = group;
this.id = new UserGroupId(user.getUserId(), group.getGroupId());
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
return false;
IsIn that = (IsIn) o;
return Objects.equals(user, that.user) &&
Objects.equals(group, that.group);
}
#Override
public int hashCode() {
return Objects.hash(user, group);
}
public User getUser() {
return user;
}
public Group getGroup() {
return group;
}
public void setUser(User user) {
this.user = user;
}
public void setGroup(Group group) {
this.group = group;
}
public UserType getTypeId() {
return typeId;
}
public void setTypeId(UserType typeId) {
this.typeId = typeId;
}
public boolean isBlocked() {
return isBlocked;
}
public void setBlocked(boolean blocked) {
isBlocked = blocked;
}
}
User
package entity;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
#Entity
#Table(name = "`user`")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "userId" ,unique = true, nullable = false)
private int userId;
#OneToMany(
mappedBy = "user",
cascade={CascadeType.ALL},
orphanRemoval = true
)
private List<IsIn> groups = new ArrayList<>();
#Column(name = "customerName", nullable = false)
private String customerName;
#Column(name = "password", nullable = false)
private String password;
#Column(name = "email", nullable = false, unique = true)
private String email;
#Column(name = "is_active", nullable = false)
private boolean is_active;
#Column(name = "notificationType", nullable = false)
private String notificationType;
#Column(name = "create_date", nullable = false)
private String create_date;
public User() { }
public User(String customerName, String password, String email, boolean is_active, String notificationType, String create_date) {
this.customerName = customerName;
this.password = password;
this.email = email;
this.is_active = is_active;
this.notificationType = notificationType;
this.create_date = create_date;
}
public void addGroup(Group group) {
IsIn isIn = new IsIn(this, group);
groups.add(isIn);
}
public void removeGroup(Group group) {
for (Iterator<IsIn> iterator = groups.iterator();
iterator.hasNext(); ) {
IsIn isIn = iterator.next();
if (isIn.getUser().equals(this) &&
isIn.getGroup().equals(group)) {
iterator.remove();
isIn.setUser(null);
isIn.setGroup(null);
}
}
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
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 isIs_active() {
return is_active;
}
public void setIs_active(boolean is_active) {
this.is_active = is_active;
}
public String getNotificationType() {
return notificationType;
}
public void setNotificationType(String notificationType) {
this.notificationType = notificationType;
}
public String getCreate_date() {
return create_date;
}
public void setCreate_date(String create_date) {
this.create_date = create_date;
}
}
Group
package entity;
import org.hibernate.annotations.NaturalIdCache;
import javax.persistence.*;
import java.util.Objects;
#Entity
#Table(name = "`group`")
#NaturalIdCache
public class Group {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "groupId")
private int groupId;
#Column(name = "groupName")
private String groupName;
#Column(name = "create_date", nullable = false)
private String create_date;
#OneToOne(fetch=FetchType.EAGER, cascade=CascadeType.ALL, orphanRemoval=true)
#JoinColumn(name = "created_by", nullable = false)
private User user;
#Column(name = "isPrivate")
private boolean isPrivate;
public Group() { }
public Group(String groupName, String create_date, User user, boolean isPrivate) {
this.groupName = groupName;
this.create_date = create_date;
this.user = user;
this.isPrivate = isPrivate;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
return false;
Group group = (Group) o;
return Objects.equals(groupId, group.getGroupId());
}
#Override
public int hashCode() { return Objects.hash(groupId); }
public int getGroupId() {
return groupId;
}
public void setGroupId(int groupId) {
this.groupId = groupId;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public String getCreate_date() {
return create_date;
}
public void setCreate_date(String create_date) {
this.create_date = create_date;
}
public boolean isPrivate() {
return isPrivate;
}
public void setPrivate(boolean aPrivate) {
isPrivate = aPrivate;
}
public User getCreated_by() {
return user;
}
public void setCreated_by(User user) {
this.user = user;
}
}
And here is my delete method (which works for other entities, except for User and Group).
public static void deleteUserById(int userId) {
Session session = sessionFactory.openSession();
try{
session.beginTransaction();
User u = UserDAO.getUserById(userId);
session.delete(u);
session.flush();
session.getTransaction().commit();
} catch (HibernateException he) {
he.printStackTrace();
}
finally {
session.close();
}
}
Any kind of help is highly appreciated, thank you for your time.
Table DDLs
CREATE TABLE IF NOT EXISTS `chatapp`.`user` (
`userId` INT NOT NULL UNIQUE AUTO_INCREMENT,
`customerName` VARCHAR(50) NOT NULL,
`password` VARCHAR(50) NOT NULL,
`email` VARCHAR(255) NOT NULL unique,
`is_active` boolean NOT NULL,
`notificationType` VARCHAR(50) NOT NULL,
`create_date` VARCHAR(50) NOT NULL,
PRIMARY KEY (`userId`),
INDEX `userId_idx` (`userId` ASC)
);
CREATE TABLE IF NOT EXISTS `chatapp`.`group` (
`groupId` INT NOT NULL UNIQUE AUTO_INCREMENT,
`groupName` VARCHAR(255) NULL,
`create_date` VARCHAR(50) NOT NULL,
`created_by` INT NOT NULL,
`isPrivate` boolean NOT NULL,
PRIMARY KEY (`groupId`),
INDEX `groupId_idx` (`groupId` ASC),
FOREIGN KEY (`created_by`) REFERENCES `user` (`userId`)
);
CREATE TABLE IF NOT EXISTS `chatapp`.`isin` (
`userId` INT NOT NULL,
`groupId` INT NOT NULL,
`typeId` INT NOT NULL,
`isBlocked` boolean NOT NULL,
PRIMARY KEY (`userId`,`groupId`),
FOREIGN KEY (`userId`) REFERENCES `user` (`userId`),
FOREIGN KEY (`groupId`) REFERENCES `group` (`groupId`),
FOREIGN KEY (`typeId`) REFERENCES `usertype` (`typeId`)
);
Full StackTrace
here
Complete Database design
here

The #JoinColumn annotations are missing in the IsIn class.
It should look like
#Entity
#Table(name = "isin")
public class IsIn {
#EmbeddedId
private UserGroupId id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn("userId")
private User user;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn("groupId")
private Group group;

Related

not-null property references a null or transient value?

i'm new in spring.I have a project that name is SampleStore. some entities created in my projects, such as User, UserRole, Product, Orders, CartItem and .... but i have a problem. when i try add new user app does it without error and new record inserted in databse. but when i try to insert new order i'll get error.
User.java
#Entity
#Table(name = "users")
public class User implements Serializable, UserDetails {
private static final long serialVersionUID = -8245107356306518473L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false)
private Long id;
#Column(name = "username", nullable = false, unique = true, length = 50)
private String username;
#Column(name = "password", nullable = false, length = 60)
private String password;
#Column(name = "enabled", nullable = true, columnDefinition = "tinyint(1) default 1")
private boolean enabled;
#Column(name = "expired", nullable = true, columnDefinition = "tinyint(1) default 1")
private boolean accountNonExpired;
#Column(name = "locked", nullable = true, columnDefinition = "tinyint(1) default 1")
private boolean accountNonLocked;
#Column(name = "credential", nullable = true, columnDefinition = "tinyint(1) default 1")
private boolean credentialsNonExpired;
#Column(name = "gender", nullable = true)
private char gender;
#Column(name = "address", nullable = true)
private String address;
#Column(name = "phonenumber", nullable = true)
private String phoneNumber;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user")
private Set<UserRole> userRoles = new HashSet<UserRole>(0);
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user")
private List<Comment> comments = new ArrayList<Comment>();
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user")
private List<Orders> orders = new ArrayList<Orders>();
public User() {
}
public User(String username, String password, boolean enabled) {
this.username = username;
this.password = password;
this.enabled = enabled;
}
public User(String username, String password, boolean enabled, Set<UserRole> userRoles) {
this.username = username;
this.password = password;
this.enabled = enabled;
this.userRoles = userRoles;
}
public User(String username, String password, boolean enabled, boolean accountNonExpired,
boolean credentialsNonExpired, boolean accountNonLocked, Set<UserRole> authorities) {
this.username = username;
this.password = password;
this.enabled = enabled;
this.accountNonExpired = accountNonExpired;
this.credentialsNonExpired = credentialsNonExpired;
this.accountNonLocked = accountNonLocked;
this.userRoles = authorities;
}
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 boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public Set<UserRole> getUserRoles() {
return userRoles;
}
public void setUserRoles(Set<UserRole> userRoles) {
this.userRoles = userRoles;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public List<Comment> getComments() {
return comments;
}
public void setComments(List<Comment> comments) {
this.comments = comments;
}
public List<Orders> getOrders() {
return orders;
}
public void setOrders(List<Orders> orders) {
this.orders = orders;
}
#Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + ", enabled=" + enabled
+ ", gender=" + gender + ", address=" + address + ", phoneNumber=" + phoneNumber + ", userRoles="
+ userRoles + "]";
}
public Collection<? extends GrantedAuthority> getAuthorities() {
Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
for (UserRole userRole : userRoles) {
setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
}
List<GrantedAuthority> result = new ArrayList<GrantedAuthority>(setAuths);
return result;
}
public boolean isAccountNonExpired() {
return accountNonExpired;
}
public boolean isAccountNonLocked() {
return accountNonLocked;
}
public boolean isCredentialsNonExpired() {
return credentialsNonExpired;
}
public void setAccountNonExpired(boolean accountNonExpired) {
this.accountNonExpired = accountNonExpired;
}
public void setAccountNonLocked(boolean accountNonLocked) {
this.accountNonLocked = accountNonLocked;
}
public void setCredentialsNonExpired(boolean credentialsNonExpired) {
this.credentialsNonExpired = credentialsNonExpired;
}
}
UserRole.java
#Entity
#Table(name = "user_roles", uniqueConstraints = #UniqueConstraint(columnNames = { "username", "role" }))
public class UserRole {
private Integer userRoleId;
private User user;
private String role;
public UserRole() {
}
public UserRole(User user, String role) {
this.user = user;
this.role = role;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_role_id", unique = true, nullable = false)
public Integer getUserRoleId() {
return this.userRoleId;
}
public void setUserRoleId(Integer userRoleId) {
this.userRoleId = userRoleId;
}
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "username", nullable = false)
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
#Column(name = "role", nullable = false, length = 45)
public String getRole() {
return this.role;
}
public void setRole(String role) {
this.role = role;
}
}
Orders.java
#Entity
#Table(name = "orders")
public class Orders implements Serializable {
private static final long serialVersionUID = -3672662224925418969L;
#Id
#Column(name = "ord_id", nullable = false)
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#DateTimeFormat(pattern = "yyyy-mm-dd")
#Column(name = "orderDate", nullable = false)
private Date orderDate;
#DateTimeFormat(pattern = "yyyy-mm-dd")
#Column(name = "delivery", nullable = false)
private Date deliveryDate;
#Column(name = "success", nullable = true, columnDefinition = "tinyint(1) default 0")
private boolean success;
#Column(name = "cancel", nullable = true, columnDefinition = "tinyint(1) default 0")
private boolean canceled;
#Column(name = "cause", nullable = true)
private String cancelCause;
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "order")
private List<CartItem> items = new ArrayList<CartItem>();
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name="username",nullable=false)
private User user;
public Orders() {
}
public Orders(Date deliveryDate, List<CartItem> items, User user) {
this.orderDate = new Date();
this.deliveryDate = deliveryDate;
this.items = items;
this.user = user;
}
public Orders(List<CartItem> items, User user) {
this.orderDate = new Date();
this.items = items;
this.user = user;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public Date getDeliveryDate() {
return deliveryDate;
}
public void setDeliveryDate(Date deliveryDate) {
this.deliveryDate = deliveryDate;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public boolean isCanceled() {
return canceled;
}
public void setCanceled(boolean canceled) {
this.canceled = canceled;
}
public String getCancelCause() {
return cancelCause;
}
public void setCancelCause(String cancelCause) {
this.cancelCause = cancelCause;
}
public List<CartItem> getItems() {
return items;
}
public void setItems(List<CartItem> items) {
this.items = items;
}
}
CartItem.java
#Entity
#Table(name = "saleitems", uniqueConstraints = {})
public class CartItem implements Serializable {
private static final long serialVersionUID = 7968604053015663078L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(nullable = false)
private Long id;
#Column(name = "prd_id", nullable = false)
private Product product;
#Column(name = "quantity", nullable = false, columnDefinition = "int(11) default 1")
private Integer quantity;
#Column(name = "totalprice", nullable = false)
private BigDecimal totalprice;
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "orderid", nullable = false)
private Orders order;
public CartItem(Product product, Integer quantity) {
this.product = product;
this.quantity = quantity;
setTotalprice();
}
public CartItem() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public BigDecimal getTotalprice() {
return totalprice;
}
public void setTotalprice() {
this.totalprice = getProduct().getPrice().multiply(new BigDecimal(getQuantity()));
}
public Orders getOrder() {
return order;
}
public void setOrder(Orders order) {
this.order = order;
}
}
here one part of my controller code that user to save new user and save new order.
#RequestMapping(value = "/saveuser", method = RequestMethod.POST)
public ModelAndView saveNewUser(#ModelAttribute User user) {
ModelAndView model = new ModelAndView();
user.setEnabled(true);
user.setAccountNonExpired(true);
user.setAccountNonLocked(true);
user.setCredentialsNonExpired(true);
UserRole role = new UserRole(user, "ROLE_USER");
Set<UserRole> roles = new HashSet<UserRole>();
roles.add(role);
user.setUserRoles(roles);
String result = userService.addUser(user);
if (!result.toLowerCase().startsWith("error")) {
model.setViewName("loginForm");
} else {
model.setViewName("newuser");
model.addObject("error", result);
}
return model;
}
#SuppressWarnings("unchecked")
#RequestMapping(value = "/store/addorder", method = RequestMethod.GET)
public ModelAndView addOrder(HttpSession session) {
ModelAndView model = new ModelAndView();
// create list of products that we have to add in orders
System.err.println("item get to retrieving---------------");
List<CartItem> items = (List<CartItem>) session.getAttribute("cart");
for (CartItem cartItem : items) {
System.err.println(cartItem.getProduct());
}
// find user by username to set orders userinfo
System.err.println("user information get to retriving---------------");
String username = SecurityContextHolder.getContext().getAuthentication().getName();
User user = userService.findByUsername(username);
System.err.println(user);
// new order generated and setter methods invoke
System.err.println("new order generated-------------------");
Orders order = new Orders(items, user);
Date d = new Date();
Date delivery = StoreUtils.deliveryDate(d, 3);
order.setOrderDate(d);
order.setDeliveryDate(delivery);
order.setUser(user);
order.setItems(items);
String addOrders = orderService.addOrders(order);
System.err.println("new order add status " + addOrders + "-------------");
System.err.println(order);
// change product quantity after adding new order
for (int i = 0; i < items.size(); i++) {
Integer qSale = items.get(i).getQuantity() * (-1);
productService.rechargeProduct(items.get(i).getProduct(), qSale);
}
if (!addOrders.toLowerCase().contains("error")) {
model.setViewName("successorder");
model.addObject("order", order);
model.addObject("message", addOrders);
session.setAttribute("cart", null);
} else {
session.setAttribute("error", addOrders);
model.setViewName("redirect:/addtocartlist");
}
return model;
}
finally, here my code in dao class that save user and order.
UserDaoImpl.java
public String addUser(User user) {
String result = "";
String pass = encoder.encode(user.getPassword());
user.setPassword(pass);
try {
session().save(user);
session().flush();
result = "success";
} catch (Exception e) {
if (e.getCause().getMessage().toLowerCase().contains("duplicate"))
result = "error :user is already joined to store!";
else
result = "error :" + e.getCause().getMessage();
}
return result;
}
OrderDaoImpl.java
public String addOrders(Orders orders) {
String result = "";
try {
session().save(orders);
result = "success";
} catch (Exception e) {
if (e.getCause() != null)
if (e.getCause().getMessage().toLowerCase().contains("duplicate"))
result = "error this order already was exist";
else
result = "error " + e.getCause().getMessage();
else {
result = "error " + e.getMessage();
}
System.err.println(result);
} finally {
session().clear();
}
return result;
}
All codes are similar, but results are diffrent. when try to add new order I get this exception:
not-null property references a null or transient value:com.softup.store.entity.CartItem.order
Set both sides of relation. On every item call setOrder(). On user setOrder() also.

HibernateQuery returns List of Objects instead of Entities

I'm running a query via Hibernate and it´s returning a list. But the list contains objects instead of my Entities... I'm not a pro in Hibernate, but my other queries work well. I have got no idea what is my mistake right now.
List getAllUsersBasedOnMandant(Long id) {
List users = null;
try {
startOperation(false);
Query query = getSession().createQuery(" from UserEntity where mandant = '" + id + "'");
users = query.list();
} catch (HibernateException e) {
handleException(e);
} finally {
getSession().close();
}
return users;
}
My output looks like this:
[int_plan.entity.UserEntity#4b82b237, int_plan.entity.UserEntity#7141a0bb, int_plan.entity.UserEntity#65b0a12c]
My entity looks like that:
#Entity
#Table(name = "user", schema = "entw_pares")
public class UserEntity {
#Expose() private Long userId;
#Expose() private String gender;
#Expose() private String firstname;
#Expose() private String lastname;
#Expose() private String username;
#Expose() private String email;
private String password;
private String secQuestion;
private String secAnswer;
private String saltAnswer;
private String salt;
private String emailValidationCode;
private Long expireTime;
private Boolean emailEnable = false;
#Expose() private Timestamp dateCreated;
#Expose() private Timestamp dateUpdated;
private Boolean admin = false;
private MandantEntity mandantEntity;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_id", nullable = false)
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
#Basic
#Column(name = "gender", nullable = false)
public String getGender() { return gender; }
public void setGender(String gender){
this.gender = gender;
}
#Basic
#Column(name = "firstname", nullable = false)
public String getFirstname() { return firstname; }
public void setFirstname(String firstnme) { this.firstname = firstnme; }
#Basic
#Column(name = "lastname", nullable = false)
public String getLastname() { return lastname; }
public void setLastname(String lastname) { this.lastname = lastname; }
#Basic
#Column(name = "username")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Basic
#Column(name = "email", nullable = false)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Basic
#Column(name = "password", nullable = false)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Basic
#Column(name = "sec_question")
public String getSecQuestion() { return secQuestion; }
public void setSecQuestion(String sec_question) { this.secQuestion =
sec_question; }
#Basic
#Column(name = "sec_answer")
public String getSecAnswer() { return secAnswer; }
public void setSecAnswer(String secAnswer) { this.secAnswer = secAnswer; }
#Basic
#Column(name = "salt_answer")
public String getSaltAnswer() { return saltAnswer; }
public void setSaltAnswer(String saltAnswer) { this.saltAnswer = saltAnswer;
}
#Basic
#Column(name = "salt")
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
#Basic
#Column(name = "email_validation_code")
public String getEmailValidationCode() {
return emailValidationCode;
}
public void setEmailValidationCode(String emailValidationCode) {
this.emailValidationCode = emailValidationCode;
}
#Basic
#Column(name = "expire_time", nullable = false)
public Long getExpireTime() {
return expireTime;
}
public void setExpireTime(Long expireTime) {
this.expireTime = expireTime;
}
#Basic
#Column(name = "email_enable")
public Boolean getEmailEnable() {
return emailEnable;
}
public void setEmailEnable(Boolean emailEnable) {
this.emailEnable = emailEnable;
}
#Basic
#CreationTimestamp
#Column(name = "date_created")
public Timestamp getDateCreated() {
return dateCreated;
}
public void setDateCreated(Timestamp dateCreated) {
this.dateCreated = dateCreated;
}
#Basic
#UpdateTimestamp
#Column(name = "date_updated")
public Timestamp getDateUpdated() {
return dateUpdated;
}
public void setDateUpdated(Timestamp dateUpdated) {
this.dateUpdated = dateUpdated;
}
#Basic
#Column(name = "admin")
public Boolean getAdmin() {
return admin;
}
public void setAdmin(Boolean admin) {
this.admin = admin;
}
public void applyValue(Field field, Object value) throws
IllegalAccessException {
field.set(this, value);
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserEntity that = (UserEntity) o;
return userId == that.userId &&
Objects.equals(gender, that.gender)&&
Objects.equals(firstname,that.firstname)&&
Objects.equals(lastname,that.lastname)&&
Objects.equals(username, that.username) &&
Objects.equals(email, that.email) &&
Objects.equals(password, that.password) &&
Objects.equals(secQuestion,that.secQuestion) &&
Objects.equals(secAnswer, that.secAnswer) &&
Objects.equals(salt, that.salt) &&
Objects.equals(emailValidationCode, that.emailValidationCode) &&
Objects.equals(emailEnable, that.emailEnable) &&
Objects.equals(dateCreated, that.dateCreated) &&
Objects.equals(dateUpdated, that.dateUpdated) &&
Objects.equals(admin, that.admin);
}
#Override
public int hashCode() {
return Objects.hash(userId, gender, firstname, lastname, username, email,
password, secQuestion, secAnswer,
salt,
emailValidationCode,
emailEnable,
dateCreated, dateUpdated, admin);
}
#ManyToOne
#JoinColumn(name = "mandant_id", referencedColumnName = "mandant_id")
public MandantEntity getMandant() {
return mandantEntity;
}
public void setMandant(MandantEntity mandant) {
this.mandantEntity = mandant;
}
Any ideas what im doing wrong?
I hope I understood the question correctly and that my answer will help you.
Please use query.setParameter([name of parameter], [value]) it will help you with the concationation. more details on that link: https://www.mkyong.com/hibernate/hibernate-parameter-binding-examples/
Your Entitys are now Objects in the users List. you can define your List already to the Objecttype of your desire, for example List<UserEntity> users = q.getResultList()
2.a now you can adress the single elements in your list like
if(!users.isEmpty()) {
for(UserEntity uEntity : users){
uEntity.doSomething()
}
return users.get(0)}
I hope this was helpful for you

hibernate: Use of #OneToMany or #ManyToMany targeting an unmapped class

I'm using hibernate-core in a maven project and I want to create the entities for the following database: db_schema
I'm just starting to learn hibernate, so please bear with me on this one. I know that it might be a stupid mistake but I just can't figure it out.
I'm getting the following exception when I try to test the code:
org.hibernate.AnnotationException: Use of #OneToMany or #ManyToMany targeting an unmapped class: entity.User.groups[entity.IsIn]
I will list the code for my entities below
User
package entity;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
#Entity
#Table(name = "user")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "userId")
private int userId;
#OneToMany(
mappedBy = "user",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<IsIn> groups = new ArrayList<>();
#Column(name = "customerName", nullable = false)
private String customerName;
#Column(name = "password", nullable = false)
private String password;
#Column(name = "email", nullable = false)
private String email;
#Column(name = "is_active", nullable = false)
private boolean is_active;
#Column(name = "notificationType", nullable = false)
private String notificationType;
#Column(name = "create_date", nullable = false)
private String create_date;
public User() { }
public User(String customerName, String password, String email, boolean is_active, String notificationType, String create_date) {
this.customerName = customerName;
this.password = password;
this.email = email;
this.is_active = is_active;
this.notificationType = notificationType;
this.create_date = create_date;
}
public void addGroup(Group group) {
IsIn isIn = new IsIn(this, group);
groups.add(isIn);
}
public void removeGroup(Group group) {
for (Iterator<IsIn> iterator = groups.iterator();
iterator.hasNext(); ) {
IsIn isIn = iterator.next();
if (isIn.getUser().equals(this) &&
isIn.getGroup().equals(group)) {
iterator.remove();
isIn.setUser(null);
isIn.setGroup(null);
}
}
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
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 isIs_active() {
return is_active;
}
public void setIs_active(boolean is_active) {
this.is_active = is_active;
}
public String getNotificationType() {
return notificationType;
}
public void setNotificationType(String notificationType) {
this.notificationType = notificationType;
}
public String getCreate_date() {
return create_date;
}
public void setCreate_date(String create_date) {
this.create_date = create_date;
}
}
Group
package entity;
import org.hibernate.annotations.NaturalIdCache;
import javax.persistence.*;
import java.util.Objects;
#Entity
#Table(name = "group")
#NaturalIdCache
public class Group {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "groupId")
private int groupId;
#Column(name = "groupName")
private String groupName;
#Column(name = "notificationMessage", nullable = false)
private String notificationMessage;
#Column(name = "create_date", nullable = false)
private String create_date;
#OneToOne
#JoinColumn(name = "created_by")
private User created_by;
#Column(name = "isPrivate")
private boolean isPrivate;
public Group() { }
public Group(String groupName, String notificationMessage, String create_date, boolean isPrivate) {
this.groupName = groupName;
this.notificationMessage = notificationMessage;
this.create_date = create_date;
this.isPrivate = isPrivate;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
return false;
Group group = (Group) o;
return Objects.equals(groupId, group.getGroupId());
}
#Override
public int hashCode() { return Objects.hash(groupId); }
public int getGroupId() {
return groupId;
}
public void setGroupId(int groupId) {
this.groupId = groupId;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public String getNotificationMessage() { return notificationMessage; }
public void setNotificationMessage(String notificationMessage) {
this.notificationMessage = notificationMessage;
}
public String getCreate_date() {
return create_date;
}
public void setCreate_date(String create_date) {
this.create_date = create_date;
}
public boolean isPrivate() {
return isPrivate;
}
public void setPrivate(boolean aPrivate) {
isPrivate = aPrivate;
}
public User getCreated_by() {
return created_by;
}
public void setCreated_by(User created_by) {
this.created_by = created_by;
}
}
UserGroupId (Embeddable)
package Embedded;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import java.io.Serializable;
import java.util.Objects;
#Embeddable
public class UserGroupId implements Serializable {
#Column(name = "userId")
private int userId;
#Column(name = "groupId")
private int groupId;
private UserGroupId() {}
public UserGroupId(int userId, int groupId) {
this.userId = userId;
this.groupId = groupId;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
return false;
UserGroupId that = (UserGroupId) o;
return Objects.equals(userId, that.userId) &&
Objects.equals(groupId, that.groupId);
}
#Override
public int hashCode() {
return Objects.hash(userId, groupId);
}
}
IsIn
package entity;
import Embedded.UserGroupId;
import javax.persistence.*;
import java.util.Objects;
#Entity
#Table(name = "isin")
public class IsIn {
#EmbeddedId
private UserGroupId id;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("userId")
private User user;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("groupId")
private Group group;
#OneToOne
#JoinColumn(name = "typeId")
private UserType typeId;
#Column(name = "isBlocked", nullable = false)
private boolean isBlocked;
private IsIn() {}
public IsIn(User user, Group group) {
this.user = user;
this.group = group;
this.id = new UserGroupId(user.getUserId(), group.getGroupId());
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
return false;
IsIn that = (IsIn) o;
return Objects.equals(user, that.user) &&
Objects.equals(group, that.group);
}
#Override
public int hashCode() {
return Objects.hash(user, group);
}
public User getUser() {
return user;
}
public Group getGroup() {
return group;
}
public void setUser(User user) {
this.user = user;
}
public void setGroup(Group group) {
this.group = group;
}
public UserType getTypeId() {
return typeId;
}
public void setTypeId(UserType typeId) {
this.typeId = typeId;
}
public boolean isBlocked() {
return isBlocked;
}
public void setBlocked(boolean blocked) {
isBlocked = blocked;
}
}
Privilege
package entity;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
#Entity
#Table(name = "privilege")
public class Privilege {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "privilegeId")
private int privilegeId;
#Column(name = "privilegeName", nullable = false)
private String privilegeName;
#ManyToMany(mappedBy = "privilege")
private Set<UserType> usertypes = new HashSet<>();
public Privilege() {}
public Privilege(String privilegeName) {
this.privilegeName = privilegeName;
}
public int getPrivilegeId() {
return privilegeId;
}
public void setPrivilegeId(int privilegeId) {
this.privilegeId = privilegeId;
}
public String getPrivilegeName() {
return privilegeName;
}
public void setPrivilegeName(String privilegeName) { this.privilegeName = privilegeName; }
public Set<UserType> getUsertypes() { return usertypes; }
}
UserType
package entity;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
#Entity
#Table(name = "usertype")
public class UserType {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "typeId")
private int typeId;
#Column(name = "typeName", nullable = false)
private String typeName;
#ManyToMany(cascade = { CascadeType.ALL })
#JoinTable(
name = "hasprivilege",
joinColumns = { #JoinColumn(name = "typeId") },
inverseJoinColumns = { #JoinColumn(name = "privilegeId") }
)
Set<Privilege> privileges = new HashSet<>();
public UserType() { }
public UserType(String typeName) {
this.typeName = typeName;
}
public int getTypeId() {
return typeId;
}
public void setTypeId(int typeId) {
this.typeId = typeId;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
}
Notification
package entity;
import javax.persistence.*;
#Entity
#Table(name = "notification")
public class Notification {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "notificationId")
private int notificationId;
#Column(name = "notificationMessage", nullable = false)
private String notificationMessage;
#Column(name = "frequency", nullable = false)
private String frequency;
#Column(name = "create_date", nullable = false)
private String create_date;
#Column(name = "update_date", nullable = false)
private String update_date;
public Notification() {}
public Notification(String notificationMessage, String frequency, String create_date, String update_date) {
this.notificationMessage = notificationMessage;
this.frequency = frequency;
this.create_date = create_date;
this.update_date = update_date;
}
public int getNotificationId() {
return notificationId;
}
public void setNotificationId(int notificationId) {
this.notificationId = notificationId;
}
public String getNotificationMessage() {
return notificationMessage;
}
public void setNotificationMessage(String notificationMessage) {
this.notificationMessage = notificationMessage;
}
public String getFrequency() {
return frequency;
}
public void setFrequency(String frequency) {
this.frequency = frequency;
}
public String getCreate_date() {
return create_date;
}
public void setCreate_date(String create_date) {
this.create_date = create_date;
}
public String getUpdate_date() {
return update_date;
}
public void setUpdate_date(String update_date) {
this.update_date = update_date;
}
}
Message
package entity;
import javax.persistence.*;
#Entity
#Table(name = "message")
public class Message {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "messageId")
private String messageId;
#ManyToOne
#JoinColumn(name = "userId")
private User userId;
#ManyToOne
#JoinColumn(name = "groupId")
private Group groupId;
#Column(name = "message")
private String message;
#Column(name = "create_date")
private String create_date;
#ManyToOne
#JoinColumn(name = "notificationId")
private Notification notificationId;
public Message() { }
public Message(User userId, Group groupId, String message, String create_date, Notification notificationId) {
this.userId = userId;
this.groupId = groupId;
this.message = message;
this.create_date = create_date;
this.notificationId = notificationId;
}
public String getMessageId() {
return messageId;
}
public User getUserId() {
return userId;
}
public Group getGroupId() {
return groupId;
}
public String getMessage() {
return message;
}
public String getCreate_date() {
return create_date;
}
public Notification getNotificationId() {
return notificationId;
}
}
I've been looking on Stack for a solution on similar issues but the suggestions did not help in my case. I'm kinda stuck right now.
Any help will be highly appreciated. Thank your for your time.

Repeated column in mapping for entity error in Spring-MVC project

I connected my MySql database to my Java project (using Spring-MVC) with Entities.
When I try to run the application, I get this error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Repeated column in mapping for entity: com.example.WebAppProcess20.Entities.OrdersitemsEntity column: order_id (should be mapped with insert="false" update="false")
OrdersItems Entity:
package com.example.WebAppProcess20.Entities;
import javax.persistence.*;
import java.util.Objects;
#Entity
#Table(name = "ordersitems", schema = "theprocess", catalog = "")
#IdClass(OrdersitemsEntityPK.class)
public class OrdersitemsEntity {
private String productId;
private String orderId;
private Integer qunatity;
private ProductsEntity productsByProductId;
private OrdersEntity ordersByOrderId;
#Id
#Column(name = "product_id")
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
#Id
#Column(name = "orderId", nullable = false, insertable = false, updatable = false)
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
#Basic
#Column(name = "qunatity")
public Integer getQunatity() {
return qunatity;
}
public void setQunatity(Integer qunatity) {
this.qunatity = qunatity;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
OrdersitemsEntity that = (OrdersitemsEntity) o;
return Objects.equals(productId, that.productId) &&
Objects.equals(orderId, that.orderId) &&
Objects.equals(qunatity, that.qunatity);
}
#Override
public int hashCode() {
return Objects.hash(productId, orderId, qunatity);
}
#ManyToOne
#JoinColumn(name = "product_id", referencedColumnName = "product_id", nullable = false)
public ProductsEntity getProductsByProductId() {
return productsByProductId;
}
public void setProductsByProductId(ProductsEntity productsByProductId) {
this.productsByProductId = productsByProductId;
}
#ManyToOne
#JoinColumn(name = "orderId", referencedColumnName = "orderId", nullable = false)
public OrdersEntity getOrdersByOrderId() {
return ordersByOrderId;
}
public void setOrdersByOrderId(OrdersEntity ordersByOrderId) {
this.ordersByOrderId = ordersByOrderId;
}
}
Orders Entity:
package com.example.WebAppProcess20.Entities;
import javax.persistence.*;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.Objects;
#Entity
#Table(name = "orders", schema = "theprocess", catalog = "")
public class OrdersEntity {
private String orderId;
private String notesFromClient;
private Timestamp orderDate;
private String orderStatus;
private String totalSum;
private ClientsEntity clientsByClientId;
private Collection<OrdersitemsEntity> ordersitemsByOrderId;
#Id
#Column(name = "orderId")
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
#Basic
#Column(name = "notes_from_client")
public String getNotesFromClient() {
return notesFromClient;
}
public void setNotesFromClient(String notesFromClient) {
this.notesFromClient = notesFromClient;
}
#Basic
#Column(name = "order_date")
public Timestamp getOrderDate() {
return orderDate;
}
public void setOrderDate(Timestamp orderDate) {
this.orderDate = orderDate;
}
#Basic
#Column(name = "order_status")
public String getOrderStatus() {
return orderStatus;
}
public void setOrderStatus(String orderStatus) {
this.orderStatus = orderStatus;
}
#Basic
#Column(name = "totalSum")
public String getTotalSum() {
return totalSum;
}
public void setTotalSum(String totalSum) {
this.totalSum = totalSum;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
OrdersEntity that = (OrdersEntity) o;
return Objects.equals(orderId, that.orderId) &&
Objects.equals(notesFromClient, that.notesFromClient) &&
Objects.equals(orderDate, that.orderDate) &&
Objects.equals(orderStatus, that.orderStatus) &&
Objects.equals(totalSum, that.totalSum);
}
#Override
public int hashCode() {
return Objects.hash(orderId, notesFromClient, orderDate, orderStatus, totalSum);
}
#ManyToOne
#JoinColumn(name = "client_id", referencedColumnName = "client_id", nullable = false)
public ClientsEntity getClientsByClientId() {
return clientsByClientId;
}
public void setClientsByClientId(ClientsEntity clientsByClientId) {
this.clientsByClientId = clientsByClientId;
}
#OneToMany(mappedBy = "ordersByOrderId")
public Collection<OrdersitemsEntity> getOrdersitemsByOrderId() {
return ordersitemsByOrderId;
}
public void setOrdersitemsByOrderId(Collection<OrdersitemsEntity> ordersitemsByOrderId) {
this.ordersitemsByOrderId = ordersitemsByOrderId;
}
}
OrdersItemsPK class:
package com.example.WebAppProcess20.Entities;
import javax.persistence.Column;
import javax.persistence.Id;
import java.io.Serializable;
import java.util.Objects;
public class OrdersitemsEntityPK implements Serializable {
private String productId;
private String orderId;
#Column(name = "product_id")
#Id
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
#Column(name = "orderId")
#Id
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
OrdersitemsEntityPK that = (OrdersitemsEntityPK) o;
return Objects.equals(productId, that.productId) &&
Objects.equals(orderId, that.orderId);
}
#Override
public int hashCode() {
return Objects.hash(productId, orderId);
}
}
Products Entity:
package com.example.WebAppProcess20.Entities;
import javax.persistence.*;
import java.util.Collection;
import java.util.Objects;
#Entity
#Table(name = "products", schema = "theprocess", catalog = "")
public class ProductsEntity {
private String productId;
private Integer availableInStock;
private String brand;
private String image;
private Integer price;
private String productCategoryTree;
private String productName;
private Integer rating;
private Collection<OrdersitemsEntity> ordersitemsByProductId;
#Id
#Column(name = "product_id")
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
#Basic
#Column(name = "available_in_stock")
public Integer getAvailableInStock() {
return availableInStock;
}
public void setAvailableInStock(Integer availableInStock) {
this.availableInStock = availableInStock;
}
#Basic
#Column(name = "brand")
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
#Basic
#Column(name = "image")
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
#Basic
#Column(name = "price")
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
#Basic
#Column(name = "product_category_tree")
public String getProductCategoryTree() {
return productCategoryTree;
}
public void setProductCategoryTree(String productCategoryTree) {
this.productCategoryTree = productCategoryTree;
}
#Basic
#Column(name = "product_name")
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
#Basic
#Column(name = "rating")
public Integer getRating() {
return rating;
}
public void setRating(Integer rating) {
this.rating = rating;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ProductsEntity that = (ProductsEntity) o;
return Objects.equals(productId, that.productId) &&
Objects.equals(availableInStock, that.availableInStock) &&
Objects.equals(brand, that.brand) &&
Objects.equals(image, that.image) &&
Objects.equals(price, that.price) &&
Objects.equals(productCategoryTree, that.productCategoryTree) &&
Objects.equals(productName, that.productName) &&
Objects.equals(rating, that.rating);
}
#Override
public int hashCode() {
return Objects.hash(productId, availableInStock, brand, image, price, productCategoryTree, productName, rating);
}
#OneToMany(mappedBy = "productsByProductId")
public Collection<OrdersitemsEntity> getOrdersitemsByProductId() {
return ordersitemsByProductId;
}
public void setOrdersitemsByProductId(Collection<OrdersitemsEntity> ordersitemsByProductId) {
this.ordersitemsByProductId = ordersitemsByProductId;
}
}
Ordersitems connects between Orders and Products - it contains the products of each order, so productId and orderId both foreign keys in Orderitems.
I think I understand the error, if I'm not wrong, the reapeted column error refers to:
#Id
#Column(name = "orderId", nullable = false, insertable = false, updatable = false)
public String getOrderId() {
return orderId;
}
and:
#ManyToOne
#JoinColumn(name = "orderId", referencedColumnName = "orderId", nullable = false)
public OrdersEntity getOrdersByOrderId() {
return ordersByOrderId;
}
public void setOrdersByOrderId(OrdersEntity ordersByOrderId) {
this.ordersByOrderId = ordersByOrderId;
}
But whatever I tried to do didn't solve the problem or even added other errors.
Can you please help me to solve this problem?
Thanks!

Saving cascade with Hibernate

I have the following entities and I'm trying to save them using hibernate cascade:
Entity Usuario:
#Entity
#Table(schema="system", name="usuarios")
public class Usuario {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column(nullable = false)
private String nome;
#Column(name = "data_nascimento")
private Date dataNascimento;
private String sexo;
#OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "usuario")
private DadosFuncionario dadosFuncionario;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Date getDataNascimento() {
return dataNascimento;
}
public void setDataNascimento(Date dataNascimento) {
this.dataNascimento = dataNascimento;
}
public String getSexo() {
return sexo;
}
public void setSexo(String sexo) {
this.sexo = sexo;
}
public DadosFuncionario getDadosFuncionario() {
return dadosFuncionario;
}
public void setDadosFuncionario(DadosFuncionario dadosFuncionario) {
this.dadosFuncionario = dadosFuncionario;
}
}
Table structure for usuarios:
CREATE TABLE "system"."usuarios" (
"id" int4 NOT NULL,
"data_nascimento" date,
"nome" varchar(255) COLLATE "default" NOT NULL,
"sexo" varchar(255) COLLATE "default"
)
Entity DadosFuncionario:
#Entity
#Table(schema = "system", name = "dados_funcionario")
public class DadosFuncionario {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column(unique = true)
private String matricula;
#Column(name = "pref_reg", nullable = true)
private int prefReg;
#Column(name = "pref_dep", nullable = false)
private int prefDep;
#Column(nullable = true)
private String telefone;
#OneToOne
#JoinColumn(name = "id_usuario")
private Usuario usuario;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMatricula() {
return matricula;
}
public void setMatricula(String matricula) {
this.matricula = matricula;
}
public int getPrefReg() {
return prefReg;
}
public void setPrefReg(int prefReg) {
this.prefReg = prefReg;
}
public int getPrefDep() {
return prefDep;
}
public void setPrefDep(int prefDep) {
this.prefDep = prefDep;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public Usuario getUsuario() {
return usuario;
}
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
}
Table structure for dados_funcionario:
CREATE TABLE "system"."dados_funcionario" (
"id" int4 NOT NULL,
"matricula" varchar(255) COLLATE "default",
"pref_dep" int4 NOT NULL,
"pref_reg" int4,
"telefone" varchar(255) COLLATE "default",
"id_usuario" int4
)
And then to test if it was saving everything the way it was supposed to, I'm doing this:
Usuario novoUsuario = new Usuario();
DadosFuncionario novoDadosFuncionario = new DadosFuncionario();
novoDadosFuncionario.setMatricula("XXXXXXXXX");
novoDadosFuncionario.setPrefDep(9999);
novoUsuario.setNome("XXXXX XXXXX");
novoUsuario.setDadosFuncionario(novoDadosFuncionario);
Transaction tx = session.beginTransaction();
session.save(novoUsuario);
tx.commit();
It insert the correct data into the correct tables, but it does not save the foreign key of usuarios in dados_funcionario (its filling the column id_usuario with null). So, it understands the relationship (it saved in cascade, because I only used the session.save() with novoUsuario and it saved the data from novoDadosFuncionario) but it doesn't insert the foreign key and I can't figure out why.
You are not setting the other side of the relation anywhere, which you should in bidirectional relationships. Add this
novoDadosFuncionario.setUsuario(novoUsuario);

Categories

Resources