#Spring Bootでメッセージアプリケーション
メッセージアプリケーションをSpring Bootで作っていますが
メッセージを送信した後にうまくDBに情報が保存されません。
どの部分に問題があるのかお分かりの方がいたらアドバイスをいただきたいです。
以下のように実行をしてみましたが、発行されたSQL文は
sql
1select message0_.message_id as message_1_4_, message0_.message_content as message_2_4_, message0_.message_time as message_3_4_, message0_.receiver_user_id as receiver4_4_, message0_.sender_user_id as sender_u5_4_ from message message0_ left outer join user user1_ on message0_.receiver_user_id=user1_.user_id where user1_.user_id=? 2
のようにselect文のみになっています。
本来はメッセージテーブルに送信した情報を保存したいです。
おそらくは@ManyToOneにおけるDBへの保存方法に問題があると思うのですが
具体的にどの部分に問題があるのかが見当がつきません。
何かアドバイスをいただけると幸いです。
使用環境
SpringBoot 2.2.4.
mysql 8.0.18
##insert文
java
1@Repository 2@Transactional 3public interface MessageReposioty extends JpaRepository<Message, Long>{ 4 List<Message> findBySenderUser_UserId(int userId); 5 List<Message> findByReceiverUser_UserId(int userId); 6 7 @Modifying 8 @Query(value = "insert into message (sender_user_id,receiver_user_id,message_content) " 9 + "VALUES (:senderUserId,:receiverUserId,:messageContent)", nativeQuery = true) 10 @Transactional 11 void sendMessage(@Param("senderUserId") int senderUserId, @Param("receiverUserId") int receiverUserId, 12 @Param("messageContent") String messageContent); 13}
##Entity
java
1@Entity 2@Transactional 3@NamedQuery(name="User.findAll", query="SELECT u FROM User u") 4public class User implements Serializable { 5 private static final long serialVersionUID = 1L; 6 7 @Id 8 @Column(name="user_id") 9 private int userId; 10 11 12 //bi-directional many-to-one association to Message 13 @OneToMany(mappedBy="senderUser") 14 private List<Message> messages1; 15 16 //bi-directional many-to-one association to Message 17 @OneToMany(mappedBy="receiverUser") 18 private List<Message> messages2; 19 20 public User() { 21 } 22 23 public int getUserId() { 24 return this.userId; 25 } 26 27 public void setUserId(int userId) { 28 this.userId = userId; 29 } 30 31 32 public List<Message> getMessages1() { 33 return this.messages1; 34 } 35 36 public void setMessages1(List<Message> messages1) { 37 this.messages1 = messages1; 38 } 39 40 public Message addMessages1(Message messages1) { 41 getMessages1().add(messages1); 42 messages1.setSenderUser(this); 43 44 return messages1; 45 } 46 47 public Message removeMessages1(Message messages1) { 48 getMessages1().remove(messages1); 49 messages1.setSenderUser(null); 50 51 return messages1; 52 } 53 54 public List<Message> getMessages2() { 55 return this.messages2; 56 } 57 58 public void setMessages2(List<Message> messages2) { 59 this.messages2 = messages2; 60 } 61 62 public Message addMessages2(Message messages2) { 63 getMessages2().add(messages2); 64 messages2.setReceiverUser(this); 65 66 return messages2; 67 } 68 69 public Message removeMessages2(Message messages2) { 70 getMessages2().remove(messages2); 71 messages2.setReceiverUser(null); 72 73 return messages2; 74 } 75 76 77}
java
1@Entity 2@NamedQuery(name="Message.findAll", query="SELECT m FROM Message m") 3public class Message implements Serializable { 4 private static final long serialVersionUID = 1L; 5 6 @Id 7 @GeneratedValue(strategy=GenerationType.IDENTITY) 8 @Column(name="message_id") 9 private long messageId; 10 11 @Column(name="message_content") 12 private String messageContent; 13 14 @Temporal(TemporalType.TIMESTAMP) 15 @Column(name="message_time") 16 private Date messageTime; 17 18 //送信者 19 @ManyToOne 20 @JoinColumn(name="sender_user_id") 21 private User senderUser; 22 23 //受信者 24 @ManyToOne 25 @JoinColumn(name="receiver_user_id") 26 private User receiverUser; 27 28 public Message() { 29 } 30 31 public long getMessageId() { 32 return this.messageId; 33 } 34 35 public void setMessageId(long messageId) { 36 this.messageId = messageId; 37 } 38 39 public String getMessageContent() { 40 return this.messageContent; 41 } 42 43 public void setMessageContent(String messageContent) { 44 this.messageContent = messageContent; 45 } 46 47 public Date getMessageTime() { 48 return this.messageTime; 49 } 50 51 public void setMessageTime(Date messageTime) { 52 this.messageTime = messageTime; 53 } 54 55 public User getSenderUser() { 56 return senderUser; 57 } 58 59 public void setSenderUser(User senderUser) { 60 this.senderUser = senderUser; 61 } 62 63 public User getReceiverUser() { 64 return receiverUser; 65 } 66 67 public void setReceiverUser(User receiverUser) { 68 this.receiverUser = receiverUser; 69 } 70
##controller
java
1@Controller 2@RequestMapping("profile") 3public class MessageController { 4 5 @Autowired 6 UserRepository userRepository; 7 @Autowired 8 MessageReposioty messageRepository; 9 10 @ModelAttribute 11 public MessageForm messageForm() { 12 return new MessageForm(); 13 } 14 15 @GetMapping("/{userId}/message") 16 String showMessage(@PathVariable("userId") Integer userId, 17 Model model) { 18 User senderUser = userRepository.findById(userId).orElse(null); 19 List<Message> recieveMessage = messageRepository.findByReceiverUser_UserId(userId); 20 model.addAttribute("recieveMessage",recieveMessage); 21 model.addAttribute("senderUser",senderUser); 22 return "profile/message"; 23 } 24 25 //送信時の処理 26 @PostMapping("/{userId}/message") 27 String sendMessage(@Validated MessageForm messageForm, 28 @AuthenticationPrincipal LoginUserDetails userDetails, 29 @PathVariable("userId") Integer userId, 30 Model model) { 31 User senderUser = userDetails.getUser(); 32 User receiverUser = userRepository.findById(userId).orElse(null); 33 User senderUser = userDetails.getUser(); 34 User receiverUser = userRepository.findById(userId).orElse(null); 35 int senderUserId = senderUser.getUserId(); 36 int receiverUserId = receiverUser.getUserId(); 37 String messageContent = messageForm.getMessageContent(); 38 //ここでinsertを実行 39 messageRepository.sendMessage(senderUserId, receiverUserId, messageContent); 40 return "redirect:{userId}/message"; 41 } 42} 43
##HTML
html
1<!DOCTYPE html> 2<html xmlns:th="http://www.thymeleaf.org" 3 xmlns:sec="http://www.thymeleaf.org/extras/spring-security"> 4<head> 5<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 6<title>Insert title here</title> 7</head> 8<body th:with="user = ${#authentication.principal.user}"> 9 <h1>メッセージ</h1> 10 <p th:text="${senderUser.userName}+'さんへメッセージを送る'"></p> 11 <form th:action="@{'/profile/'+${senderUser.userId}+'/message'}" th:object="${messageForm}"> 12 <textarea placeholder="メッセージを入力してください" th:field="*{messageContent}"> 13 </textarea> 14 <input type="submit"> 15 </form> 16</body> 17</html>
#作成したテーブル
sql
1 2--ユーザーテーブル-- 3CREATE TABLE IF NOT EXISTS user( 4 user_id INTEGER AUTO_INCREMENT, 5 user_name VARCHAR(12) NOT NULL, 6 PRIMARY KEY(user_id); 7) ENGINE=INNODB DEFAULT CHARSET=utf8; 8 9--メッセージテーブル-- 10CREATE TABLE IF NOT EXISTS message( 11 message_id BIGINT AUTO_INCREMENT NOT NULL, 12 sender_user_id INTEGER NOT NULL, 13 receiver_user_id INTEGER NOT NULL, 14 message_content VARCHAR(300), 15 message_time datetime DEFAULT CURRENT_TIMESTAMP, 16 PRIMARY KEY(message_id), 17 FOREIGN KEY (sender_user_id) 18 REFERENCES user(user_id) 19 ON DELETE CASCADE, 20 FOREIGN KEY (receiver_user_id) 21 REFERENCES user(user_id) 22 ON DELETE CASCADE 23) ENGINE=INNODB DEFAULT CHARSET=utf8; 24 25
回答2件
あなたの回答
tips
プレビュー