阅读本文之前,首先请基于SpringBoot创建一个Web项目,参考文章http://www.jianshu.com/p/157eb1ab8524
技术框架
- SpringBoot
- Spring Data JPA
- H2 DataBase
- Maven
开发过程
1.在pom.xml中继续添加jpa和h2的依赖,使用内嵌数据库h2,不需要设置任何datasource属性,但是每次重启数据库都会被重置,一般用作演示最好不过了。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
2.创建实体Person.java,实体类一般是通过myeclipse的hibernate插件反转功能生成的,或者其他的一些方式,不通的方式生成的实体类略有差别。
@Entity
public class Person implements java.io.Serializable {
private static final long serialVersionUID = 18723482374628374L;
private Long id;
private String name;
private int age;
public Person(){
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Id
@GeneratedValue(strategy = GenerationTYpe.AUTO)
@Column(name= "id" unique = true, nullable = false)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
/*省略剩余的get set*/
}
3.创建PersonRespository.java
public interface PersonRespository extends JpaRepository<Person, Long> {
Person findByName(String name);
Person findByNameAndAge(String name, Integer age);
@Query("from Person p where p.name=:name")
Person findPerson(@Param("name")
String name);
}
4.创建PersonController.java
@Controller
@RequestMapping("/person")
public class PersonController {
@Autowired
private PersonRespository personRespository;
@RequestMapping("/list")
public ModelAndView list() {
ModelAndView view = new ModelAndView();
List<Person> plist = personRespository.findAll();
view.addObject("plist", plist);
view.setViewName("person/list");
return view;
}
@RequestMapping("/add")
public String add() {
Person p = new Person();
Random r = new Random();
p.setAge(r.nextInt(50));
p.setName("shu" + r.nextInt(50));
personRespository.save(p);
return "forward:/person/list";
}
}
5.在src/main/resources/templates/person/下创建list.html
<!DOCTYPE HTML>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title></title>
</head>
<body>
<table border="1">
<tbody>
<tr>
<th>id</th>
<th>name</th>
<th>age</th>
</tr>
<tr th:each="item,iterStat:${plist}">
<th th:text="${item.id}"></th>
<th th:text="${item.name}"></th>
<th th:text="${item.age}"></th>
</tr>
</tbody>
</table>
</body>
</html>
6.运行方式,启动SpringBoot的主函数,Application.java的main函数
访问http://localhost:8080/myweb/person/add/ ,便可以看到运行结果
网友评论