2017-02-04 16 views
2

у меня есть три сущности, как показано ниже:Получить данные из нескольких таблиц, основанных на юридических лиц в весеннем JPA

Комментарии:

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

Темы:

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

Я хочу получить все данные от t по таблицам/объектам по запросу:

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

} 

Как это достичь? Я видел примеры, использующие @query и некоторые примеры, используя searchByAnd..., но его более запутанный подход.

Update:

Пробовал с помощью @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$1.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 

Обновить код:

Тема Bean:

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

Хранилища:

комментарий Нравится Repo:

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

    CommentLikes findByCommentId(long commentId); 
} 

комментарий ответить Repo:

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

    CommentReply findByReplyId(String replyId); 

    @Transactional 
    Long deleteByReplyId(String replyId); 

} 

комментарий Repo:

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

    @Transactional 
    Long deleteByCommentId(long deleteId); 
} 

Тема Repo:

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

    @Transactional 
    Long deleteByTopicId(String topicId); 

    List<TopicBean> findByUsername(String username); 
} 

информация пользователя репо:

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

    UserInfo findByUsername(String username); 

    UserInfo findRoleByUsername(String username); 
} 

ответ

3

Поскольку ваши метки включают пружинных ботинки и весну-JPA.
Я предполагаю, что вы можете использовать пружинных хранилища данных

Субъекты размещен не связаны каким-либо образом.Таким образом, объекты должны быть связаны с тем, чтобы восстановить все данные с одного репозитория Модифицированная версия сущностей выглядеть следующим образом:

комментарии таблица

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

темы таблица

@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 таблица

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

Обратите внимание, что t он выше переписывания основан на самом разумном предположении, которое я могу сделать в соответствии с исходными сущностями.

Теперь три объекта правильно связаны. Вы можете просто использовать репозиторий TopicBean для извлечения всех объектов TopicBeans, а остальные два будут восстановлены.
topicBeanRepo.findAll()

+0

Не ясно ....... – kittu

+0

Это только одно возможное решение. В вашем вопросе не говорится, что желателен только один репозиторий, и нет репозитория ваших сообщений, поэтому, я думаю, вам нужен рабочий пример. Из опубликованных вами столов нет способа сделать это только с одним репозиторием, потому что эти таблицы никоим образом не связаны. –

+0

Я могу помочь вам реструктурировать ваши таблицы/сущности, но, пожалуйста, перефразируйте или обновите свой вопрос. –