JPA是Java Persistence API的简称,中文名Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。
通过@Entity 表明是一个映射的实体类, @Id表明id, @GeneratedValue 字段自动生成
package sample.data.jpa.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "t_user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
private String name;
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;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
public User(Long id, String name) {
super();
this.id = id;
this.name = name;
}
public User() {
}
}
数据访问层,通过编写一个继承自 JpaRepository 的接口就能完成数据访问,其中包含了几本的单表查询的方法,非常的方便。值得注意的是,这个User对象名,而不是具体的表名,另外Interger是主键的类型,一般为Integer或者Long
package sample.data.jpa.service;
import org.springframework.data.repository.CrudRepository;
import sample.data.jpa.domain.User;
public interface UserRepository extends CrudRepository {
User findByName(String name);
}
在这个例子中我简略了service层的书写,在实际开发中,不可省略。新写一个controller,示例如下:
package sample.data.jpa.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sample.data.jpa.domain.User;
import sample.data.jpa.service.UserRepository;
@Controller
public class SampleController {
@Autowired
private UserRepository userRepository;
@GetMapping("/")
@ResponseBody
public String helloWorld() {
userRepository.deleteAll();
User user = new User();
user.setName("zhangsan");
userRepository.save(user);
user = userRepository.findByName("zhangsan");
System.out.println("name:"+user.getName());
return "Hello World";
}
}
测试: 打开浏览器输入 http://localhost:8080/
源码下载:https://gitee.com/zhmal/spring-boot-samples/tree/master/spring-boot-sample-data-jpa
参考资料:
http://projects.spring.io/spring-data-jpa/
https://spring.io/guides/gs/accessing-data-jpa/