Detached entity passed to persist: JPA OneToMany relations - java

I'm trying to set up save entity with children together, but I can't find how it is works, I tried to do like in all tutorials but always had a error detached entity passed to persist
this is my entities:
#Entity
#Table(name = "CurriculumVitaes")
public class CurriculumVitae {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotBlank
private String title;
private String summary;
#OneToMany(mappedBy = "curriculumVitae", targetEntity = Education.class, cascade={CascadeType.ALL})
private List<Education> educations = new ArrayList<>();
public CurriculumVitae(){}
public CurriculumVitae(Long id, String title, String summary){
this.id = id;
this.title = title;
this.summary = summary;
}
public void addEducation(Education education) {
if(this.educations.contains(education)){
return;
}
this.educations.add(education);
education.setCurriculumVitae(this);
}
public void removeEducation(Education education){
if(this.educations.contains(education)){
return;
}
this.educations.remove(education);
education.setCurriculumVitae(null);
}
public boolean equals(Object object) {
if (object == this)
return true;
if ((object == null) || !(object instanceof CurriculumVitae))
return false;
final CurriculumVitae a = (CurriculumVitae)object;
if (id != null && a.getId() != null) {
return id.equals(a.getId());
}
return false;
}
}
and child entity:
#Entity
#Table(name = "Educations")
public class Education {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotBlank
private String title;
private String areaOfStudy;
private String description;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "curriculumVitaeId", referencedColumnName = "id")
private CurriculumVitae curriculumVitae;
public Education(){}
public Education(String title, String areaOfStudy, String description){
this.title = title;
this.areaOfStudy = areaOfStudy;
this.description = description;
}
public CurriculumVitae getCurriculumVitae() {
return curriculumVitae;
}
public void setCurriculumVitae(CurriculumVitae curriculumVitae) {
//prevent endless loop
if (sameAsFormer(curriculumVitae))
return ;
//set new owner
CurriculumVitae oldOwner = this.curriculumVitae;
this.curriculumVitae = curriculumVitae;
//remove from the old owner
if (oldOwner!=null)
oldOwner.removeEducation(this);
//set myself into new owner
if (curriculumVitae!=null)
curriculumVitae.addEducation(this);
}
private boolean sameAsFormer(CurriculumVitae newOwner) {
return this.curriculumVitae==null? newOwner == null : this.curriculumVitae.equals(newOwner);
}
public boolean equals(Object object) {
if (object == this)
return true;
if ((object == null) || !(object instanceof Education))
return false;
final Education a = (Education)object;
if (id != null && a.getId() != null) {
return id.equals(a.getId());
}
return false;
}
}
How can I set up save entities all together with one repository method save?
without cascade it will not save inner entities.
#PostMapping
public #ResponseBody CurriculumVitaeViewModel addCurriculumVitae(#RequestBody SaveCurriculumVitaeRequest model){
CurriculumVitae newCv = new CurriculumVitae();
curriculumVitaeModelMapper.Map(model, newCv);
for (EducationViewModel ed:model.getEducations()
) {
Education newEd = new Education();
educationModelMapper.Map(ed, newEd);
newCv.addEducation(newEd);
}
CurriculumVitae savedCv = curriculumVitaeRepository.save(newCv);

Related

JPA Updates Part of A Record And Returns No Error

I have a java web application using JPA. My problem seems simple but has stumped me for a day now.
I have two tables in my database, Book and Author.
Both input fields in the view for these tables are in the same form.
What's weird is when I update (mrege()) the edited record the book will update but the author does not. I've debugged and followed the author object as far as netbeans will let me and when I merge() my new book record, only the Book table/object are effected.
The Book is a Many-To-One
The Author is a One-To-Many
Controller
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try {
String action = request.getParameter("action");
if (action != null) {
List<String> values;
try {
values = new ArrayList<>();
switch (action) {
case "save": // Ecompasses Save and Update
Book book = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date;
String bookAuthorID = request.getParameter("authorID");
String bookID = request.getParameter("bookID");
String title = request.getParameter("title");
String userEnteredDate = request.getParameter("datePublished");
Author author = null;
if (bookID.matches("\\d+")) { // Update
book = bookService.find(new Integer(bookID));
book.setTitle(title);
book.setDatePublished(sdf.parse(userEnteredDate));
author = authorService.find(new Integer(bookAuthorID));
author.setAuthorFirstName(request.getParameter("authorFirstName"));
author.setAuthorLastName(request.getParameter("authorLastName"));
book.setAuthorID(author);
bookService.edit(book);
}
}
Author Entity
#Entity
#Table(name = "Author")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Author.findAll", query = "SELECT a FROM Author a"),
#NamedQuery(name = "Author.findByAuthorID", query = "SELECT a FROM Author a WHERE a.authorID = :authorID"),
#NamedQuery(name = "Author.findByAuthorFirstName", query = "SELECT a FROM Author a WHERE a.authorFirstName = :authorFirstName"),
#NamedQuery(name = "Author.findByAuthorLastName", query = "SELECT a FROM Author a WHERE a.authorLastName = :authorLastName")})
public class Author implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "AuthorID")
private Integer authorID;
#Size(max = 50)
#Column(name = "AuthorFirstName")
private String authorFirstName;
#Size(max = 50)
#Column(name = "AuthorLastName")
private String authorLastName;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "authorID")
private Collection<Book> bookCollection;
public Author() {
}
public Author(Integer authorID) {
this.authorID = authorID;
}
public Integer getAuthorID() {
return authorID;
}
public void setAuthorID(Integer authorID) {
this.authorID = authorID;
}
public String getAuthorFirstName() {
return authorFirstName;
}
public void setAuthorFirstName(String authorFirstName) {
this.authorFirstName = authorFirstName;
}
public String getAuthorLastName() {
return authorLastName;
}
public void setAuthorLastName(String authorLastName) {
this.authorLastName = authorLastName;
}
#XmlTransient
public Collection<Book> getBookCollection() {
return bookCollection;
}
public void setBookCollection(Collection<Book> bookCollection) {
this.bookCollection = bookCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (authorID != null ? authorID.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Author)) {
return false;
}
Author other = (Author) object;
if ((this.authorID == null && other.authorID != null) || (this.authorID != null && !this.authorID.equals(other.authorID))) {
return false;
}
return true;
}
#Override
public String toString() {
return "edu.wctc.asp.bookwebapp.bookservice.Author[ authorID=" + authorID + " ]";
}
}
Book Entity
#Entity
#Table(name = "Book")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Book.findAll", query = "SELECT b FROM Book b"),
#NamedQuery(name = "Book.findByBookID", query = "SELECT b FROM Book b WHERE b.bookID = :bookID"),
#NamedQuery(name = "Book.findByTitle", query = "SELECT b FROM Book b WHERE b.title = :title"),
#NamedQuery(name = "Book.findByDatePublished", query = "SELECT b FROM Book b WHERE b.datePublished = :datePublished")})
public class Book implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "BookID")
private Integer bookID;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 50)
#Column(name = "title")
private String title;
#Column(name = "DatePublished")
#Temporal(TemporalType.DATE)
private Date datePublished;
#JoinColumn(name = "AuthorID", referencedColumnName = "AuthorID")
#ManyToOne(optional = false)
private Author authorID;
public Book() {
}
public Book(Integer bookID) {
this.bookID = bookID;
}
public Book(Integer bookID, String title) {
this.bookID = bookID;
this.title = title;
}
public Integer getBookID() {
return bookID;
}
public void setBookID(Integer bookID) {
this.bookID = bookID;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getDatePublished() {
return datePublished;
}
public void setDatePublished(Date datePublished) {
this.datePublished = datePublished;
}
public Author getAuthorID() {
return authorID;
}
public void setAuthorID(Author authorID) {
this.authorID = authorID;
}
#Override
public int hashCode() {
int hash = 0;
hash += (bookID != null ? bookID.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Book)) {
return false;
}
Book other = (Book) object;
if ((this.bookID == null && other.bookID != null) || (this.bookID != null && !this.bookID.equals(other.bookID))) {
return false;
}
return true;
}
#Override
public String toString() {
return "edu.wctc.asp.bookwebapp.bookservice.Book[ bookID=" + bookID + " ]";
}
}
Apply CascadeType.MERGE:
#JoinColumn(name = "AuthorID", referencedColumnName = "AuthorID")
#ManyToOne(optional = false, cascade=CascadeType.MERGE)
private Author authorID;

Error " java.lang.IllegalStateException: During synchronization a new object was found through a relationship that was not marked cascade PERSIST"

this is my first post, so please bear with me if i do make any errors.
I get an error " java.lang.IllegalStateException: During synchronization a new object was found through a relationship that was not marked cascade PERSIST"
whenever i want to query(add,edit,delete) the database.
The tables related are sponsors and donations. There is a one to many relationship between them. Classes below:
Sponsors
#Entity
#Table(name = "SPONSORS")
#NamedQueries({
#NamedQuery(name = "Sponsors.findAll", query = "SELECT s FROM Sponsors s")})
public class Sponsors implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "SPONSORID")
private Short sponsorid;
#Basic(optional = false)
#Column(name = "NAME")
private String name;
#Basic(optional = false)
#Column(name = "SURNAME")
private String surname;
#Basic(optional = false)
#Column(name = "ADDRESS")
private String address;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "sponsorid")
private List<Donations> donationsList;
public Sponsors() {
}
public Sponsors(Short sponsorid) {
this.sponsorid = sponsorid;
}
public Sponsors(Short sponsorid, String name, String surname, String address) {
this.sponsorid = sponsorid;
this.name = name;
this.surname = surname;
this.address = address;
}
public Short getSponsorid() {
return sponsorid;
}
public void setSponsorid(Short sponsorid) {
this.sponsorid = sponsorid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public List<Donations> getDonationsList() {
return donationsList;
}
public void setDonationsList(List<Donations> donationsList) {
this.donationsList = donationsList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (sponsorid != null ? sponsorid.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Sponsors)) {
return false;
}
Sponsors other = (Sponsors) object;
if ((this.sponsorid == null && other.sponsorid != null) || (this.sponsorid != null && !this.sponsorid.equals(other.sponsorid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "Pat.Sponsors[ sponsorid=" + sponsorid + " ]";
}
}
Donations:
#Entity
#Table(name = "DONATIONS")
#NamedQueries({
#NamedQuery(name = "Donations.findAll", query = "SELECT d FROM Donations d")})
public class Donations implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "DONATIONID")
private Short donationid;
#Basic(optional = false)
#Column(name = "DONATIONDATE")
#Temporal(TemporalType.DATE)
private Date donationdate;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Column(name = "DONATIONAMOUNT")
private Double donationamount;
#JoinColumn(name = "SPONSORID", referencedColumnName = "SPONSORID")
#ManyToOne(optional = false)
private Sponsors sponsorid;
public Donations() {
}
public Donations(Short donationid) {
this.donationid = donationid;
}
public Donations(Short donationid, Date donationdate) {
this.donationid = donationid;
this.donationdate = donationdate;
}
public Short getDonationid() {
return donationid;
}
public void setDonationid(Short donationid) {
this.donationid = donationid;
}
public Date getDonationdate() {
return donationdate;
}
public void setDonationdate(Date donationdate) {
this.donationdate = donationdate;
}
public Double getDonationamount() {
return donationamount;
}
public void setDonationamount(Double donationamount) {
this.donationamount = donationamount;
}
public Sponsors getSponsorid() {
return sponsorid;
}
public void setSponsorid(Sponsors sponsorid) {
this.sponsorid = sponsorid;
}
#Override
public int hashCode() {
int hash = 0;
hash += (donationid != null ? donationid.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Donations)) {
return false;
}
Donations other = (Donations) object;
if ((this.donationid == null && other.donationid != null) || (this.donationid != null && !this.donationid.equals(other.donationid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "Pat.Donations[ donationid=" + donationid + " ]";
}
}
The field
#ManyToOne(optional = false)
private Sponsors sponsorid;
in the Donations entity is not configured for cascading. Try changing it to:
#ManuToOne(optional = false, cascade = CascadeType.ALL)
private Sponsors sponsorid;

Joins on composite key using hibernate criteria

I am not getting how to write Hibernate criteria query to achieve the result similar to the result obtained by below SQL query. Please suggest me what are all steps need to be followed to achieve the result.
SELECT PRODUCT.PRODUCTNAME, ITEM.ITEMNAME
FROM PRODUCT_ITEM
JOIN PRODUCT
ON PRODUCT_ITEM.ID = PRODUCT.ID
JOIN ITEM
ON PRODUCT_ITEM.ID = ITEM.ID
Above is my Sql Query to fetch the product_name and item_name. It is working correctly.
I tried get the same result using HIBERNATE CRITERIA QUERY.
Criteria criteria = session.createCriteria(ProductItem.class,"pi");
criteria.createAlias("pi.pk.product", "pip");
criteria.createAlias("pi.pk.item", "pii");
criteria.setProjection(Projections.projectionList().add(Projections.property("pip.id")).add(Projections.property("pii.id")));
List<Object[]> list = criteria.list();
i am getting error saying
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not execute query
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.loader.Loader.doList(Loader.java:2147)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2028)
at org.hibernate.loader.Loader.list(Loader.java:2023)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:95)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1569)
at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:283)
at checkComposite.main(checkComposite.java:38)
Caused by: org.postgresql.util.PSQLException: ERROR: missing FROM-clause entry for table "pip1_"
Position: 8
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2198)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1927)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:561)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:419)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:304)
at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:186)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1668)
at org.hibernate.loader.Loader.doQuery(Loader.java:662)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:224)
at org.hibernate.loader.Loader.doList(Loader.java:2144)
Here my ENTITYS are as below.
#Entity
#Table(name = "item")
public class Item {
private Integer id;
private String name;
private List<ProductItem> productItems = new LinkedList<ProductItem>();
public Item() {
}
#Id
#GenericGenerator(name = "generator", strategy = "increment")
#GeneratedValue(generator = "generator")
#Column(name = "item_id", nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "name")
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.item")
public List<ProductItem> getProductItems() {
return this.productItems;
}
public void setProductItems(List<ProductItem> productItems) {
this.productItems = productItems;
}
}
Product Entity
#Entity
#Table(name = "product")
public class Product {
private Integer id;
private String name;
private List<ProductItem> productItems = new LinkedList<ProductItem>();
public Product() {
}
#Id
#GenericGenerator(name = "generator", strategy = "increment")
#GeneratedValue(generator = "generator")
#Column(name = "product_id", nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "name")
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.product")
public List<ProductItem> getProductItems() {
return this.productItems;
}
public void setProductItems(List<ProductItem> productItems) {
this.productItems = productItems;
}
}
PRODUCT_ITEM entity.
#Entity
#Table(name = "product_item")
#AssociationOverrides({
#AssociationOverride(name = "pk.item", joinColumns = #JoinColumn(name = "item_id")),
#AssociationOverride(name = "pk.product", joinColumns = #JoinColumn(name = "product_id"))
})
public class ProductItem {
private ProductItemPk pk = new ProductItemPk();
#EmbeddedId
private ProductItemPk getPk() {
return pk;
}
private void setPk(ProductItemPk pk) {
this.pk = pk;
}
#Transient
public Item getItem() {
return getPk().getItem();
}
public void setItem(Item item) {
getPk().setItem(item);
}
#Transient
public Product getProduct() {
return getPk().getProduct();
}
public void setProduct(Product product) {
getPk().setProduct(product);
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ProductItem that = (ProductItem) o;
if (getPk() != null ? !getPk().equals(that.getPk()) : that.getPk() != null) return false;
return true;
}
public int hashCode() {
return (getPk() != null ? getPk().hashCode() : 0);
}
}
Embedable Class is as below.
#Embeddable
public class ProductItemPk implements Serializable {
private Item item;
private Product product;
#ManyToOne
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
#ManyToOne
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ProductItemPk that = (ProductItemPk) o;
if (item != null ? !item.equals(that.item) : that.item != null) return false;
if (product != null ? !product.equals(that.product) : that.product != null)
return false;
return true;
}
public int hashCode() {
int result;
result = (item != null ? item.hashCode() : 0);
result = 31 * result + (product != null ? product.hashCode() : 0);
return result;
}
}
Try changing the query to:
Criteria criteria = session.createCriteria(ProductItem.class,"pi");
criteria.createAlias("pi.pk", "pipk");
criteria.createAlias("pipk.product", "pip");
criteria.createAlias("pipk.item", "pii");
criteria.setProjection(Projections.projectionList().add(Projections.property("pip.id")).add(Projections.property("pii.id")));
List<Object[]> list = criteria.list();

JPA - Get collection from ManyToOne relationship

I have a table Post and Post_Image
#Entity
#Table(name = "post")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Post.findAll", query = "SELECT p FROM Post p"),
#NamedQuery(name = "Post.findByPostId", query = "SELECT p FROM Post p WHERE p.postId = :postId"),
#NamedQuery(name = "Post.findByTitle", query = "SELECT p FROM Post p WHERE p.title = :title"),
#NamedQuery(name = "Post.findByCreatedDatetime", query = "SELECT p FROM Post p WHERE p.createdDatetime = :createdDatetime")})
public class Post implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#NotNull
#Column(name = "post_id")
private Integer postId;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 500)
#Column(name = "title")
private String title;
#Basic(optional = false)
#NotNull
#Lob
#Size(min = 1, max = 65535)
#Column(name = "content")
private String content;
#Column(name = "created_datetime")
#Temporal(TemporalType.TIMESTAMP)
private Date createdDatetime;
#JoinColumn(name = "user_id", referencedColumnName = "user_id")
#ManyToOne(optional = false)
private User userId;
#JoinColumn(name = "post_type_id", referencedColumnName = "post_type_id")
#ManyToOne(optional = false)
private PostType postTypeId;
public Post() {
Date date = new Date();
this.createdDatetime =new Date(date.getTime());
}
public Post(Integer postId) {
this.postId = postId;
}
public Post(Integer postId, String title, String content) {
this.postId = postId;
this.title = title;
this.content = content;
}
public Integer getPostId() {
return postId;
}
public void setPostId(Integer postId) {
this.postId = postId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getCreatedDatetime() {
return createdDatetime;
}
public void setCreatedDatetime(Date createdDatetime) {
this.createdDatetime = createdDatetime;
}
public User getUserId() {
return userId;
}
public void setUserId(User userId) {
this.userId = userId;
}
public PostType getPostTypeId() {
return postTypeId;
}
public void setPostTypeId(PostType postTypeId) {
this.postTypeId = postTypeId;
}
#Override
public int hashCode() {
int hash = 0;
hash += (postId != null ? postId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Post)) {
return false;
}
Post other = (Post) object;
if ((this.postId == null && other.postId != null) || (this.postId != null && !this.postId.equals(other.postId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entity.Post[ postId=" + postId + " ]";
}
}
and
#Entity
#Table(name = "post_image")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "PostImage.findAll", query = "SELECT p FROM PostImage p"),
#NamedQuery(name = "PostImage.findByPostImageId", query = "SELECT p FROM PostImage p WHERE p.postImageId = :postImageId"),
#NamedQuery(name = "PostImage.findByPath", query = "SELECT p FROM PostImage p WHERE p.path = :path"),
#NamedQuery(name = "PostImage.findByTitle", query = "SELECT p FROM PostImage p WHERE p.title = :title")})
public class PostImage implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "post_image_id")
private Integer postImageId;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 500)
#Column(name = "path")
private String path;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 500)
#Column(name = "title")
private String title;
#JoinColumn(name = "post_id", referencedColumnName = "post_id")
#ManyToOne(optional = false)
private Post postId;
public PostImage() {
}
public PostImage(Integer postImageId) {
this.postImageId = postImageId;
}
public PostImage(Integer postImageId, String path, String title) {
this.postImageId = postImageId;
this.path = path;
this.title = title;
}
public Integer getPostImageId() {
return postImageId;
}
public void setPostImageId(Integer postImageId) {
this.postImageId = postImageId;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Post getPostId() {
return postId;
}
public void setPostId(Post postId) {
this.postId = postId;
}
#Override
public int hashCode() {
int hash = 0;
hash += (postImageId != null ? postImageId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof PostImage)) {
return false;
}
PostImage other = (PostImage) object;
if ((this.postImageId == null && other.postImageId != null) || (this.postImageId != null && !this.postImageId.equals(other.postImageId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entity.PostImage[ postImageId=" + postImageId + " ]";
}
}
i want to get collection of images for particular post like
Collection objPostImage = objPost.getPostImageCollection()
but manytoone relationship do not provide this functionality to me how can i convert it to one to many or how can i get Image Collection for a post.?
I am new to java so any help and suggestion will be appreciated
thanx in advance...
You can add a java.util.Set of PostImages in your Post object, and use the Hibernate mapping to provide the relationship. This site has a great example of setting up One to Many relationships.
So, for example, you would want to add something like the following to your Post class:
private Set<PostImage> postImages = new HashSet<PostImage>();
#OneToMany(fetch = FetchType.LAZY, mappedBy = "post")
public Set<PostImage> getPostImages() {
return this.postImages;
}
public void setPostImages(Set<PostImage> postImages) {
this.postImages= postImages;
}
Then, in your PostImage class, add a reference to a Post object:
private Post post;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "POST_ID", nullable = false)
public Stock getPost() {
return this.post;
}
public void setPost(Post post) {
this.post= post;
}
After adding that, you will be able to call the getPostImages() method on your Post object.
Try this:
#Entity
#Table(name = "post")
public class Post
{
//....
#OneToMany(mappedBy = "post")
private Set<PostImage> images;
//....
}
#Entity
#Table(name = "post_image")
public class PostImage
{
//....
#JoinColumn(name = "post_id", referencedColumnName = "id")
#ManyToOne(optional = false)
private Post post;
//....
}
The reason why Seth's answer didn't work is because EclipseLink uses fields to access persistence data. (Hibernate uses properties IIRC.) You can specify per class how a JPA provider should access this data.
Using fields:
#Entity
#Access(AccessType.FIELD)
public class SomeEntity
{
#Id
private Long id;
//....
}
Using properties:
#Entity
#Access(AccessType.PROPERTY)
public class SomeEntity
{
private Long id;
//....
#Id
public Long getId()
{
return id;
}
}
However when using #Access(AccessType.PROPERTY) fields are also used (at least in EclipseLink) so something like this is possible:
#Entity
#Access(AccessType.PROPERTY)
public class SomeEntity
{
private Long id;
#Column(name = "text")
private String someText;
//....
#Id
public Long getId()
{
return id;
}
}

How to get save() on my model in java?

Netbeans was kind enough to generate this class for me. But I'm wondering how I save data to the database?
I would think it would be like....
Content $content = new Content();
$content->setName();
$content->save();
But I don't see any save functionality or anything that hints that this content can be saved. I could write queries and such to do so, but with the annotations it created it seems like it has support already built in.
#Entity
#Table(name = "content")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Content.findAll", query = "SELECT c FROM Content c"),
#NamedQuery(name = "Content.findById", query = "SELECT c FROM Content c WHERE c.id = :id"),
#NamedQuery(name = "Content.findByUserId", query = "SELECT c FROM Content c WHERE c.userId = :userId")})
public class Content implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#NotNull
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Column(name = "user_id")
private int userId;
#Basic(optional = false)
#NotNull
#Lob
#Size(min = 1, max = 65535)
#Column(name = "body")
private String body;
public Content() {
}
public Content(Integer id) {
this.id = id;
}
public Content(Integer id, int userId, String body) {
this.id = id;
this.userId = userId;
this.body = body;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Content)) {
return false;
}
Content other = (Content) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "model.Content[ id=" + id + " ]";
}
}

Categories

Resources