2012-06-05 2 views
0

У меня есть таблица почт и Post_ImageJPA - получить коллекцию из ManyToOne отношений

@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 + " ]"; 
    } 

} 

и

@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 + " ]"; 
    } 

} 

я хочу, чтобы получить коллекцию изображений для конкретной должности, как Collection objPostImage = objPost.getPostImageCollection() , но многие отношения друг с другом не обеспечивают эту функциональность для меня, как я могу преобразовать ее в одну для многих или как я могу получить Image Collection для публикации.? Я новичок в Java, так что любая помощь и предложения будут оценены Thanx заранее ...

ответ

0

Вы можете добавить java.util.Set из PostImages в сообщении вашего объекта и использовать отображение гибернации, чтобы обеспечить связь , This site имеет отличный пример настройки отношений от одного до многих.

Так, например, вы хотите добавить что-то вроде следующее сообщение вашего класса:

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; 
} 

Тогда в классе PostImage, добавьте ссылку на сообщение объекта:

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; 
} 

После этого вы сможете вызвать метод getPostImages() для объекта Post.

+0

Я использую ссылку eclipse, будет ли это работать с этим? – Jitendra

+0

Не работает Я получил эту ошибку Внутреннее исключение: Исключение [EclipseLink-7244] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.ValidationException Исключение Описание: встречается несовместимое сопоставление между [class entity.Post] и [class entity.PostImage]. Обычно это происходит, когда мощность отображения не соответствует мощности его обратного указателя. – Jitendra

0

Попробуйте это:

@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; 

    //.... 
} 

Причина, почему ответ Сета не работает, потому что EclipseLink использует поля для доступа к данным сохраняемости. (Hibernate использует свойства IIRC.) Вы можете указать для каждого класса, как поставщик JPA должен получить доступ к этим данным. также используются

@Entity 
@Access(AccessType.PROPERTY) 
public class SomeEntity 
{ 
    private Long id; 

    //.... 

    @Id 
    public Long getId() 
    { 
     return id; 
    } 
} 

Однако при использовании @Access(AccessType.PROPERTY) полей (по крайней мере, в EclipseLink) так что-то, как это возможно::

Использование полей:

@Entity 
@Access(AccessType.FIELD) 
public class SomeEntity 
{ 
    @Id 
    private Long id; 

    //.... 
} 

Используя свойства

@Entity 
@Access(AccessType.PROPERTY) 
public class SomeEntity 
{ 
    private Long id; 

    @Column(name = "text") 
    private String someText; 

    //.... 

    @Id 
    public Long getId() 
    { 
     return id; 
    } 
}