#springBootでDBに保存する方法
プロフィール編集画面より情報を入力してUserへ情報を保存をしたいのですが、
Userの持つRegionの情報をどのように保存するのが適切でしょうか?
以下のように自分で試してはみたのですが、うまくはいきませんでした。
おそらくはControllerでの処理方法が誤っているのですが、試行錯誤してみましたがうまくいきませんでしたのでアドバイスをいただけると幸いです。
地域テーブルにはidと都道府県情報が既に入っています。
java
1//ゲッターセッターは略 2@Entity 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 @GeneratedValue(strategy=GenerationType.IDENTITY) 9 @Column(name="user_id") 10 private int userId; 11 12 private Integer age; 13 14 private String gender; 15 16 @Column(name="mail_address") 17 private String mailAddress; 18 19 private String password; 20 21 @Column(name="profile_image") 22 private String profileImage; 23 24 @Column(name="self_introduction") 25 private String selfIntroduction; 26 27 @Column(name="user_name") 28 private String userName; 29 30 @ManyToOne 31 @JoinColumn(name="region_id") 32 private Region region; 33
java
1@Entity 2@NamedQuery(name="Region.findAll", query="SELECT r FROM Region r") 3public class Region implements Serializable { 4 private static final long serialVersionUID = 1L; 5 6 @Id 7 @GeneratedValue(strategy=GenerationType.IDENTITY) 8 @Column(name="region_id") 9 private int regionId; 10 11 @Column(name="region_name") 12 private String regionName; 13 14 //bi-directional many-to-one association to User 15 @OneToMany(mappedBy="region") 16 private List<User> users; 17 18 public Region() { 19 } 20 21 public int getRegionId() { 22 return this.regionId; 23 } 24 25 public void setRegionId(int regionId) { 26 this.regionId = regionId; 27 } 28 29 public String getRegionName() { 30 return this.regionName; 31 } 32 33 public void setRegionName(String regionName) { 34 this.regionName = regionName; 35 } 36 37 public List<User> getUsers() { 38 return this.users; 39 } 40 41 public void setUsers(List<User> users) { 42 this.users = users; 43 } 44 45 public User addUser(User user) { 46 getUsers().add(user); 47 user.setRegion(this); 48 49 return user; 50 } 51 52 public User removeUser(User user) { 53 getUsers().remove(user); 54 user.setRegion(null); 55 56 return user; 57 } 58 59}
java
1//getter,setterは略 2public class UserProfileForm implements Serializable{ 3 private static final long serialVersionUID = 1L; 4 5 @NotEmpty(message="ユーザー名を入力してください") 6 @Size(min=1,max=12,message="ユーザー名の長さが不適切です") 7 @Pattern(regexp="[a-zA-Z0-9亜-熙ぁ-んァ-ヶ#$@%&*._^(){}-]+",message="不適切な文字が含まれています") 8 private String userName; 9 10 @Range(min=0 , max= 100,message="0から100までの数値を入力してください" ) 11 private Integer age; 12 13 private String gender; 14 15 @Size(max=300,message="自己紹介は300字が最大です") 16 private String selfIntroduction; 17 private String profileImage; 18 private Region region;
java
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 <table> 11 <form th:action="@{'/profile/edit/'+${user.userId}}" th:object="${userProfileForm}" method="post"> 12 <tr><td><label for="userName">ユーザ名:</label></td> 13 <td><input type="text" name="userName" th:attr="value = ${user.userName}" th:errorclass="err"/> 14 <div class="err" th:each="err,st : ${#lists.sort(#fields.errors('userName'))}" 15 th:text="${err}" th:if="${st.index == 0}">エラーメッセージが出力されます</div> 16 </td> 17 </tr> 18 <tr> 19 <td><label for="gender">性別</label></td> 20 <td><input type="radio" name="gender" th:field="*{gender}" id="radioA" value="男性"/> 21 <label for="radioA">男性</label> 22 <input type="radio" name="gender" th:field="*{gender}" id="radioB" value="女性"/> 23 <label for="radioB">女性</label> 24 </td> 25 </tr> 26 <tr> 27 <td><label for="age">年齢:</label></td> 28 <td><select id="age" name="age" th:errorclass="err"> 29 <option th:each="i : ${#numbers.sequence(0, 100)}" 30 th:value="${i}" th:text="${i}" th:selected="${i==user.age}">歳 31 </option> 32 </select> 33 <div class="err" th:each="err,st : ${#lists.sort(#fields.errors('age'))}" 34 th:text="${err}" th:if="${st.index == 0}">エラーメッセージが出力されます</div> 35 </td> 36 </tr> 37 <tr> 38 <tr> 39 <td><label for="region">地域:</label></td> 40 <td><select id="region" name="region"> 41 <option th:each="region : ${regionList}" 42 th:value="${region}" th:text="${region.regionName}" > 43 </option> 44 </select> 45 </tr> 46 <tr> 47 <tr> 48 <td><label for="selfIntroduction">自己紹介</label></td> 49 <td><textarea name="selfIntroduction" th:errorclass="err" th:text="${user.selfIntroduction}"> 50 </textarea> 51 <div class="err" th:each="err,st : ${#lists.sort(#fields.errors('selfIntroduction'))}" 52 th:text="${err}" th:if="${st.index == 0}">エラーメッセージが出力されます</div> 53 </td> 54 </tr> 55 <tr> 56 <td><a th:href="@{'/profile/'+${user.userId}}">プロフィール画面に戻る</a></td> 57 <td> 58 <input type="submit" value="プロフィールを変更" /> 59 </td> 60 </tr> 61 </form> 62 </table> 63 64</body> 65</html>
java
1 2@Controller 3public class ProfileController { 4 @Autowired 5 UserService userService; 6 @Autowired 7 UserRepository userRepository; 8 @Autowired 9 RegionRepository regionRepository; 10 11 12 13 @GetMapping("/profile/edit/{userId}") 14 String showProfileEdit(@PathVariable("userId") Integer userId, 15 Model model) { 16 User user = userRepository.findById(userId).orElseGet(null); 17 List<Region> regionList = regionRepository.findAll(); 18 model.addAttribute("regionList",regionList); 19 model.addAttribute("user",user); 20 return "profile/userEdit"; 21 } 22 23 @PostMapping(value="/profile/edit/{userId}") 24 String create(@Validated UserProfileForm userForm, 25 BindingResult bindingResult, 26 @PathVariable("userId") Integer userId, 27 Model model) { 28 if(bindingResult.hasErrors()) { 29 return "profile/userEdit"; 30 } 31 User user = userRepository.findById(userId).orElseGet(null); 32 user.setUserName(userForm.getUserName()); 33 user.setGender(userForm.getGender()); 34 user.setAge(userForm.getAge()); 35 user.setRegion(userForm.getRegion()); 36 user.setSelfIntroduction(userForm.getSelfIntroduction()); 37 userService.update(user); 38 return "redirect:/profile/{userid}"; 39 } 40 41 42} 43
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。