- jpa依赖
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
- domain类
package com.hikvison.test.pgtest.entity;
import java.io.Serializable;
import javax.persistence.*;
import lombok.Data;
/**
* 测试pg数据库的一些性能
* 1. 主键自增
* 2. 高并发锁机制
*
* @date 2018年8月28日 下午7:23:17
*/
@Data
@Entity
@Table(name="test_pg_wushan")
public class TestEntity implements Serializable {
private static final long serialVersionUID = 2672553622864930471L;
@Id
@SequenceGenerator(sequenceName="test_sequence", name="abc" )
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="abc")
@Column(name="id")
private Integer id;
@Column(name="test_name")
private String name;
@Transient
private Integer version;
}
- repository类
package com.hikvison.test.pgtest.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.hikvison.test.pgtest.entity.TestEntity;
public interface TestRepository extends JpaRepository<TestEntity, Long> {
}
- controller类
package com.hikvison.test.pgtest.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.hikvison.test.pgtest.entity.TestEntity;
import com.hikvison.test.pgtest.repository.TestRepository;
/**
* 测试用contro
*
* @date 2018年8月28日 下午7:35:25
*/
@Controller
public class TeatController {
@Autowired
TestRepository r ;
@RequestMapping("/")
@ResponseBody
public String test1(){
return "hello";
}
@RequestMapping("/save")
@ResponseBody
public String test2(){
TestEntity te = new TestEntity();
te.setName(System.currentTimeMillis()+"");
r.save(te);
return "success";
}
}
增加数据库链接信息,数据库驱动,spring boot依赖,启动运行即可.
实现主键自增解析:
- 在domain类中,使用了
@Id
@SequenceGenerator(sequenceName="test_sequence", name="abc" )
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="abc")
@Column(name="id")
private Integer id;
其中:
1) test_sequence:数据库中的序列名,如果不存在,会创建,初始值为1,步长为1(postgresql和oracle一样,依赖序列实现主键的自增)
2)@SequenceGenerator,注意使用此注解声明序列.
有个问题:
我测试的表主键编号从50开始的,没弄清楚为什么.