need to save child without retrieve it in hibernate - java

I need to save the child table values without retrieve the values.
POJO Class:
public class User {
private String firstName;
#Id
#SequenceGenerator(name = "userID", sequenceName = "userID")
#GeneratedValue(strategy = GenerationType.AUTO, generator = "userID")
#Column(name = "id")
private Long id;
private String lastName;
private Integer passwordReset;
#Column(name = "useremail", nullable = false, unique = true)
#Email
#NotEmpty
private String email;
#Column(name = "password", nullable = false)
private String password;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "user_id", referencedColumnName = "id")
private List<WashingOrder> orderList;
#Column(unique = true)
#NotEmpty(message = "{username}")
private String username;
public String getFirstName() {
return firstName;
}
public Long getId() {
return id;
}
public String getLastName() {
return lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public String getUsername() {
return username;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setId(Long id) {
this.id = id;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setPassword(String password) {
this.password = password;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getPasswordReset() {
return passwordReset;
}
public void setPasswordReset(Integer passwordReset) {
this.passwordReset = passwordReset;
}
public List<WashingOrder> getOrderList() {
return orderList;
}
public void setOrderList(List<WashingOrder> orderList) {
this.orderList = orderList;
}
}
public class WashingOrder {
#Id
#SequenceGenerator(name = "orderNo", sequenceName = "orderNo")
#GeneratedValue(strategy = GenerationType.AUTO, generator = "orderNo")
#Column(name = "orderNo")
private Long orderNo;
#Column(name = "totalClothes", nullable = false)
#NotNull
private Integer totalClothes;
#Column(name = "mensCloth", nullable = true)
private Integer mensCloth;
#Column(name = "womensCloth", nullable = true)
private Integer womensCloth;
#Column(name = "otherCloth", nullable = true)
private Integer otherClothes;
#Column(name = "deliveryDate", nullable = true)
/* #DateTimeFormat(pattern = "yyyy-mm-dd") */
private Date deliveryDate;
#Column(name = "status", nullable = true)
private String orderStatus;
public Long getOrderNo() {
return orderNo;
}
public void setOrderNo(Long orderNo) {
this.orderNo = orderNo;
}
public Integer getTotalClothes() {
return totalClothes;
}
public void setTotalClothes(Integer totalClothes) {
this.totalClothes = totalClothes;
}
public Integer getMensCloth() {
return mensCloth;
}
public void setMensCloth(Integer mensCloth) {
this.mensCloth = mensCloth;
}
public Integer getWomensCloth() {
return womensCloth;
}
public void setWomensCloth(Integer womensCloth) {
this.womensCloth = womensCloth;
}
public Integer getOtherClothes() {
return otherClothes;
}
public void setOtherClothes(Integer otherClothes) {
this.otherClothes = otherClothes;
}
public Date getDeliveryDate() {
return deliveryDate;
}
public void setDeliveryDate(Date deliveryDate) {
this.deliveryDate = deliveryDate;
}
public String getOrderStatus() {
return orderStatus;
}
public void setOrderStatus(String orderStatus) {
this.orderStatus = orderStatus;
}
}
Implementation:
Session session = sessionFactory.getCurrentSession();
long id = 1;
Query query = session.createQuery("from user where id =" + id);
User emp6 = (User) session.load(User.class, new Long(1));
User user = (User) query.uniqueResult();
List<WashingOrder> washingOrder = user.getOrderList();
washingOrder.add(order);
user.setOrderList(washingOrder);
session.save(user);
Long orderID = (long) 1;
return orderID;
Here if you check I am getting the order list first (user.getOrderList()) and then I am adding the new list and saving the user.
But I want to save the new order list of the user without retrieve the previous order list.
There is any possibility for the adding new order data without retrieve the previous order list of the particular user.

You need to change a mapping
public class User {
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<WashingOrder> orderList;
}
public class WashingOrder {
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "user_id")
private User user;
}
Session session = sessionFactory.getCurrentSession();
User user = (User) session.load(User.class, 1L);
WashingOrder order = new WashingOrder();
order.setUser(user);
session.save(order);
You can try to use a fake User instead of loading
WashingOrder order = new WashingOrder();
order.setUser(new User(1L));
session.save(order);

Related

Hibernate doesn't create table that implements Serializable interface?

I have small project with Spring Data, MVC and Web Flow. Also I have 2 entities that I use in Spring Web Flow, so they MUST implement Serializable interface, but I noticed that Hibernate doesn't create tables, that implement it, for proving it I just copied my entity, removed "implements Serializable" created new class and pasted the entity code there, the new table was created. How it works ? How to create table from entity that implement Serializable, is it possible at all ?
The entities code:
#Table(name = "users")
#Entity
public class User implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "idUsers")
private int id;
#Column(name = "login")
#Size(min = 3, max = 15,message = "Неправильний розмір")
#NotEmpty(message = "Не може бути пустим!")
private String login;
#Size(min = 6, max = 21,message = "Неправильний розмір")
#NotEmpty(message = "Не може бути пустим!")
#Column(name = "password")
private String password;
#NotNull(message = "Не може бути пустим!")
#Column(name = "email")
private String email;
#Column(name = "photo")
private String path;
#Column(name = "about")
private String about;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#OneToMany(
fetch = FetchType.EAGER,
mappedBy = "user",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private Set<CommentsToBook> commentsToBooks;
public Set<CommentsToBook> getCommentsToBooks() {
return commentsToBooks;
}
public void setCommentsToBooks(Set<CommentsToBook> commentsToBooks) {
this.commentsToBooks = commentsToBooks;
}
public Set<BookOrder> getOrders() {
return orders;
}
public void setOrders(Set<BookOrder> orders) {
this.orders = orders;
}
#OneToMany(
fetch = FetchType.EAGER,
mappedBy = "user",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private Set<BookOrder> orders;
public String getPath() {
return path;
}
public String getAbout() {
return about;
}
public void setAbout(String about) {
this.about = about;
}
public void setPath(String path) {
this.path = path;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
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;
}
}
And the second one:
#Entity
#Table(name = "booook_order")
public class BookOrder implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private int id;
#Column(name = "bank_card")
private String bankCardId;
#Column(name = "user_name")
private String custName;
public User getUser() {
return user;
}
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(name = "book", joinColumns = {
#JoinColumn(name = "id")
},inverseJoinColumns = {#JoinColumn(name = "idlibrary")})
private Set<Book> booksList;
#Column(name ="novaposhta-vid")
private String NPVid;
public String getNPVid() {
return NPVid;
}
public void setNPVid(String NPVid) {
this.NPVid = NPVid;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
#Column(name = "city")
private String city;
public void setUser(User user) {
this.user = user;
}
#ManyToOne(cascade = CascadeType.ALL,
fetch = FetchType.EAGER)
#JoinColumn(name = "idUsers")
private User user;
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Set<Book> getBooksList() {
return booksList;
}
public void setBooksList(Set<Book> booksList) {
this.booksList = booksList;
}
public String getBankCardId() {
return bankCardId;
}
public void setBankCardId(String bankCardId) {
this.bankCardId = bankCardId;
}
}

OneToMany relationship error: Field 'XX' doesn't have a default value

I'm trying to create One-To-Many relationship between two objects but I got this error. I don't know how to mapping property ID from object MyUserAccount to object Book. ID is a String data received from Google (I'm doing Social Login in my project).
Error
PreparedStatementCallback; SQL [INSERT INTO Books(TENSACH, TACGIA, NHANXET, TINHTRANG, THELOAI, IMAGE, IMAGE_NAME) VALUES ( ?, ?, ?, ?, ?, ?, ?)]; Field 'ID' doesn't have a default value; nested exception is java.sql.SQLException: Field 'ID' doesn't have a default value
BookDao (How I save object Book into database)
public void save(Book book) {
// TODO Auto-generated method stub
KeyHolder keyHolder = new GeneratedKeyHolder();
String sql = "INSERT INTO Books(TENSACH, TACGIA, NHANXET, TINHTRANG, THELOAI, IMAGE, IMAGE_NAME) "
+ "VALUES ( :tensach, :tacgia, :nhanxet, :tinhtrang, :theloai, :image, :image_name)";
namedParameterJdbcTemplate.update(sql, getSqlParameterByModel(book), keyHolder);
book.setBook_ID(keyHolder.getKey().intValue());
}
private SqlParameterSource getSqlParameterByModel(Book book) {
MapSqlParameterSource paramSource = new MapSqlParameterSource();
paramSource.addValue("book_id", book.getBook_ID());
paramSource.addValue("tensach", book.getTensach());
paramSource.addValue("tacgia", book.getTacgia());
paramSource.addValue("nhanxet", book.getNhanxet());
paramSource.addValue("tinhtrang", book.getTinhtrang());
paramSource.addValue("image", book.getImage());
paramSource.addValue("image_name", book.getImage_name());
paramSource.addValue("theloai", book.getTheloai());
return paramSource;
}
Model Book
public class Book implements Serializable {
private static final long serialVersionUID = 1L;
private Integer book_ID;
private String tensach;
private String tacgia;
private String nhanxet;
private String tinhtrang;
private String theloai;
private byte[] image;
private String image_name;
private String data;
private MyUserAccount myUserAccount;
public Book() {
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "ID", nullable = false)
public MyUserAccount getMyUserAccount() {
return this.myUserAccount;
}
public void setMyUserAccount(MyUserAccount myUserAccount) {
this.myUserAccount = myUserAccount;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "book_id", unique = true, nullable = false)
public Integer getBook_ID() {
return book_ID;
}
#Column(name = "image_name")
public String getImage_name() {
return image_name;
}
#Column(name = "tensach", length = 50, nullable = true)
public String getTensach() {
return tensach;
}
#Lob
#Type(type = "org.hibernate.type.BinaryType")
#Column(name = "image", columnDefinition = "LONGBLOB", nullable = true)
public byte[] getImage() {
return image;
}
#Column(name = "tacgia", length = 50, nullable = true)
public String getTacgia() {
return tacgia;
}
#Column(name = "nhanxet", length = 100, nullable = true)
public String getNhanxet() {
return nhanxet;
}
#Column(name = "tinhtrang", length = 50, nullable = true)
public String getTinhtrang() {
return tinhtrang;
}
#Column(name = "theloai", length = 50, nullable = true)
public String getTheloai() {
return theloai;
}
#Column(name = "data", length = 16777215)
public String getData() {
return data;
}
public void setBook_ID(Integer book_ID) {
this.book_ID = book_ID;
}
public void setImage_name(String image_name) {
this.image_name = image_name;
}
public void setImage(byte[] image) {
this.image = image;
}
public void setTensach(String tensach) {
this.tensach = tensach;
}
public void setTacgia(String tacgia) {
this.tacgia = tacgia;
}
public void setNhanxet(String nhanxet) {
this.nhanxet = nhanxet;
}
public void setTinhtrang(String tinhtrang) {
this.tinhtrang = tinhtrang;
}
public void setTheloai(String theloai) {
this.theloai = theloai;
}
public void setData(String data) {
this.data = data;
}
#Override
public String toString() {
return "Book [book_ID=" + book_ID + ", tensach=" + tensach + ", tacgia=" + tacgia + ", nhanxet=" + nhanxet
+ ", tinhtrang=" + tinhtrang + ", theloai=" + theloai + ", image=" + Arrays.toString(image) + "]";
}
}
Model MyUserAccount.
public class MyUserAccount implements Serializable {
private static final long serialVersionUID = 1L;
public static final String ROLE_USER = "ROLE_USER";
private String id;
private String email;
private String userName;
private String firstName;
private String lastName;
private String password;
private String role;
private String enabled;
private List<Book> book = new ArrayList<Book>(0);
public MyUserAccount() {
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "myUserAccount")
public List<Book> getBook() {
return book;
}
public void setBook(List<Book> book) {
this.book = book;
}
public MyUserAccount(String id, String email, String userName, String firstName, //
String lastName, String password, String role, String enabled) {
this.id = id;
this.email = email;
this.userName = userName;
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
this.role = role;
this.enabled = enabled;
}
#Id
#Column(name = "ID", unique = true, nullable = false)
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Column(name = "EMAIL", unique = true, nullable = false)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name = "USER_NAME", unique = true, nullable = false)
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
#Column(name = "FIRST_NAME", nullable = false)
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "LAST_NAME", nullable = false)
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Column(name = "PASSWORD", nullable = false)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name = "ROLE", nullable = false)
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
#Column(name = "ENABLED", columnDefinition = "VARCHAR(1) default 'Y'", nullable = false)
public String getEnabled() {
return enabled;
}
public void setEnabled(String enabled) {
this.enabled = enabled;
}
}
Controller
#RequestMapping(value = "/motsach/add/", method = RequestMethod.POST)
public String saveBook(#ModelAttribute("bookForm") #Validated Book book, BindingResult result, Model model,
#RequestParam CommonsMultipartFile[] image, String userName, final RedirectAttributes redirectAttributes)
throws IOException, UnsupportedEncodingException {
MyUserAccount myUserAccount = myUserAccountDAO.findByUserName(userName);
System.out.println(userName + "sssssssssssss");
book.setMyUserAccount(myUserAccount);
redirectAttributes.addFlashAttribute("css", "success");
if (book.getBook_ID() == null) {
System.out.println(book.getBook_ID());
redirectAttributes.addFlashAttribute("msg", "book added successfully!");
} else {
redirectAttributes.addFlashAttribute("msg", "book updated successfully!");
}
for (CommonsMultipartFile aFile : image) {
System.out.println("Saving file: " + aFile.getOriginalFilename());
book.setImage_name(aFile.getOriginalFilename());
book.setImage(aFile.getBytes());
System.out.println("Damn that Shit!");
}
bookService.saveOrUpdate(book);
// POST/REDIRECT/GET
return "redirect:/motsach/" + book.getBook_ID();
}
You have a #manyToOne (with ID as name ) relation that can't be null. So in order to add a book you have to set MyUserAccount to a book before saving or you can turn into :
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "ID", nullable = true)
public MyUserAccount getMyUserAccount() {
return this.myUserAccount;
}
and modify your column in your database to set the possibility of null value.

How to formulate JPA method for findBy Join table column

I have two table i.e. User and Organization having join . i have to write a method which will give users on basis of organisation name containing the input string.
User.java
#Entity
#Table(name = "USERS")
#EntityListeners(UsersEntityListener.class)
#NamedQueries({
#NamedQuery(name = "User.findAll", query = "SELECT u FROM User u")})
public class User extends Domain implements Serializable {
private static final long serialVersionUID = 1L;
#Basic(optional = false)
#Column(name = "FIRST_NAME", nullable = false)
private String firstName;
#Basic(optional = false)
#Column(name = "LAST_NAME", nullable = false)
private String lastName;
#Column(name = "MIDDLE_NAME")
private String middleName;
#Basic(optional = false)
#Column(name = "GENDER", nullable = false)
private String gender;
#Basic(optional = false)
#Column(name = "MOBILE", nullable = false)
private String mobile;
#Basic(optional = false)
#Column(name = "EMAIL", nullable = false)
private String email;
#Basic(optional = false)
#Column(name = "USERNAME", nullable = false)
private String username;
#Basic(optional = false)
#Column(name = "PASSWORD", nullable = false)
private String password;
#Column(name = "URL")
private String url;
#PrePersist
public void encryptPassword(){
this.setPassword(new BCryptPasswordEncoder().encode(getPassword()));
}
#OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
private List<UserRole> userRoles;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "user")
private Organization organization;
public User() {
}
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 getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
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 getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Organization getOrganization() {
return organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
public List<UserRole> getUserRoles() {
return userRoles;
}
public void setUserRoles(List<UserRole> userRoles) {
this.userRoles = userRoles;
}
}
Organization.java
#Entity
#Table(name = "ORGANIZATIONS", uniqueConstraints = {
#UniqueConstraint(columnNames = {"USER_ID"})})
#NamedQueries({
#NamedQuery(name = "Organization.findAll", query = "SELECT o FROM Organization o")})
public class Organization extends Domain implements Serializable {
private static final long serialVersionUID = 1L;
#Basic(optional = false)
#Column(name = "ORGANIZATION", nullable = false, length = 256)
private String organization;
#Column(name = "WEBSITE")
private String website;
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
#OneToMany(cascade = CascadeType.ALL, mappedBy = "organization")
private List<Location> locations;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "senderOrganization")
private List<PurchaseOrder> sendPurchaseOrders;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "receiverOrganization")
private List<PurchaseOrder> receivedPurchaseOrders;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "organization")
private List<Purchaser> purchasing;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "senderOrganization")
private List<Quotation> sendQuotations;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "receiverOrganization")
private List<Quotation> receivedQuotations;
#JoinColumn(name = "USER_ID", referencedColumnName = "ID", nullable = false)
#OneToOne(optional = false)
private User user;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "senderOrganization")
private List<Enquiry> sendEnquiries;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "receiverOrganization")
private List<Enquiry> receivedEnquiries;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "organization")
private List<Supplier> supplying;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "senderOrganization")
private List<Invoice> sendInvoices;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "receiverOrganization")
private List<Invoice> receivedInvoices;
public Organization() {
}
public String getOrganization() {
return organization;
}
public void setOrganization(String organization) {
this.organization = organization;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<Location> getLocations() {
return locations;
}
public void setLocations(List<Location> locations) {
this.locations = locations;
}
public List<PurchaseOrder> getSendPurchaseOrders() {
return sendPurchaseOrders;
}
public void setSendPurchaseOrders(List<PurchaseOrder> sendPurchaseOrders) {
this.sendPurchaseOrders = sendPurchaseOrders;
}
public List<PurchaseOrder> getReceivedPurchaseOrders() {
return receivedPurchaseOrders;
}
public void setReceivedPurchaseOrders(List<PurchaseOrder> receivedPurchaseOrders) {
this.receivedPurchaseOrders = receivedPurchaseOrders;
}
public List<Purchaser> getPurchasing() {
return purchasing;
}
public void setPurchasing(List<Purchaser> purchasing) {
this.purchasing = purchasing;
}
public List<Quotation> getSendQuotations() {
return sendQuotations;
}
public void setSendQuotations(List<Quotation> sendQuotations) {
this.sendQuotations = sendQuotations;
}
public List<Quotation> getReceivedQuotations() {
return receivedQuotations;
}
public void setReceivedQuotations(List<Quotation> receivedQuotations) {
this.receivedQuotations = receivedQuotations;
}
public List<Enquiry> getSendEnquiries() {
return sendEnquiries;
}
public void setSendEnquiries(List<Enquiry> sendEnquiries) {
this.sendEnquiries = sendEnquiries;
}
public List<Enquiry> getReceivedEnquiries() {
return receivedEnquiries;
}
public void setReceivedEnquiries(List<Enquiry> receivedEnquiries) {
this.receivedEnquiries = receivedEnquiries;
}
public List<Supplier> getSupplying() {
return supplying;
}
public void setSupplying(List<Supplier> supplying) {
this.supplying = supplying;
}
public List<Invoice> getSendInvoices() {
return sendInvoices;
}
public void setSendInvoices(List<Invoice> sendInvoices) {
this.sendInvoices = sendInvoices;
}
public List<Invoice> getReceivedInvoices() {
return receivedInvoices;
}
public void setReceivedInvoices(List<Invoice> receivedInvoices) {
this.receivedInvoices = receivedInvoices;
}
#OneToMany(mappedBy = "organization")
private List<Tax> taxes;
public List<Tax> getTaxes() {
return taxes;
}
public void setTaxes(List<Tax> taxes) {
this.taxes = taxes;
}
#OneToMany(mappedBy = "organization")
private List<Identity> identities;
public List<Identity> getIdentities() {
return identities;
}
public void setIdentities(List<Identity> identities) {
this.identities = identities;
}
}
IUserRepository
#Repository
#RepositoryRestResource
public interface IUserRepository extends JpaRepository<User, UUID> {
Page<User> findByOrganizationContaining(#Param("organization") String organization, Pageable pageable);
}
I have created this method as
Page<User> findByOrganizationContaining(#Param("organization") String organization, Pageable pageable);
But its not working out as i wanna search it on the basis of organization name which is column in organization table.
you don't have name attribute in Organization, You have organization I think that is what you are referrring to. you can do something like this
Page<User> findByOrganization_Organization(String organization, Pageable pageable);
underscore(_) refers to nested fields. But for this to work, you need to fetch organization eagerly.
#OneToOne(cascade = CascadeType.ALL, mappedBy = "user", fetch=FetchType.EAGER)
private Organization organization;
Hello you can use either query method or something like this can help you out
Page<User> findByOrganization_Organization(#Param(organization)String organization, Pageable pageable);

Hibernate mappedBy and ManyToMany

I'm starting from scratch a new project and i got this problem which i cannot solve. I have three entities, and they all have a manytomany relationship with each other. There is the Cluster:
#Entity
#Component
#Table(name = "clusterEntity")
public class Cluster {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false, updatable = false)
private Long id;
#Column(name = "name")
private String name;
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;
}
#ManyToMany
#JoinTable(name="cluster_user",
joinColumns=#JoinColumn(name="cluster_id", referencedColumnName="id"),
inverseJoinColumns=#JoinColumn(name="user_id", referencedColumnName="id"))
private List<User> users_cluster;
#ManyToMany
#JoinTable(name="cluster_sito",
joinColumns=#JoinColumn(name="cluster_id", referencedColumnName="id"),
inverseJoinColumns=#JoinColumn(name="sito_id", referencedColumnName="id"))
private List<Sito> sitos;
#Override
public String toString() {
return "Cluster{" +
"id=" + id +
", name='" + name +
", users='" + users_cluster.toString() +
'}';
}
}
This is the User:
#Entity
#Component
#Table(name = "userEntity")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false, updatable = false)
private Long id;
#Column(name = "email", nullable = false, unique = true)
private String email;
#Column(name = "password_hash", nullable = false)
private String passwordHash;
#Column(name = "role", nullable = false)
#Enumerated(EnumType.STRING)
private Role role;
#Column(name = "G1", nullable = true)
private String G1;
#Column(name = "G2", nullable = true)
private String G2;
#Column(name = "G3", nullable = true)
private String G3;
#Column(name = "G4", nullable = true)
private String G4;
#Column(name = "G5", nullable = true)
private String G5;
#Column(name = "G6", nullable = true)
private String G6;
#Column (name = "access_token", nullable = true)
private String access_token;
#Column (name = "refresh_token", nullable = true)
private String refresh_token;
public Long getId() {
return id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPasswordHash() {
return passwordHash;
}
public void setPasswordHash(String passwordHash) {
this.passwordHash = passwordHash;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public String getG1() {
return G1;
}
public void setG1(String g1) {
G1 = g1;
}
public String getG2() {
return G2;
}
public void setG2(String g2) {
G2 = g2;
}
public String getG3() {
return G3;
}
public void setG3(String g3) {
G3 = g3;
}
public String getG4() {
return G4;
}
public void setG4(String g4) {
G4 = g4;
}
public String getG5() {
return G5;
}
public void setG5(String g5) {
G5 = g5;
}
public String getG6() {
return G6;
}
public void setG6(String g6) {
G6 = g6;
}
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public String getRefresh_token() {
return refresh_token;
}
public void setRefresh_token(String refresh_token) {
this.refresh_token = refresh_token;
}
#ManyToMany(mappedBy="users_cluster")
private List<User> users_cluster;
#ManyToMany(mappedBy="users_sito")
private List<User> users_sito;
public User(){}
#Override
public String toString() {
return "User{" +
"id=" + id +
", email='" + email.replaceFirst("#.*", "#***") +
", passwordHash='" + passwordHash.substring(0, 10) +
", role=" + role +
'}';
}
}
This is the Sito:
#Entity
#Component
#Table(name = "sitoEntity")
public class Sito {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false, updatable = false)
private Long id;
#Column(name = "name")
private String name;
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;
}
#ManyToMany
#JoinTable(name="sito_user",
joinColumns=#JoinColumn(name="sito_id", referencedColumnName="id"),
inverseJoinColumns=#JoinColumn(name="user_id", referencedColumnName="id"))
private List<User> users_sito;
#Override
public String toString() {
return "Sito{" +
"id=" + id +
", name='" + name+
", users='" + users_sito.toString()+
'}';
}
}
When i try compiling with maven i get the following error about mappedBY, as if it was written on both side of the relation, but in fact it is written only on one side:
Caused by: org.hibernate.AnnotationException: Illegal use of mappedBy on both sides of the relationship: User.users_cluster
Anyone has any ideaof what am i doing wrong?
Clustor
As far as I can see the Cluster entity is annotated correctly except some kine of naming convention. Instead of
private List<User> users_cluster;
I would recommend using
private List<User> users;
The list contains users so it should be named to reflect that; good naming is the best documentation, (imo).
User
This entity seems to be correctly annotated but the references are wrong as they are self referencing. So the entity should be modified as follows if you want to create a many-to-many relationship between the thre entities:
public class User {
// ...
#ManyToMany(mappedBy="users")
private List<Cluster> clusters;
#ManyToMany(mappedBy="users")
private List<Sito> sitos;
// getters + setters
}
Sito
Here too I made a small modification as follows:
public class Sito {
// ...
#ManyToMany
#JoinTable(name="sito_user",
joinColumns=#JoinColumn(name="sito_id", referencedColumnName="id"),
inverseJoinColumns=#JoinColumn(name="user_id", referencedColumnName="id"))
private List<User> users;
#ManyToMany(mappedBy = "sitos")
private List<Cluster> clusters;
// getters + setters
}
Now your three entities should be related to each other as you desired.

Hibernate Criteria list always return 0 items

Function in my DAO (findByUsername) is always returning 0 rows no matter if I change the entity class, even after removing annotation from the entity there is no exception, just 0 rows. This code is implemented in the spring based app according to some examples I have found.
DAO:
#Repository("userDao")
public class UserDao extends CustomHibernateDaoSupport {
public void save(User user) {
getHibernateTemplate().save(user);
}
public void delete(User user) {
getHibernateTemplate().delete(user);
}
public User findByUsername(String username) throws DataNotFoundException {
Session session = getSession();
Criteria crit = session.createCriteria(User.class);
System.out.println(username);
crit.add(Restrictions.eq("username", username));
crit.setMaxResults(1);
List<User> users = crit.list();
System.out.println(users);
if (users.size() < 1) {
throw new DataNotFoundException();
}
return users.get(0);
}
}
ENTITY:
#Entity
#Table(name = "users")
public class User {
private Integer id;
private String username;
private String password;
private boolean active;
private String activationCode;
private Date createdAt;
private String email;
private Set<Wall> walls = new HashSet<Wall>();
#Id
#GeneratedValue
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "username", unique = true, nullable = false)
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 = "active")
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
#Column(name = "activation_code")
public String getActivationCode() {
return activationCode;
}
public void setActivationCode(String activationCode) {
this.activationCode = activationCode;
}
#Column(name = "created_at", columnDefinition = "DATETIME")
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
#Column(name = "email")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "users_has_walls", joinColumns = {
#JoinColumn(name = "user_id", nullable = false, updatable = false) },
inverseJoinColumns = { #JoinColumn(name = "wall_id",
nullable = false, updatable = false) })
public Set<Wall> getWalls() {
return walls;
}
public void setWalls(Set<Wall> walls) {
this.walls = walls;
}
}
The solution was to change import declaration to
import javax.persistence.Entity;
instead of hibernate.
User entity class was not imported.

Categories