一.SpringData
1. SpringData特点
SpringData为我们提供使用统一的API来对各种数据库,对数据访问层进行操作;API包含了CRUD(创建,获取,更新,删除),查询,排序和分页的相关操作。
2.统一的Repository接口
Repository<T,ID extends Serializable>;统一接口
RevisionRepository<T,ID extends Serializable,N extends Number & Comparable<N>>;基于乐观锁机制
CrudRepository<T,ID extends Serializable>;基本CRUD操作
PagingAndSortingRepository<T,ID extends Serializable>;基本CRUD及分页
二.SpringData JPA开发步骤
1:springboot选择1.5版本
2.选中Web,JPA,Mysql,JDBC模块
3. JPA-ORM(Object Relational Map对象关系映射) 编写一个实体类(bean)和数据表进行映射,并且配置好映射关系
//配置JPA注解配置映射关系
@Entity //告诉JPA这时一个实体类
@Table(name='tbl_user') //指定和哪个表对应
public class User
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@Column(name="lastname",length=50)
private String lastName;
@Column
private String email;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
4. 编写一个Dao接口来操作实体类对应的数据表(Repository)
import com.lulu.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
//继承JpaRepository来完成对数据库的操作
public interface UserRepository extends JpaRepository<User,Integer>{
}
5.基本的配置
#Mysql属性配置文件,Spring-boot系统配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/jdbcdb
spring.datasource.username=root
spring.datasource.password=12345678
#配置自动建表:updata:没有表新建,有表更新操作,控制台显示建表语句
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
6. 运行app。mysql自动创建tbl_user
7.添加获取和新增功能
@RestController
public class UserController {
@Autowired
UserRepository userRepository;
@GetMapping("/user/{id}")
public User getUser(@PathVariable("id") Integer i){
User user=userRepository.findOne(i);
}
@GetMapping("/user")
public User insertUser(User user){
User save=userRepository.save(user);
return save;
}
}
8. 运行
输入:http://localhost:8080/user?lastName=aa&email=cc
输入:http://localhost:8080/user?userName=bb&email=dd