目录
更新信息:
更新时间 | 更新内容 |
2020-03-25 | 更新了整个页面的排版,更新注意事项,更新了代码 |
前言:
最近使用了Spring data JPA来完成数据访问层的实现,JPA提供了一些封装方法供我们调用,非常方便,小编目前用的是SpringBoot项目。
步骤:
1.配置pom.xml
- a.配置Spring-data-JPA
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.10.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
- b.配置mysql连接
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
2.配置application.properties
# 数据源配置
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8
spring.datasource.username=test
spring.datasource.password=123123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#JPA (JpaBaseConfiguration, HibernateJpaAutoConfiguration)
spring.data.jpa.repositories.enabled=true
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.DefaultNamingStrategy
spring.jpa.generate-ddl=false
spring.jpa.show-sql=true
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.DefaultNamingStrategy
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
3.实体类
@Entity
@Table(name = "bos_customer", schema = "dbo", catalog = "userdb")
public class BosCustomerModel {
private int id;
private String cname;
private String openId;
@Id
@Column(name = "id")
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Basic
@Column(name = "cname")
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
@Basic
@Column(name = "openId")
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BosCustomerModel that = (BosCustomerModel) o;
return id == that.id &&
Objects.equals(cname, that.cname) &&
Objects.equals(openId, that.openId);
}
@Override
public int hashCode() {
return Objects.hash(id, cname, openId);
}
}
大家看我这个实体类是不是觉得很繁琐? 其实有一个插件可以帮助我们简化代码,有一些常用的注解
@Data @Getter/@Setter @ToString @Builder @Slf4j 等等,这篇文章不做具体的展开。
定义JPA的写法:
4. CustomerJPARespository类
public interface CustomerJPARepository extends JpaRepository<BosCustomerModel, Integer>, JpaSpecificationExecutor<BosCustomerModel> {
@Query("select count(*) from BosCustomerModel where openId=?1")
int findBosCustomerModelByOpenId(String openId);
}
同时还可以定义Repository
package com.test.model.Repository;
import com.test.model.BosCustomerModel;
import org.springframework.data.repository.CrudRepository;
/**
* @Author tanghh
* @Date 2020/3/25 14:51
*/
public interface BosCustomerRepository extends CrudRepository<BosCustomerModel, Long> {
}
5.WeiService
public interface WeiService {
void insertCustomer(String openId,String cname);
BosCustomerModel findBosCustomerModelByOpenId(String openId);
}
6.WeiServiceImpl
@Service("weiServiceImpl")
public class WeiServiceImpl implements WeiService {
@Autowired
private CustomerJPARepository customerJPARepository;
@Transactional
@Override
public void insertCustomer(String openId,String cname){
BosCustomerModel model=new BosCustomerModel();
model.setCname(cname);
model.setOpenId(openId);
int row=customerJPARepository.findBosCustomerModelByOpenId(openId);
if(row==0){
customerJPARepository.saveAndFlush(model);
}
}
7.WeiController
@RequestMapping(value="/insertData",method = RequestMethod.POST)
public String insertCustomer(@RequestParam("cname") String cname){
//第一次输入的时候将名字和openId保存到客户表中
weiService.insertCustomer(WeiXinController.OPENID,cname);
return "sucess";
}
8.补充一下springJPA的用法:
1.增加:
Bos_customerModel customer=new Bos_customerModel();
customer.setId(1);
customer.setCname("小王");
保存单个对象:
customerJPARespository.save(customerModel);
保存或更新:
customerJPARespository.saveAndFlush(customerModel);
保存多个对象:
List<customerModel> customers=new ArrayList<customerModel>();
customers.add(customer);
customerJPARespository.save(customers);
2.删除
删除都是按照主键id来删除的,区别是多条sql和单条sql
删除单条:
customerJPARespository.delete(1);
删除全部(删除全部,先findALL查找出来,再一条一条删除,最后提交事务):
customerJPARespository.deleteAll();
删除全部,一条sql
customerJPARespository.deleteAllInBatch();
删除集合,一条一条删除
List<customerModel> customers=new ArrayList<customerModel>();
CustomerModel customer=new CustomerModel();
customer.setId(1);
customer.setCname("gag);
customers.add(customer);
customerJPARespository.delete(customers);
删除集合,一条sql,拼接or
customerJPARespository.deleteInBatch(customers);
3.修改 (更新也是按照主键来更新)
CustomerModel customer=new CustomerModel();
customer.setId(1);
customer.setCname("gag);
customerJPARespository.saveAndFlush(customer);
注意事项:
- 1.一般情况添加数据我用的是save() 方法,而saveAndFlush() 这个方法什么时候用到呢,比如我现在添加一条数据到数据库中,我现在要立马拉到添加的这条数据的 id ,这个时候就可以使用 saveAndFlush() 这个方法。
- 2.关于删除数据的话,我们系统目前做的是逻辑删除,不是真正的将当前这条数据从数据库中删掉,只是改变当前数据的一个状态,进行的是一个查询操作。
- 3.查询的话,可以调用JPA的findAll() 方法。
- 4.我刚写这篇文章的时候在18年,我在2020对这篇文章内容进行了升级,其中 我最开始的使用JPARepository ,在2020年的时候我发现DruidRepository 也可以使用,俩者有区别。他们存在继承关系:
PagingAndSortingRepository 继承 CrudRepository JpaRepository 继承 PagingAndSortingRepository
也就是说, CrudRepository 提供基本的增删改查;PagingAndSortingRepository 提供分页和排序方法; JpaRepository 提供JPA需要的方法。