hibernate many to one annotations - mapping exception - java

I have to tables book and borrow and I want to have in my Borrow class method to get Book. I have something like this:
#Entity
#Table(name="borrow")
public class Borrow {
#Id
#Column(name="ID")
#GeneratedValue
private Long id;
#Column(name="book_id")
private long bookId;
#Column(name="user_id")
private long userId;
#Column(name="borrow_date")
private Date borrowDate;
#Column(name="return_date")
private Date returnDate;
private Book book;
public long getBookId() {
return bookId;
}
public void setBookId(long bookId) {
this.bookId = bookId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "user_id", nullable = false)
#ForeignKey(name = "id")
public Book getBook() {
return this.book;
}
public void setBook(Book book) {
this.book = book;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public Date getBorrowDate() {
return borrowDate;
}
public void setBorrowDate(Date borrowDate) {
this.borrowDate = borrowDate;
}
public Date getReturnDate() {
return returnDate;
}
public void setReturnDate(Date returnDate) {
this.returnDate = returnDate;
}
}
In table book I have id field and I want to join by it. Like book.id = borrow.book_id. I get execption:
Could not determine type for: Book, at table: borrow, for columns: [org.hibernate.mapping.Column(book)]
Book class:
#Entity
#Table(name="book")
public class Book {
#Id
#Column(name="ID")
#GeneratedValue
private Long id;
#Column(name="title")
private String title;
#Column(name="author")
private String author;
#Column(name="isbn")
private String isbn;
#Column(name="year")
private String year;
#Column(name="publisher")
private String publisher;
#Column(name="book_url")
private String bookUrl;
#Column(name="review_url")
private String reviewUrl;
#Column(name="status_id")
private int status;
#Column(name="accepted")
private boolean accepted;
#Column(name="in_library")
private boolean inLibrary;
#Column(name="user_id")
private long userId;
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public boolean isAccepted() {
return accepted;
}
public void setAccepted(boolean accepted) {
this.accepted = accepted;
}
public boolean isInLibrary() {
return inLibrary;
}
public void setInLibrary(boolean inLibrary) {
this.inLibrary = inLibrary;
}
public Book(long l, String string) {
this.title = string;
this.id = l;
}
public Book() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getBookUrl() {
return bookUrl;
}
public void setBookUrl(String bookUrl) {
this.bookUrl = bookUrl;
}
public String getReviewUrl() {
return reviewUrl;
}
public void setReviewUrl(String reviewUrl) {
this.reviewUrl = reviewUrl;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}

The issue is that you're mixing field and property access. Your #Id annotation is on a field, so that's where hibernate is looking for book's annotation. From 2.2.2.2. Access type:
The placement of annotations within a class hierarchy has to be
consistent (either field or on property) to be able to determine the
default access type. It is recommended to stick to one single
annotation placement strategy throughout your whole application.
So either keep your annotations consistent (recommended), or use the methods described in the rest of that section to override the access type for book (e.g. by using the #Access annotation)

Related

org.springframework.orm.jpa.JpaSystemException: Error accessing field by reflection for persistent property

I am using Spring Boot (v 2.4.0) with Hibernate 5.4.24 and, when trying to get some information from my database, I keep getting this error message:
org.springframework.orm.jpa.JpaSystemException: Error accessing field [private int es.uc3m.orders.model.Shoppingcart.usID] by reflection for persistent property [es.uc3m.orders.model.Shoppingcart#usID] : 1; nested exception is org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private int es.uc3m.orders.model.Shoppingcart.usID] by reflection for persistent property [es.uc3m.orders.model.Shoppingcart#usID] : 1
It is kind of weird for me, because it only happens when I try to access the table Shoppingcart, since I can get informatin from the rest of the tables.
I also used the exact same entities with another project but, insetad of using Spring Boot, persistence was made with EntityManagers and it worked perfectly fine.
These are my entities:
Shoppingcart
#Entity
#NamedQuery(name="Shoppingcart.findAll", query="SELECT s FROM Shoppingcart s")
public class Shoppingcart implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int scID;
private int usID;
//bi-directional many-to-many association to Product
#ManyToMany
#JoinTable(
name="sc_has_product"
, joinColumns={
#JoinColumn(name="scID")
}
, inverseJoinColumns={
#JoinColumn(name="productID")
}
)
private List<Product> products;
//bi-directional one-to-one association to User
#OneToOne(mappedBy="shoppingcart")
private User user;
public Shoppingcart() {
}
public int getScID() {
return this.scID;
}
public void setScID(int scID) {
this.scID = scID;
}
public int getusID() {
return this.usID;
}
public void setusID(int usID) {
this.usID = usID;
}
public List<Product> getProducts() {
return this.products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
public boolean isNull() {
return getProducts().isEmpty();
}
User
#Entity
#Table(name="users")
#NamedQuery(name="User.findAll", query="SELECT u FROM User u")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String address;
#Column(name="card_n")
private Long cardN;
private String city;
private String country;
private int cvv;
private String email;
private String exp;
private String name;
private String pass;
private String surname1;
private String surname2;
private String typeOfUser;
#Column(name="zip_code")
private int zipCode;
//bi-directional many-to-one association to Order
#OneToMany(mappedBy="user")
private List<Orders> orders;
//bi-directional many-to-one association to Product
#OneToMany(mappedBy="user")
private List<Product> products;
//bi-directional one-to-one association to Shoppingcart
#OneToOne(cascade=CascadeType.REMOVE)
#JoinColumn(name="ID", referencedColumnName="usID", insertable=false, updatable=false)
private Shoppingcart shoppingcart;
public User() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public Long getCardN() {
return this.cardN;
}
public void setCardN(Long cardN) {
this.cardN = cardN;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return this.country;
}
public void setCountry(String country) {
this.country = country;
}
public int getCvv() {
return this.cvv;
}
public void setCvv(int cvv) {
this.cvv = cvv;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getExp() {
return this.exp;
}
public void setExp(String exp) {
this.exp = exp;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPass() {
return this.pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String getSurname1() {
return this.surname1;
}
public void setSurname1(String surname1) {
this.surname1 = surname1;
}
public String getSurname2() {
return this.surname2;
}
public void setSurname2(String surname2) {
this.surname2 = surname2;
}
public int getZipCode() {
return this.zipCode;
}
public void setZipCode(int zipCode) {
this.zipCode = zipCode;
}
public List<Orders> getOrders() {
return this.orders;
}
public void setOrders(List<Orders> orders) {
this.orders = orders;
}
public Orders addOrder(Orders order) {
getOrders().add(order);
order.setUser(this);
return order;
}
public Orders removeOrder(Orders order) {
getOrders().remove(order);
order.setUser(null);
return order;
}
public List<Product> getProducts() {
return this.products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public Product addProduct(Product product) {
getProducts().add(product);
product.setUser(this);
return product;
}
public Product removeProduct(Product product) {
getProducts().remove(product);
product.setUser(null);
return product;
}
public Shoppingcart getShoppingcart() {
return this.shoppingcart;
}
public void setShoppingcart(Shoppingcart shoppingcart) {
this.shoppingcart = shoppingcart;
}
public String getTypeOfUser() {
return typeOfUser;
}
public void setTypeOfUser(String typeOfUser) {
this.typeOfUser = typeOfUser;
}
}
This is the ShoppingcartDAO class:
public interface ShoppingCartDAO extends CrudRepository<Shoppingcart, Integer> {
#Query("SELECT s FROM Shoppingcart s JOIN User u ON u.id = s.usID AND u.id LIKE :id")
Shoppingcart findByUser(#Param("id") int id);
#Query("SELECT s FROM Shoppingcart s")
List<Shoppingcart> findAllShoppingCart();
}
And, finally, this is my ShoppingcartController class:
#RestController
#CrossOrigin
#EnableAutoConfiguration
public class ShoppingCartController {
#Autowired
ShoppingCartDAO scDAO;
#RequestMapping(value = "sc", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<?> assignShoppingCart(#RequestBody(required = true) Shoppingcart sc) {
try {
scDAO.save(sc);
return new ResponseEntity<Void>(HttpStatus.CREATED);
} catch(Exception e) {
return new ResponseEntity<Void>(HttpStatus.BAD_REQUEST);
}
}
#RequestMapping(value = "sc", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<?> getEveryShoppingCart() {
try {
List<Shoppingcart> sc = scDAO.findAllShoppingCart();
return new ResponseEntity<List<Shoppingcart>>(sc, (sc != null) ? HttpStatus.OK : HttpStatus.NOT_FOUND);
} catch(Exception e) {
System.out.println(e);
return new ResponseEntity<Void>(HttpStatus.BAD_REQUEST);
}
}
}
I am really going nuts as I canĀ“t figure out what is going on with my code, so thank you in advance if you help me.
I finally fixed it. For those of you who are wondering how, I deleted the relationships between tables that I had, ending with:
Shoppingcart:
#Entity
public class Shoppingcart implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int scID;
#Column(name = "usID")
private Integer userID;
public Shoppingcart() {
}
public int getScID() {
return this.scID;
}
public void setScID(int scID) {
this.scID = scID;
}
public Integer getUserID() {
return userID;
}
public void setUserID(Integer userID) {
this.userID = userID;
}
Product:
#Entity
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int productID;
private String category;
private String color;
private String description;
private String estadoProducto;
private String fecha;
private int orderID;
private String photo;
private double price;
private int seller;
private String sexo;
private String state = "Disponible";
private String talla;
private String title;
public Product() {
}
public int getProductID() {
return this.productID;
}
public void setProductID(int productID) {
this.productID = productID;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getColor() {
return this.color;
}
public void setColor(String color) {
this.color = color;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public String getEstadoProducto() {
return this.estadoProducto;
}
public void setEstadoProducto(String estadoProducto) {
this.estadoProducto = estadoProducto;
}
public String getFecha() {
return this.fecha;
}
public void setFecha(String fecha) {
this.fecha = fecha;
}
public String getPhoto() {
return this.photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public double getPrice() {
return this.price;
}
public void setPrice(double price) {
this.price = price;
}
public String getSexo() {
return this.sexo;
}
public void setSexo(String sexo) {
this.sexo = sexo;
}
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
public String getTalla() {
return this.talla;
}
public void setTalla(String talla) {
this.talla = talla;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public int getOrderID() {
return orderID;
}
public void setOrderID(int orderID) {
this.orderID = orderID;
}
public int getSeller() {
return seller;
}
public void setSeller(int seller) {
this.seller = seller;
}
With this, everything worked fine, but don't ask me why, because I don't know it.
Your Getters/Setters are wrongly implemented.
Like :
Actual :
public int getusID() {
return this.usID;
}
Expected :
public int getUsID() {
return this.usID;
}
Same with setter

How to write hibernate insert query if entity name is saved in a variable

In my application I came to a situation where i need to save some data to an entity but the entity name is unknown, and is saved in a variable and entity field and its value are in a list.So i need to pick the entity name from variable and its field and data from list.
Variable is xEntity.
public void saveData(String xEntity,List<Attribute> attributeList) {
// hibernate insert query
}
Some of the entity class are shown below which may come as the xEntity,and attributeList in function saveData().
#Entity
#Table(name = "person")
public class Person implements Serializable {
#Id
#GeneratedValue
#Column(name = "id")
private Integer id;
#Column(name = "emp_id")
private String empId;
#Column(name = "name")
private String name;
#Column(name="dob")
private Date dob;
#Column(name="active")
private Boolean active;
#Column(name="created_on")
private Timestamp createdOn;
public Person() {
}
public Person(Integer id, String empId, String name, Date dob, Boolean active, Timestamp createdOn) {
this.id = id;
this.empId = empId;
this.name = name;
this.dob = dob;
this.active = active;
this.createdOn = createdOn;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public Timestamp getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Timestamp createdOn) {
this.createdOn = createdOn;
}
}
#Entity
#Table(name = "person_address")
public class PersonAddress implements Serializable {
#Id
#GeneratedValue
#Column(name = "id")
private Integer id;
#Column(name = "emp_id")
private String empId;
#Column(name = "house_name")
private String houseName;
#Column(name="post_office")
private String postOffice;
#Column(name="district")
private String district;
#Column(name="state")
private String state;
#Column(name="active")
private Boolean active;
#Column(name="created_on")
private Timestamp createdOn;
public PersonAddress() {
}
public PersonAddress(Integer id, String empId, String houseName, String postOffice, String district, String state, Boolean active, Timestamp createdOn) {
this.id = id;
this.empId = empId;
this.houseName = houseName;
this.postOffice = postOffice;
this.district = district;
this.state = state;
this.active = active;
this.createdOn = createdOn;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
public String getHouseName() {
return houseName;
}
public void setHouseName(String houseName) {
this.houseName = houseName;
}
public String getPostOffice() {
return postOffice;
}
public void setPostOffice(String postOffice) {
this.postOffice = postOffice;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public void setState(String state) {
this.state = state;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public Timestamp getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Timestamp createdOn) {
this.createdOn = createdOn;
}
}
#Entity
#Table(name = "person_qualification")
public class PersonQualification implements Serializable {
#Id
#GeneratedValue
#Column(name = "id")
private Integer id;
#Column(name = "emp_id")
private String empId;
#Column(name = "degree")
private String degree;
#Column(name="grade")
private String grade;
#Column(name="active")
private Boolean active;
#Column(name="created_on")
private Timestamp createdOn;
public PersonQualification() {
}
public PersonQualification(Integer id, String empId, String degree, String grade, Boolean active, Timestamp createdOn) {
this.id = id;
this.empId = empId;
this.degree = degree;
this.grade = grade;
this.active = active;
this.createdOn = createdOn;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
public String getDegree() {
return degree;
}
public void setDegree(String degree) {
this.degree = degree;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public Timestamp getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Timestamp createdOn) {
this.createdOn = createdOn;
}
}
Below are some of the values that may come to attributeList each time.
attributeList = [{"fieldName":"empId","value":"EMP_123"},{"fieldName":"name","value":"Basil"},{"fieldName":"dob","value":"26-11-90"}]
attributeList = [{"fieldName":"empId","value":"EMP_123"},{"fieldName":"houseName","value":"Ellikkal"},{"fieldName":"postOffice","value":"Chengara"},{"fieldName":"district","value":"Alappy"},{"fieldName":"state","value":"Kerala"}]
attributeList = [{"fieldName":"empId","value":"EMP_123"},{"fieldName":"degree","value":"B.Tech"},{"fieldName":"grade","value":"First class"}]
Date value come as string date which should be formatted to type Date.Below is the Attribute class.
public class Attribute implements Serializable {
private String fieldName;
private String value;
public Attribute() {
super();
// TODO Auto-generated constructor stub
}
public Attribute(String fieldName, String value) {
this.fieldName = fieldName;
this.value = value;
}
public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Now can i use hibernate query to save data to each entity?If anyone know please help me.
Though I don't know why you want to do this but if you have no other choice then you have to use reflection here.
First create instance using your class name. It should be full class name. Also your classes should have default constructor.
Class<?> clazz = Class.forName(className);
Constructor<?> ctor = clazz.getConstructor();
Object object = ctor.newInstance();
Now use reflection to set the values of fields. Lets assume your field name is stored in fieldName and value is stored in fieldValue
declaredField = object.getClass().getDeclaredField(fieldName);
declaredField.setAccessible(true);
declaredField.set(object, fieldValue);
For the cases where you need to convert the type from String to Date etc. You have to get field type and convert accordingly. Field type can be found out by:
declaredField.getFieldType();
Now save this object using hibernate.
sessionFactory.getCurrentSession().save(object);
I'm afraid HQL doesn't support inserting per query but you can use reflection to build your entities or create a native query.

EclipseLink ADD CONSTRAINT Exception

I would like to use create-or-extend-tables but eclipselink gives below error after tables were created. I am using Eclipselink 2.5.2 and db is MS Sql 2014
Exception [EclipseLink-4002] (Eclipse Persistence Services -
2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException Internal
Exception: com.microsoft.sqlserver.jdbc.SQLServerException:
'announcementCOMPANY_ID' object already exists. Error Code: 2714 Call:
ALTER TABLE announcement ADD CONSTRAINT announcementCOMPANY_ID FOREIGN
KEY (COMPANY_ID) REFERENCES company (ID) Query:
DataModifyQuery(sql="ALTER TABLE announcement ADD CONSTRAINT
announcementCOMPANY_ID FOREIGN KEY (COMPANY_ID) REFERENCES company
(ID)")
Persistance.java
persistenceMap.put("javax.persistence.jdbc.driver", ConfigParams
.getInstance().getValue(ConfigConstants.JDBC_DRIVER));
persistenceMap.put("javax.persistence.jdbc.user", ConfigParams
.getInstance().getValue(ConfigConstants.JDBC_USER));
persistenceMap.put("javax.persistence.jdbc.password", ConfigParams
.getInstance().getValue(ConfigConstants.JDBC_PASSWORD));
persistenceMap.put("javax.persistence.jdbc.url", ConfigParams
.getInstance().getValue(ConfigConstants.JDBC_URL));
persistenceMap.put("eclipselink.logging.logger",
Log4jSessionLog.class.getName());
// persistenceMap.put("eclipselink.logging.file",
// Log4jSessionLog.class.getName());
persistenceMap
.put("eclipselink.ddl-generation.output-mode", "database");
persistenceMap.put("eclipselink.weaving.internal", "false");
persistenceMap.put("eclipselink.logging.level", ConfigParams
.getInstance().getValue(ConfigConstants.JDBC_LOGGING_LEVEL));
persistenceMap.put("eclipselink.ddl-generation",
"create-or-extend-tables");
Announcement.java
#Entity
#Table(name="announcement")
public class Announcement {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "annId")
private int id;
#Column(nullable =false, length = 250, name="annName")
private String name;
#Column(length = 250)
private String mainTitle;
#Column(nullable=false, length = 250)
private String subTitle;
#Lob
private String content;
#Column(nullable = false)
private Date startDate;
#Transient
private java.util.Date startDateUtil;
#Column(nullable = false)
private Date endDate;
#Transient
private java.util.Date endDateUtil;
#Lob
private String imgUrl;
#Column(nullable = false)
private boolean isActive;
#Column(nullable = false)
private boolean isDeleted;
#Transient
private BtcResponse status;
private Type type;
#ManyToMany
#JoinTable(name="announcementLogs")
private List<Log> logAList = new ArrayList<Log>();
private Company company;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMainTitle() {
return mainTitle;
}
public void setMainTitle(String mainTitle) {
this.mainTitle = mainTitle;
}
public String getSubTitle() {
return subTitle;
}
public void setSubTitle(String subTitle) {
this.subTitle = subTitle;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public java.util.Date getStartDateUtil() {
return startDateUtil;
}
public void setStartDateUtil(java.util.Date startDateUtil) {
this.startDateUtil = startDateUtil;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public java.util.Date getEndDateUtil() {
return endDateUtil;
}
public void setEndDateUtil(java.util.Date endDateUtil) {
this.endDateUtil = endDateUtil;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public boolean isActive() {
return isActive;
}
public void setActive(boolean isActive) {
this.isActive = isActive;
}
public boolean isDeleted() {
return isDeleted;
}
public void setDeleted(boolean isDeleted) {
this.isDeleted = isDeleted;
}
public BtcResponse getStatus() {
return status;
}
public void setStatus(BtcResponse status) {
this.status = status;
}
public List<Log> getLogAList() {
return logAList;
}
public void setLogAList(List<Log> logAList) {
this.logAList = logAList;
}
#ManyToOne
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public Announcement() {
super();
}
public Announcement(BtcResponse status) {
super();
this.status = status;
}
public Announcement(java.util.Date startDateUtil,
java.util.Date endDateUtil, String imgUrl, boolean isActive) {
super();
this.startDateUtil = startDateUtil;
this.endDateUtil = endDateUtil;
this.imgUrl = imgUrl;
this.isActive = isActive;
}
#ManyToOne
#JoinColumn(name = "id")
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
}
Company.java
#Entity
#Table(name="company")
public class Company {
#Id
#Column(nullable = false)
private int id;
#Column(length = 100, nullable = false, name="companyName")
private String name;
private List<Banner> bannerList = new ArrayList<Banner>();
private List<Announcement> announcementList = new ArrayList<Announcement>();
private List<PriceList> priceList = new ArrayList<PriceList>();
#OneToMany(mappedBy="company")
public List<Announcement> getAnnouncementList() {
return announcementList;
}
public void setAnnouncementList(List<Announcement> announcementList) {
this.announcementList = announcementList;
}
#Transient
private BtcResponse status;
public int getId() {
return id;
}
public Company(int id, String name) {
super();
this.id = id;
this.name = name;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#OneToMany(mappedBy="company")
public List<Banner> getBannerList() {
return bannerList;
}
public void setBannerList(List<Banner> bannerList) {
this.bannerList = bannerList;
}
public BtcResponse getStatus() {
return status;
}
public void setStatus(BtcResponse status) {
this.status = status;
}
public Company() {
super();
}
public Company(BtcResponse status) {
super();
this.status = status;
}
#OneToMany(mappedBy="company")
public List<PriceList> getPriceList() {
return priceList;
}
public void setPriceList(List<PriceList> priceList) {
this.priceList = priceList;
}
}

Hibernate Automatically load relationships

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;

hibernate gives two rows the same instead of two distinct rows

I have a user dao
#Entity
#Table(name="EBIGUSERTIM")
public class EbigUser {
private String id;
private Integer source;
private String entryscheme;
private String fullName;
private String email;
private Long flags;
private String status;
private String createdBy;
private Date createdStamp;
private String modifiedBy;
private Date modifiedStamp;
#Id
#Column(name="ID")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Id
#Column(name="SOURCE")
public Integer getSource() {
return source;
}
public void setSource(Integer source) {
this.source = source;
}
#Column(name="ENTRYSCHEME")
public String getEntryscheme() {
return entryscheme;
}
public void setEntryscheme(String entryscheme) {
this.entryscheme = entryscheme;
}
#Column(name="FULLNAME")
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
#Column(name="EMAIL")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name="FLAGS")
public Long getFlags() {
return flags;
}
public void setFlags(Long flags) {
this.flags = flags;
}
#Column(name="STATUS")
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Column(name="CREATEDBY")
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
#Column(name="CREATEDSTAMP")
public Date getCreatedStamp() {
return createdStamp;
}
public void setCreatedStamp(Date createdStamp) {
this.createdStamp = createdStamp;
}
#Column(name="MODIFIEDBY")
public String getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(String modifiedBy) {
this.modifiedBy = modifiedBy;
}
#Column(name="MODIFIEDSTAMP")
public Date getModifiedStamp() {
return modifiedStamp;
}
public void setModifiedStamp(Date modifiedStamp) {
this.modifiedStamp = modifiedStamp;
}
i am selecting 2 rows out of the db. The sql works
select * from ebigusertim where id='blah'
It returns 2 distinct rows. When i query the data using hibernate, it appears that the object memory is not being allocated for each entry in the list. Thus, i get 2 entries in the list with the same object.
Criteria userCriteria = session.createCriteria(EbigUser.class);
userCriteria.add(Restrictions.eq("id", id));
userlist = userCriteria.list();
Why are you defining two id columns(both id and source are mapped with annotation #Id)?
#Id
#Column(name="ID")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Id
#Column(name="SOURCE")
public Integer getSource() {
return source;
}
Please remove one if it is by mistake. If both together make composite key, map them accordingly e.g.
#Embeddable
public class UserPK implements Serializable {
#Column(name = "ID", nullable = false)
private String id;
#Column(name = "SOURCE", nullable = false)
private Integer source;
.....
.....
}
Use this new class in you original class as Id as below:
#EmbeddedId
private UserPK userPK;
Hope this helps.

Categories