java spring jpa中基于实体从多个表中获取数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42037275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:18:39  来源:igfitidea点击:

Get data from multiple tables based on entities in spring jpa

javaspringspring-bootjpaspring-data-jpa

提问by kittu

I have three entities like below:

我有如下三个实体:

Comments:

评论:

@Entity
@Table(name = "comments")
public class CommentBean implements Serializable {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "commentId")
    private long commentId;

    @Column(name = "topicId")
    private String topicId;
}

Topics:

话题:

@Entity
@Table(name = "topics")
public class TopicBean implements Serializable {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "topicId")
    private String topicId;
    @Column(name = "title")
    private String title;
    @Column(name = "details")
    private String details;
    @Column(name = "username")
    private String username;
    @Column(name = "userImage")
    private String userImage;
    @Column(name = "dayPosted")
    private String dayPosted;
}

Likes:

喜欢:

@Entity
@Table(name = "comment_likes")
public class CommentLikes implements Serializable {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "commentLikes")
    private String commentLikes;

    @Column(name = "commentId")
    private long commentId;
}

I want to get all data from three tables/entities on request:

我想根据要求从三个表/实体中获取所有数据:

@RequestMapping(path = "/get_data_on_login", method = RequestMethod.GET)
public ResponseEntity get_data_on_login()) throws Exception {

}

How do I achieve this? I have seen examples using @query and some examples using searchByAnd...but Its more confusing which approach to follow.

我如何实现这一目标?我已经看到使用@query 的示例和使用的一些示例,searchByAnd...但是遵循哪种方法更令人困惑。

Update:

更新:

Tried using @JoinColumn to map tables to get the data using bean.findAll()however, I am getting this error:

尝试使用@JoinColumn 映射表以获取数据,bean.findAll()但是,我收到此错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1589) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:554) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081) ~[spring-context-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856) ~[spring-context-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.4.3.RELEASE.jar:1.4.3.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761) [spring-boot-1.4.3.RELEASE.jar:1.4.3.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371) [spring-boot-1.4.3.RELEASE.jar:1.4.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-1.4.3.RELEASE.jar:1.4.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1186) [spring-boot-1.4.3.RELEASE.jar:1.4.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1175) [spring-boot-1.4.3.RELEASE.jar:1.4.3.RELEASE]
    at seconds47.Application.main(Application.java:24) [classes/:?]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:882) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) ~[spring-orm-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:373) ~[spring-orm-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:362) ~[spring-orm-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1648) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1585) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    ... 16 more
Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: seconds47.beans.CommentBean column: topicId (should be mapped with insert="false" update="false")
    at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:830) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.mapping.PersistentClass.checkPropertyColumnDuplication(PersistentClass.java:848) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:870) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:605) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.mapping.RootClass.validate(RootClass.java:265) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:329) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:443) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) ~[spring-orm-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:373) ~[spring-orm-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:362) ~[spring-orm-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1648) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1585) ~[spring-beans-4.3.5.RELEASE.jar:4.3.5.RELEASE]
    ... 16 more

Update code:

更新代码:

Topic Bean:

话题豆:

@Entity
@Table(name = "topics")
public class TopicBean implements Serializable {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "topicId")
    private String topicId;
    @Column(name = "title")
    private String title;
    @Column(name = "details")
    private String details;
    @Column(name = "username")
    private String username;
    @Column(name = "userImage")
    private String userImage;
    @Column(name = "dayPosted")
    private String dayPosted;

    @OneToMany(mappedBy="topicBean")
    private List<CommentBean> commentBeans;
}

commentBean:

评论豆:

@Entity
@Table(name = "comments")
public class CommentBean implements Serializable {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "commentId")
    private long commentId;

    @Column(name = "topicId")
    private String topicId;

    @Column(name = "comments")
    private String comments;

    @Column(name = "commentDate")
    private String commentDate;

    @Column(name = "userImage")
    private String userImage;

    @Column(name = "username")
    private String username;

    @ManyToOne
    @JoinColumn(name="topicId")
    private TopicBean topicBean;
}

Repositories:

存储库:

comment Likes Repo:

评论喜欢回购:

@Repository
public interface CommentLikeRepository extends JpaRepository<CommentLikes, Long>{

    CommentLikes findByCommentId(long commentId);
}

comment reply Repo:

评论回复回购:

@Repository
public interface CommentReplyRepository extends JpaRepository<CommentReply, Long> {

    CommentReply findByReplyId(String replyId);

    @Transactional
    Long deleteByReplyId(String replyId);

}

comment Repo:

评论回购:

@Repository
public interface CommentRepository extends JpaRepository<CommentBean, Long>{
    List<CommentBean> findByTopicId(String topicId);
    CommentBean findByCommentId(long commentId);

    @Transactional
    Long deleteByCommentId(long deleteId);
}

Topic Repo:

主题回购:

@Repository
public interface TopicRepository extends JpaRepository<TopicBean, Long> {
    TopicBean findByTopicId(String topicId);

    @Transactional
    Long deleteByTopicId(String topicId);

    List<TopicBean> findByUsername(String username);
}

user info repo:

用户信息回购:

@Repository
public interface UserInfoRepository extends JpaRepository<UserInfo, Long>{

    UserInfo findByUsername(String username);

    UserInfo findRoleByUsername(String username);
}

回答by Minjun Yu

Since your tags include spring-bootand spring-jpa.
I assume you can use spring data repositories

由于您的标签包括spring-bootspring-jpa
我假设您可以使用spring 数据存储库

The entities posted are not associated in any way. Therefore, the entities must be associated in order to retrieve all the data with one repository The modified version of entities look like this:

发布的实体没有任何关联。因此,实体必须关联才能使用一个存储库检索所有数据实体的修改版本如下所示:

comments table

评论表

@Entity
@Table(name = "comments")
public class CommentBean implements Serializable {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "commentId")
    private long commentId;

    @ManyToOne
    @JoinColumn(name="topicId")
    private TopicBean topicBean;

    @OneToMany(mappedBy="commentBean")
    private List<CommentLikes> commentLikesList;
}

topics table

主题表

@Entity
@Table(name = "topics")
public class TopicBean implements Serializable {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "topicId")
    private String topicId;
    @Column(name = "title")
    private String title;
    @Column(name = "details")
    private String details;
    @Column(name = "username")
    private String username;
    @Column(name = "userImage")
    private String userImage;
    @Column(name = "dayPosted")
    private String dayPosted;

    @OneToMany(mappedBy="topicBean")
    private List<CommentBean> commentBeans;
}

comment_likes table

comment_likes 表

@Entity
@Table(name = "comment_likes")
public class CommentLikes implements Serializable {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "commentLikes")
    private String commentLikes;

    @ManyToOne
    @JoinColumn(name="commentId")
    private CommentBean commentBean;
}  

Note that the above rewrite is based on the most sensible guess I can make according to the original entities.

请注意,上述重写是基于我根据原始实体可以做出的最明智的猜测。

Now the three entities are properly associated. You can just use TopicBean repository to retrieve all the TopicBeans and the other two will be retrieved as well.
topicBeanRepo.findAll()

现在这三个实体已正确关联。您可以只使用 TopicBean 存储库来检索所有 TopicBeans,另外两个也将被检索。
topicBeanRepo.findAll()