Spring Boot和Thymeleaf:连接的实体对象返回为null

时间:2017-07-18 15:28:21

标签: java spring hibernate jpa thymeleaf

我正在使用带有Hibernate和JPA的Spring Boot框架,以及用于view元素的Thymeleaf。我想在页面上的同一个HTML表格中显示来自2个不同实体的相关数据。但是,应该包含来自我的连接实体的数据的对象返回null。

编辑:问题的根本原因是正在执行的查询是在2个主键上而不是在我的MsgOrig表的主键和外键上连接我的两个表我的ReplyMessage表(" msgOrigID")按预期方式。知道怎么纠正这个吗?

另外,为了让这个工作,我试图返回所有消息。但是我的最终目标是仅返回登录用户发送的消息。是否有可用于此目的的JPA存储库方法?或者我应该编写自定义查询吗?

MsgOrig的实体类:

@Entity
@Table(name = "messageoriginator")
public class MsgOrig {

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

@Column(name = "Date")
private String date;    

@Column(name = "MsgTime")
private String msgTime;

@Column(name = "message")
private String msg;

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

@OneToOne(cascade = CascadeType.ALL) 
@JoinColumn(name = "msgOrigID")  
private ReplyMessage reply;

//getters and setters
}

ReplyMessage的实体类:

@Entity
@Table(name = "replymessage")
public class ReplyMessage {

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

@Column(name = "msgOrigID")
private int msgOrigId;

@Column(name = "Date")
private String date;    

@Column(name = "MsgTime")
private String msgTime;

@Column(name = "message")
private String msg;

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

@OneToOne(mappedBy="reply")
private MsgOrig msgOrig; 

//getters and setters
}

控制器方法:

    @RequestMapping(value={"/mymessages"}, method = RequestMethod.GET)
public ModelAndView messages(){
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("mymessages", messageService.listAllMessages());
    return modelAndView;
}

MessageService接口的实现类:

@Service("messageService")
public class MessageServiceImpl implements MessageService{

@Autowired
private MessageRepository messageRepository;    

@Override
public List<MsgOrig> listAllMessages() {
    return messageRepository.findAll();
}
}

存储库类:

@Repository("messageRepository")
public interface MessageRepository extends JpaRepository<MsgOrig, Integer> {

@Query("SELECT t.email FROM MsgOrig t where t.id = :id") 
String findUsersEmail(@Param("id") int id);
}

关于Thymeleaf模板的相关部分(返回&#34;未找到&#34;):

<td th:text="${mymessages.reply != null ? mymessages.reply.msgTime : 'NOT FOUND'}"/>

0 个答案:

没有答案