Новичок в программировании и все еще учусь, поэтому заранее извиняюсь за мои глупые / странные вопросы и не обязательно сразу понимаю!
Я пытаюсь установить отношение «многие ко многим» между классами Аватара и Дисциплины , но что-то идет не так, как приложение не запускается, и это должен быть контроллер, который вызывает сбой запуска.
Аватар. java
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
@Entity
public class Avatar {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@NotBlank(message = "Name cannot be blank!")
@Size(min=3, max=19, message = "Name must be from 3 to 19 characters and must be composed entirely of letters and (optional) spaces.")
private String name;
@NotBlank(message = "Creation date cannot be blank!")
@Size(min=10, max=10, message = "Date must be in DD.MM.YYYY format.")
private String cdate;
@NotBlank(message = "Game account cannot be blank!")
@Size(min=8, max=32, message = "Game account is a combination of your player name (3 to 27 characters), a dot (.) and four-digit number.")
private String account;
@ManyToOne
@JoinColumn(name = "genderid")
private Gender gender;
@ManyToOne
@JoinColumn(name = "raceid")
private Race race;
@ManyToOne
@JoinColumn(name = "professionid")
private Profession profession;
@ManyToOne
@JoinColumn(name = "levelid")
private Level level;
public Avatar() {}
public Avatar(String name, String cdate, String account) {
super();
this.name = name;
this.cdate = cdate;
this.account = account;
}
public Avatar(String name, Gender gender, Race race, Profession profession, Level level, String cdate, String account) {
super();
this.name = name;
this.gender = gender;
this.race = race;
this.profession = profession;
this.level = level;
this.cdate = cdate;
this.account = account;
}
@ManyToMany(cascade = CascadeType.MERGE)
@JoinTable(name = "avatar_discipline", joinColumns = { @JoinColumn(name = "avatarid") }, inverseJoinColumns = { @JoinColumn(name = "disciplineid") })
public Set<Discipline> getDisciplines() {
return this.disciplines;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public Race getRace() {
return race;
}
public void setRace(Race race) {
this.race = race;
}
public Profession getProfession() {
return profession;
}
public void setProfession(Profession profession) {
this.profession = profession;
}
public Level getLevel() {
return level;
}
public void setLevel(Level level) {
this.level = level;
}
public String getCdate() {
return cdate;
}
public void setCdate(String cdate) {
this.cdate = cdate;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
@Override
public String toString() {
return "Avatar [id=" + id + ", name=" + name + ", cdate=" + cdate + ", account=" + account + "]";
}
}
Дисциплина. java
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@Entity
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Discipline {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long disciplineid;
private String name;
@ManyToMany(mappedBy = "disciplines")
@JsonIgnore
private Set<Avatar> avatars;
public Discipline() {}
public Discipline(String name) {
this.name = name;
}
public Long getDisciplineid() {
return disciplineid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Avatar> getAvatars() {
return avatars;
}
public void setAvatars(Set<Avatar> avatars) {
this.avatars = avatars;
}
}
Контроллер. java
import java.util.List;
import java.util.Optional;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import fi.markoairisto.gw2db.domain.Avatar;
import fi.markoairisto.gw2db.domain.AvatarRepository;
import fi.markoairisto.gw2db.domain.Discipline;
import fi.markoairisto.gw2db.domain.DisciplineRepository;
import fi.markoairisto.gw2db.domain.GenderRepository;
import fi.markoairisto.gw2db.domain.LevelRepository;
import fi.markoairisto.gw2db.domain.ProfessionRepository;
import fi.markoairisto.gw2db.domain.RaceRepository;
@Controller
public class AvatarController {
@Autowired
private AvatarRepository avatarRepository;
@Autowired
private GenderRepository genderRepository;
@Autowired
private RaceRepository raceRepository;
@Autowired
private ProfessionRepository professionRepository;
@Autowired
private LevelRepository levelRepository;
@Autowired
private DisciplineRepository disciplineRepository;
@RequestMapping(value = {"/login", "/"})
public String login() {
return "login";
}
@RequestMapping(value = "/myavatars")
public String avatarListing(Model model) {
model.addAttribute("avatars", avatarRepository.findAll());
return "myavatars";
}
@RequestMapping("/myavatars")
public String index(Model model) {
List<Avatar> avatars = (List<Avatar>) avatarRepository.findAll();
model.addAttribute("avatars", avatars);
return "myavatars";
}
@RequestMapping(value = "/add")
public String avatarAddition(Model model) {
model.addAttribute("avatar", new Avatar());
model.addAttribute("genders", genderRepository.findAll());
model.addAttribute("races", raceRepository.findAll());
model.addAttribute("professions", professionRepository.findAll());
model.addAttribute("levels", levelRepository.findAll());
return "addavatar";
}
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String avatarSaving(@Valid Avatar avatar, BindingResult bindingResult, Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("genders", genderRepository.findAll());
model.addAttribute("races", raceRepository.findAll());
model.addAttribute("professions", professionRepository.findAll());
model.addAttribute("levels", levelRepository.findAll());
return "addavatar";
}
avatarRepository.save(avatar);
return "redirect:myavatars";
}
@PreAuthorize("hasAuthority('ADMIN')")
@RequestMapping(value = "/editavatar/{id}", method = RequestMethod.GET)
public String avatarEditing(@PathVariable("id") Long editId, Model model) {
model.addAttribute("editAvatar", avatarRepository.findById(editId).get());
model.addAttribute("genders", genderRepository.findAll());
model.addAttribute("races", raceRepository.findAll());
model.addAttribute("professions", professionRepository.findAll());
model.addAttribute("levels", levelRepository.findAll());
return "editavatar";
}
@PreAuthorize("hasAuthority('ADMIN')")
@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
public String avatarDeletion(@PathVariable("id") Long delId, Model model) {
avatarRepository.deleteById(delId);
return "redirect:../myavatars";
}
@PreAuthorize("hasAuthority('ADMIN')")
@RequestMapping(value = "adddiscipline/{id}", method = RequestMethod.GET)
public String addDiscipline(@PathVariable("id") Long avatarId, Model model) {
model.addAttribute("disciplines", disciplineRepository.findAll());
model.addAttribute("avatar", avatarRepository.findById(avatarId));
return "adddiscipline";
}
@PreAuthorize("hasAuthority('ADMIN')")
@RequestMapping(value="/avatar/{id}/disciplines", method=RequestMethod.GET)
public String disciplineAddition(@PathVariable Long id, @RequestParam Long disciplineId, Model model) {
Discipline discipline = disciplineRepository.findById(disciplineId);
Avatar avatar = avatarRepository.findById(id);
if (avatar != null) {
if (!avatar.hasDiscipline(discipline)) {
avatar.getDisciplines().add(discipline);
}
avatarRepository.save(avatar);
model.addAttribute("avatar", disciplineRepository.findById(id));
model.addAttribute("disciplines", disciplineRepository.findAll());
return "redirect:/myavatars";
}
return "redirect:/myavatars";
}
@RequestMapping(value = "getavatars", method = RequestMethod.GET)
public @ResponseBody List<Avatar> getAvatars() {
return (List<Avatar>)avatarRepository.findAll();
}
}
Я предоставлю больше информации, если потребуется! Спасибо за любой полезный совет, который поможет мне решить проблему!