我试图弄清楚如何使用SpringMVC和hibernate从表单中持久保存用户输入。例如,我正在遵循本指南:
基本上它显示了一个控制器:
@Controller
public class GreetingController {
@RequestMapping(value="/greeting", method= RequestMethod.GET)
public String greetingForm(Model model) {
model.addAttribute("greeting", new Greeting());
return "greeting";
}
@RequestMapping(value="/greeting", method=RequestMethod.POST)
public String greetingSubmit(@ModelAttribute Greeting greeting, Model model) {
model.addAttribute("greeting", greeting);
return "result";
}
}
一个Greeting.java,我为JPA添加了一些注释,但我不确定该表单是否有自己的对象,我需要为问候实体创建一个单独的对象。
@Entity
@Table(name = "greeting")
public class Greeting {
@Id
@GeneratedValue
@Column(name = "greeting_id")
private long id;
@Column(name = "greeting_content")
private String content;
public long getId() {
return id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
以及用于显示的html和仅具有starter-web和百里香叶依赖性的pom ......
我还创建了一个简单的存储库,它扩展了CrudRepository,以及目前为空的服务层。
我想弄清楚的是当单击提交按钮时如何使用hibernate将问候字段持久保存到数据库。任何帮助都会很棒,谢谢。
答案 0 :(得分:1)
Spring CrudRepository
提供save()
方法。测试代码和Spring / Entity配置的简单方法可以尝试这样:
@Controller
public class GreetingController {
//Autowire your CrudRepo of Greeting
@Autowired
GreetingRepository repository;
@RequestMapping(value="/greeting", method= RequestMethod.GET)
public String greetingForm(Model model) {
model.addAttribute("greeting", new Greeting());
//create a new Greeting() Object and set your values to it.
//create a constructor if the values are not that much.
Greeting greeting = new Greeting();
greeting.setContent(yourContent);
repository.save(greeting);
return "greeting";
}
@RequestMapping(value="/greeting", method=RequestMethod.POST)
public String greetingSubmit(@ModelAttribute Greeting greeting, Model model) {
model.addAttribute("greeting", greeting);
//create a new Greeting() Object and set your values to it.
//create a constructor if the values are not that much.
Greeting greeting = new Greeting();
greeting.setContent(yourContent);
repository.save(greeting);
return "result";
}
}
默认情况下,CrudRepository接口应该如下所示:
@Repository
public interface GreetingRepository extends CrudRepository<Greeting, Serializable>{
}